PackageManagerService.java revision f8bb2445ff28d64d12d81d91539bb419f69e7874
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.PARSE_IS_OEM;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108
109import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
110
111import android.Manifest;
112import android.annotation.IntDef;
113import android.annotation.NonNull;
114import android.annotation.Nullable;
115import android.app.ActivityManager;
116import android.app.AppOpsManager;
117import android.app.IActivityManager;
118import android.app.ResourcesManager;
119import android.app.admin.IDevicePolicyManager;
120import android.app.admin.SecurityLog;
121import android.app.backup.IBackupManager;
122import android.content.BroadcastReceiver;
123import android.content.ComponentName;
124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.IIntentReceiver;
127import android.content.Intent;
128import android.content.IntentFilter;
129import android.content.IntentSender;
130import android.content.IntentSender.SendIntentException;
131import android.content.ServiceConnection;
132import android.content.pm.ActivityInfo;
133import android.content.pm.ApplicationInfo;
134import android.content.pm.AppsQueryHelper;
135import android.content.pm.AuxiliaryResolveInfo;
136import android.content.pm.ChangedPackages;
137import android.content.pm.ComponentInfo;
138import android.content.pm.FallbackCategoryProvider;
139import android.content.pm.FeatureInfo;
140import android.content.pm.IDexModuleRegisterCallback;
141import android.content.pm.IOnPermissionsChangeListener;
142import android.content.pm.IPackageDataObserver;
143import android.content.pm.IPackageDeleteObserver;
144import android.content.pm.IPackageDeleteObserver2;
145import android.content.pm.IPackageInstallObserver2;
146import android.content.pm.IPackageInstaller;
147import android.content.pm.IPackageManager;
148import android.content.pm.IPackageManagerNative;
149import android.content.pm.IPackageMoveObserver;
150import android.content.pm.IPackageStatsObserver;
151import android.content.pm.InstantAppInfo;
152import android.content.pm.InstantAppRequest;
153import android.content.pm.InstantAppResolveInfo;
154import android.content.pm.InstrumentationInfo;
155import android.content.pm.IntentFilterVerificationInfo;
156import android.content.pm.KeySet;
157import android.content.pm.PackageCleanItem;
158import android.content.pm.PackageInfo;
159import android.content.pm.PackageInfoLite;
160import android.content.pm.PackageInstaller;
161import android.content.pm.PackageManager;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageManagerInternal;
164import android.content.pm.PackageParser;
165import android.content.pm.PackageParser.ActivityIntentInfo;
166import android.content.pm.PackageParser.PackageLite;
167import android.content.pm.PackageParser.PackageParserException;
168import android.content.pm.PackageStats;
169import android.content.pm.PackageUserState;
170import android.content.pm.ParceledListSlice;
171import android.content.pm.PermissionGroupInfo;
172import android.content.pm.PermissionInfo;
173import android.content.pm.ProviderInfo;
174import android.content.pm.ResolveInfo;
175import android.content.pm.ServiceInfo;
176import android.content.pm.SharedLibraryInfo;
177import android.content.pm.Signature;
178import android.content.pm.UserInfo;
179import android.content.pm.VerifierDeviceIdentity;
180import android.content.pm.VerifierInfo;
181import android.content.pm.VersionedPackage;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.DisplayMetrics;
233import android.util.EventLog;
234import android.util.ExceptionUtils;
235import android.util.Log;
236import android.util.LogPrinter;
237import android.util.MathUtils;
238import android.util.PackageUtils;
239import android.util.Pair;
240import android.util.PrintStreamPrinter;
241import android.util.Slog;
242import android.util.SparseArray;
243import android.util.SparseBooleanArray;
244import android.util.SparseIntArray;
245import android.util.TimingsTraceLog;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.PermissionsState.PermissionState;
286import com.android.server.pm.Settings.DatabaseVersion;
287import com.android.server.pm.Settings.VersionInfo;
288import com.android.server.pm.dex.DexManager;
289import com.android.server.pm.dex.DexoptOptions;
290import com.android.server.pm.dex.PackageDexUsage;
291import com.android.server.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    public static final int REASON_SHARED = 6;
581
582    public static final int REASON_LAST = REASON_SHARED;
583
584    /** All dangerous permission names in the same order as the events in MetricsEvent */
585    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
586            Manifest.permission.READ_CALENDAR,
587            Manifest.permission.WRITE_CALENDAR,
588            Manifest.permission.CAMERA,
589            Manifest.permission.READ_CONTACTS,
590            Manifest.permission.WRITE_CONTACTS,
591            Manifest.permission.GET_ACCOUNTS,
592            Manifest.permission.ACCESS_FINE_LOCATION,
593            Manifest.permission.ACCESS_COARSE_LOCATION,
594            Manifest.permission.RECORD_AUDIO,
595            Manifest.permission.READ_PHONE_STATE,
596            Manifest.permission.CALL_PHONE,
597            Manifest.permission.READ_CALL_LOG,
598            Manifest.permission.WRITE_CALL_LOG,
599            Manifest.permission.ADD_VOICEMAIL,
600            Manifest.permission.USE_SIP,
601            Manifest.permission.PROCESS_OUTGOING_CALLS,
602            Manifest.permission.READ_CELL_BROADCASTS,
603            Manifest.permission.BODY_SENSORS,
604            Manifest.permission.SEND_SMS,
605            Manifest.permission.RECEIVE_SMS,
606            Manifest.permission.READ_SMS,
607            Manifest.permission.RECEIVE_WAP_PUSH,
608            Manifest.permission.RECEIVE_MMS,
609            Manifest.permission.READ_EXTERNAL_STORAGE,
610            Manifest.permission.WRITE_EXTERNAL_STORAGE,
611            Manifest.permission.READ_PHONE_NUMBERS,
612            Manifest.permission.ANSWER_PHONE_CALLS);
613
614
615    /**
616     * Version number for the package parser cache. Increment this whenever the format or
617     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
618     */
619    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
620
621    /**
622     * Whether the package parser cache is enabled.
623     */
624    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
625
626    final ServiceThread mHandlerThread;
627
628    final PackageHandler mHandler;
629
630    private final ProcessLoggingHandler mProcessLoggingHandler;
631
632    /**
633     * Messages for {@link #mHandler} that need to wait for system ready before
634     * being dispatched.
635     */
636    private ArrayList<Message> mPostSystemReadyMessages;
637
638    final int mSdkVersion = Build.VERSION.SDK_INT;
639
640    final Context mContext;
641    final boolean mFactoryTest;
642    final boolean mOnlyCore;
643    final DisplayMetrics mMetrics;
644    final int mDefParseFlags;
645    final String[] mSeparateProcesses;
646    final boolean mIsUpgrade;
647    final boolean mIsPreNUpgrade;
648    final boolean mIsPreNMR1Upgrade;
649
650    // Have we told the Activity Manager to whitelist the default container service by uid yet?
651    @GuardedBy("mPackages")
652    boolean mDefaultContainerWhitelisted = false;
653
654    @GuardedBy("mPackages")
655    private boolean mDexOptDialogShown;
656
657    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
658    // LOCK HELD.  Can be called with mInstallLock held.
659    @GuardedBy("mInstallLock")
660    final Installer mInstaller;
661
662    /** Directory where installed third-party apps stored */
663    final File mAppInstallDir;
664
665    /**
666     * Directory to which applications installed internally have their
667     * 32 bit native libraries copied.
668     */
669    private File mAppLib32InstallDir;
670
671    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
672    // apps.
673    final File mDrmAppPrivateInstallDir;
674
675    // ----------------------------------------------------------------
676
677    // Lock for state used when installing and doing other long running
678    // operations.  Methods that must be called with this lock held have
679    // the suffix "LI".
680    final Object mInstallLock = new Object();
681
682    // ----------------------------------------------------------------
683
684    // Keys are String (package name), values are Package.  This also serves
685    // as the lock for the global state.  Methods that must be called with
686    // this lock held have the prefix "LP".
687    @GuardedBy("mPackages")
688    final ArrayMap<String, PackageParser.Package> mPackages =
689            new ArrayMap<String, PackageParser.Package>();
690
691    final ArrayMap<String, Set<String>> mKnownCodebase =
692            new ArrayMap<String, Set<String>>();
693
694    // Keys are isolated uids and values are the uid of the application
695    // that created the isolated proccess.
696    @GuardedBy("mPackages")
697    final SparseIntArray mIsolatedOwners = new SparseIntArray();
698
699    /**
700     * Tracks new system packages [received in an OTA] that we expect to
701     * find updated user-installed versions. Keys are package name, values
702     * are package location.
703     */
704    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
705    /**
706     * Tracks high priority intent filters for protected actions. During boot, certain
707     * filter actions are protected and should never be allowed to have a high priority
708     * intent filter for them. However, there is one, and only one exception -- the
709     * setup wizard. It must be able to define a high priority intent filter for these
710     * actions to ensure there are no escapes from the wizard. We need to delay processing
711     * of these during boot as we need to look at all of the system packages in order
712     * to know which component is the setup wizard.
713     */
714    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
715    /**
716     * Whether or not processing protected filters should be deferred.
717     */
718    private boolean mDeferProtectedFilters = true;
719
720    /**
721     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
722     */
723    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
724    /**
725     * Whether or not system app permissions should be promoted from install to runtime.
726     */
727    boolean mPromoteSystemApps;
728
729    @GuardedBy("mPackages")
730    final Settings mSettings;
731
732    /**
733     * Set of package names that are currently "frozen", which means active
734     * surgery is being done on the code/data for that package. The platform
735     * will refuse to launch frozen packages to avoid race conditions.
736     *
737     * @see PackageFreezer
738     */
739    @GuardedBy("mPackages")
740    final ArraySet<String> mFrozenPackages = new ArraySet<>();
741
742    final ProtectedPackages mProtectedPackages;
743
744    @GuardedBy("mLoadedVolumes")
745    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
746
747    boolean mFirstBoot;
748
749    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
750
751    // System configuration read by SystemConfig.
752    final int[] mGlobalGids;
753    final SparseArray<ArraySet<String>> mSystemPermissions;
754    @GuardedBy("mAvailableFeatures")
755    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
756
757    // If mac_permissions.xml was found for seinfo labeling.
758    boolean mFoundPolicyFile;
759
760    private final InstantAppRegistry mInstantAppRegistry;
761
762    @GuardedBy("mPackages")
763    int mChangedPackagesSequenceNumber;
764    /**
765     * List of changed [installed, removed or updated] packages.
766     * mapping from user id -> sequence number -> package name
767     */
768    @GuardedBy("mPackages")
769    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
770    /**
771     * The sequence number of the last change to a package.
772     * mapping from user id -> package name -> sequence number
773     */
774    @GuardedBy("mPackages")
775    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
776
777    class PackageParserCallback implements PackageParser.Callback {
778        @Override public final boolean hasFeature(String feature) {
779            return PackageManagerService.this.hasSystemFeature(feature, 0);
780        }
781
782        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
783                Collection<PackageParser.Package> allPackages, String targetPackageName) {
784            List<PackageParser.Package> overlayPackages = null;
785            for (PackageParser.Package p : allPackages) {
786                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
787                    if (overlayPackages == null) {
788                        overlayPackages = new ArrayList<PackageParser.Package>();
789                    }
790                    overlayPackages.add(p);
791                }
792            }
793            if (overlayPackages != null) {
794                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
795                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
796                        return p1.mOverlayPriority - p2.mOverlayPriority;
797                    }
798                };
799                Collections.sort(overlayPackages, cmp);
800            }
801            return overlayPackages;
802        }
803
804        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
805                String targetPackageName, String targetPath) {
806            if ("android".equals(targetPackageName)) {
807                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
808                // native AssetManager.
809                return null;
810            }
811            List<PackageParser.Package> overlayPackages =
812                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
813            if (overlayPackages == null || overlayPackages.isEmpty()) {
814                return null;
815            }
816            List<String> overlayPathList = null;
817            for (PackageParser.Package overlayPackage : overlayPackages) {
818                if (targetPath == null) {
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                    continue;
824                }
825
826                try {
827                    // Creates idmaps for system to parse correctly the Android manifest of the
828                    // target package.
829                    //
830                    // OverlayManagerService will update each of them with a correct gid from its
831                    // target package app id.
832                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
833                            UserHandle.getSharedAppGid(
834                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
835                    if (overlayPathList == null) {
836                        overlayPathList = new ArrayList<String>();
837                    }
838                    overlayPathList.add(overlayPackage.baseCodePath);
839                } catch (InstallerException e) {
840                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
841                            overlayPackage.baseCodePath);
842                }
843            }
844            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
845        }
846
847        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
848            synchronized (mPackages) {
849                return getStaticOverlayPathsLocked(
850                        mPackages.values(), targetPackageName, targetPath);
851            }
852        }
853
854        @Override public final String[] getOverlayApks(String targetPackageName) {
855            return getStaticOverlayPaths(targetPackageName, null);
856        }
857
858        @Override public final String[] getOverlayPaths(String targetPackageName,
859                String targetPath) {
860            return getStaticOverlayPaths(targetPackageName, targetPath);
861        }
862    };
863
864    class ParallelPackageParserCallback extends PackageParserCallback {
865        List<PackageParser.Package> mOverlayPackages = null;
866
867        void findStaticOverlayPackages() {
868            synchronized (mPackages) {
869                for (PackageParser.Package p : mPackages.values()) {
870                    if (p.mIsStaticOverlay) {
871                        if (mOverlayPackages == null) {
872                            mOverlayPackages = new ArrayList<PackageParser.Package>();
873                        }
874                        mOverlayPackages.add(p);
875                    }
876                }
877            }
878        }
879
880        @Override
881        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
882            // We can trust mOverlayPackages without holding mPackages because package uninstall
883            // can't happen while running parallel parsing.
884            // Moreover holding mPackages on each parsing thread causes dead-lock.
885            return mOverlayPackages == null ? null :
886                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
887        }
888    }
889
890    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
891    final ParallelPackageParserCallback mParallelPackageParserCallback =
892            new ParallelPackageParserCallback();
893
894    public static final class SharedLibraryEntry {
895        public final @Nullable String path;
896        public final @Nullable String apk;
897        public final @NonNull SharedLibraryInfo info;
898
899        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
900                String declaringPackageName, int declaringPackageVersionCode) {
901            path = _path;
902            apk = _apk;
903            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
904                    declaringPackageName, declaringPackageVersionCode), null);
905        }
906    }
907
908    // Currently known shared libraries.
909    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
910    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
911            new ArrayMap<>();
912
913    // All available activities, for your resolving pleasure.
914    final ActivityIntentResolver mActivities =
915            new ActivityIntentResolver();
916
917    // All available receivers, for your resolving pleasure.
918    final ActivityIntentResolver mReceivers =
919            new ActivityIntentResolver();
920
921    // All available services, for your resolving pleasure.
922    final ServiceIntentResolver mServices = new ServiceIntentResolver();
923
924    // All available providers, for your resolving pleasure.
925    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
926
927    // Mapping from provider base names (first directory in content URI codePath)
928    // to the provider information.
929    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
930            new ArrayMap<String, PackageParser.Provider>();
931
932    // Mapping from instrumentation class names to info about them.
933    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
934            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
935
936    // Mapping from permission names to info about them.
937    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
938            new ArrayMap<String, PackageParser.PermissionGroup>();
939
940    // Packages whose data we have transfered into another package, thus
941    // should no longer exist.
942    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
943
944    // Broadcast actions that are only available to the system.
945    @GuardedBy("mProtectedBroadcasts")
946    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
947
948    /** List of packages waiting for verification. */
949    final SparseArray<PackageVerificationState> mPendingVerification
950            = new SparseArray<PackageVerificationState>();
951
952    /** Set of packages associated with each app op permission. */
953    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
954
955    final PackageInstallerService mInstallerService;
956
957    private final PackageDexOptimizer mPackageDexOptimizer;
958    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
959    // is used by other apps).
960    private final DexManager mDexManager;
961
962    private AtomicInteger mNextMoveId = new AtomicInteger();
963    private final MoveCallbacks mMoveCallbacks;
964
965    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
966
967    // Cache of users who need badging.
968    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
969
970    /** Token for keys in mPendingVerification. */
971    private int mPendingVerificationToken = 0;
972
973    volatile boolean mSystemReady;
974    volatile boolean mSafeMode;
975    volatile boolean mHasSystemUidErrors;
976    private volatile boolean mEphemeralAppsDisabled;
977
978    ApplicationInfo mAndroidApplication;
979    final ActivityInfo mResolveActivity = new ActivityInfo();
980    final ResolveInfo mResolveInfo = new ResolveInfo();
981    ComponentName mResolveComponentName;
982    PackageParser.Package mPlatformPackage;
983    ComponentName mCustomResolverComponentName;
984
985    boolean mResolverReplaced = false;
986
987    private final @Nullable ComponentName mIntentFilterVerifierComponent;
988    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
989
990    private int mIntentFilterVerificationToken = 0;
991
992    /** The service connection to the ephemeral resolver */
993    final EphemeralResolverConnection mInstantAppResolverConnection;
994    /** Component used to show resolver settings for Instant Apps */
995    final ComponentName mInstantAppResolverSettingsComponent;
996
997    /** Activity used to install instant applications */
998    ActivityInfo mInstantAppInstallerActivity;
999    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1000
1001    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1002            = new SparseArray<IntentFilterVerificationState>();
1003
1004    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1005
1006    // List of packages names to keep cached, even if they are uninstalled for all users
1007    private List<String> mKeepUninstalledPackages;
1008
1009    private UserManagerInternal mUserManagerInternal;
1010
1011    private DeviceIdleController.LocalService mDeviceIdleController;
1012
1013    private File mCacheDir;
1014
1015    private ArraySet<String> mPrivappPermissionsViolations;
1016
1017    private Future<?> mPrepareAppDataFuture;
1018
1019    private static class IFVerificationParams {
1020        PackageParser.Package pkg;
1021        boolean replacing;
1022        int userId;
1023        int verifierUid;
1024
1025        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1026                int _userId, int _verifierUid) {
1027            pkg = _pkg;
1028            replacing = _replacing;
1029            userId = _userId;
1030            replacing = _replacing;
1031            verifierUid = _verifierUid;
1032        }
1033    }
1034
1035    private interface IntentFilterVerifier<T extends IntentFilter> {
1036        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1037                                               T filter, String packageName);
1038        void startVerifications(int userId);
1039        void receiveVerificationResponse(int verificationId);
1040    }
1041
1042    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1043        private Context mContext;
1044        private ComponentName mIntentFilterVerifierComponent;
1045        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1046
1047        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1048            mContext = context;
1049            mIntentFilterVerifierComponent = verifierComponent;
1050        }
1051
1052        private String getDefaultScheme() {
1053            return IntentFilter.SCHEME_HTTPS;
1054        }
1055
1056        @Override
1057        public void startVerifications(int userId) {
1058            // Launch verifications requests
1059            int count = mCurrentIntentFilterVerifications.size();
1060            for (int n=0; n<count; n++) {
1061                int verificationId = mCurrentIntentFilterVerifications.get(n);
1062                final IntentFilterVerificationState ivs =
1063                        mIntentFilterVerificationStates.get(verificationId);
1064
1065                String packageName = ivs.getPackageName();
1066
1067                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1068                final int filterCount = filters.size();
1069                ArraySet<String> domainsSet = new ArraySet<>();
1070                for (int m=0; m<filterCount; m++) {
1071                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1072                    domainsSet.addAll(filter.getHostsList());
1073                }
1074                synchronized (mPackages) {
1075                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1076                            packageName, domainsSet) != null) {
1077                        scheduleWriteSettingsLocked();
1078                    }
1079                }
1080                sendVerificationRequest(verificationId, ivs);
1081            }
1082            mCurrentIntentFilterVerifications.clear();
1083        }
1084
1085        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1086            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1087            verificationIntent.putExtra(
1088                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1089                    verificationId);
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1092                    getDefaultScheme());
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1095                    ivs.getHostsString());
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1098                    ivs.getPackageName());
1099            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1100            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1101
1102            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1103            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1104                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1105                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1106
1107            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1108            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1109                    "Sending IntentFilter verification broadcast");
1110        }
1111
1112        public void receiveVerificationResponse(int verificationId) {
1113            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1114
1115            final boolean verified = ivs.isVerified();
1116
1117            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1118            final int count = filters.size();
1119            if (DEBUG_DOMAIN_VERIFICATION) {
1120                Slog.i(TAG, "Received verification response " + verificationId
1121                        + " for " + count + " filters, verified=" + verified);
1122            }
1123            for (int n=0; n<count; n++) {
1124                PackageParser.ActivityIntentInfo filter = filters.get(n);
1125                filter.setVerified(verified);
1126
1127                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1128                        + " verified with result:" + verified + " and hosts:"
1129                        + ivs.getHostsString());
1130            }
1131
1132            mIntentFilterVerificationStates.remove(verificationId);
1133
1134            final String packageName = ivs.getPackageName();
1135            IntentFilterVerificationInfo ivi = null;
1136
1137            synchronized (mPackages) {
1138                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1139            }
1140            if (ivi == null) {
1141                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1142                        + verificationId + " packageName:" + packageName);
1143                return;
1144            }
1145            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1146                    "Updating IntentFilterVerificationInfo for package " + packageName
1147                            +" verificationId:" + verificationId);
1148
1149            synchronized (mPackages) {
1150                if (verified) {
1151                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1152                } else {
1153                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1154                }
1155                scheduleWriteSettingsLocked();
1156
1157                final int userId = ivs.getUserId();
1158                if (userId != UserHandle.USER_ALL) {
1159                    final int userStatus =
1160                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1161
1162                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1163                    boolean needUpdate = false;
1164
1165                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1166                    // already been set by the User thru the Disambiguation dialog
1167                    switch (userStatus) {
1168                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1169                            if (verified) {
1170                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1171                            } else {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1173                            }
1174                            needUpdate = true;
1175                            break;
1176
1177                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1178                            if (verified) {
1179                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1180                                needUpdate = true;
1181                            }
1182                            break;
1183
1184                        default:
1185                            // Nothing to do
1186                    }
1187
1188                    if (needUpdate) {
1189                        mSettings.updateIntentFilterVerificationStatusLPw(
1190                                packageName, updatedStatus, userId);
1191                        scheduleWritePackageRestrictionsLocked(userId);
1192                    }
1193                }
1194            }
1195        }
1196
1197        @Override
1198        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1199                    ActivityIntentInfo filter, String packageName) {
1200            if (!hasValidDomains(filter)) {
1201                return false;
1202            }
1203            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1204            if (ivs == null) {
1205                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1206                        packageName);
1207            }
1208            if (DEBUG_DOMAIN_VERIFICATION) {
1209                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1210            }
1211            ivs.addFilter(filter);
1212            return true;
1213        }
1214
1215        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1216                int userId, int verificationId, String packageName) {
1217            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1218                    verifierUid, userId, packageName);
1219            ivs.setPendingState();
1220            synchronized (mPackages) {
1221                mIntentFilterVerificationStates.append(verificationId, ivs);
1222                mCurrentIntentFilterVerifications.add(verificationId);
1223            }
1224            return ivs;
1225        }
1226    }
1227
1228    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1229        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1230                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1231                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1232    }
1233
1234    // Set of pending broadcasts for aggregating enable/disable of components.
1235    static class PendingPackageBroadcasts {
1236        // for each user id, a map of <package name -> components within that package>
1237        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1238
1239        public PendingPackageBroadcasts() {
1240            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1241        }
1242
1243        public ArrayList<String> get(int userId, String packageName) {
1244            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1245            return packages.get(packageName);
1246        }
1247
1248        public void put(int userId, String packageName, ArrayList<String> components) {
1249            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1250            packages.put(packageName, components);
1251        }
1252
1253        public void remove(int userId, String packageName) {
1254            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1255            if (packages != null) {
1256                packages.remove(packageName);
1257            }
1258        }
1259
1260        public void remove(int userId) {
1261            mUidMap.remove(userId);
1262        }
1263
1264        public int userIdCount() {
1265            return mUidMap.size();
1266        }
1267
1268        public int userIdAt(int n) {
1269            return mUidMap.keyAt(n);
1270        }
1271
1272        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1273            return mUidMap.get(userId);
1274        }
1275
1276        public int size() {
1277            // total number of pending broadcast entries across all userIds
1278            int num = 0;
1279            for (int i = 0; i< mUidMap.size(); i++) {
1280                num += mUidMap.valueAt(i).size();
1281            }
1282            return num;
1283        }
1284
1285        public void clear() {
1286            mUidMap.clear();
1287        }
1288
1289        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1290            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1291            if (map == null) {
1292                map = new ArrayMap<String, ArrayList<String>>();
1293                mUidMap.put(userId, map);
1294            }
1295            return map;
1296        }
1297    }
1298    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1299
1300    // Service Connection to remote media container service to copy
1301    // package uri's from external media onto secure containers
1302    // or internal storage.
1303    private IMediaContainerService mContainerService = null;
1304
1305    static final int SEND_PENDING_BROADCAST = 1;
1306    static final int MCS_BOUND = 3;
1307    static final int END_COPY = 4;
1308    static final int INIT_COPY = 5;
1309    static final int MCS_UNBIND = 6;
1310    static final int START_CLEANING_PACKAGE = 7;
1311    static final int FIND_INSTALL_LOC = 8;
1312    static final int POST_INSTALL = 9;
1313    static final int MCS_RECONNECT = 10;
1314    static final int MCS_GIVE_UP = 11;
1315    static final int WRITE_SETTINGS = 13;
1316    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1317    static final int PACKAGE_VERIFIED = 15;
1318    static final int CHECK_PENDING_VERIFICATION = 16;
1319    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1320    static final int INTENT_FILTER_VERIFIED = 18;
1321    static final int WRITE_PACKAGE_LIST = 19;
1322    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1323
1324    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1325
1326    // Delay time in millisecs
1327    static final int BROADCAST_DELAY = 10 * 1000;
1328
1329    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1330            2 * 60 * 60 * 1000L; /* two hours */
1331
1332    static UserManagerService sUserManager;
1333
1334    // Stores a list of users whose package restrictions file needs to be updated
1335    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1336
1337    final private DefaultContainerConnection mDefContainerConn =
1338            new DefaultContainerConnection();
1339    class DefaultContainerConnection implements ServiceConnection {
1340        public void onServiceConnected(ComponentName name, IBinder service) {
1341            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1342            final IMediaContainerService imcs = IMediaContainerService.Stub
1343                    .asInterface(Binder.allowBlocking(service));
1344            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1345        }
1346
1347        public void onServiceDisconnected(ComponentName name) {
1348            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1349        }
1350    }
1351
1352    // Recordkeeping of restore-after-install operations that are currently in flight
1353    // between the Package Manager and the Backup Manager
1354    static class PostInstallData {
1355        public InstallArgs args;
1356        public PackageInstalledInfo res;
1357
1358        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1359            args = _a;
1360            res = _r;
1361        }
1362    }
1363
1364    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1365    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1366
1367    // XML tags for backup/restore of various bits of state
1368    private static final String TAG_PREFERRED_BACKUP = "pa";
1369    private static final String TAG_DEFAULT_APPS = "da";
1370    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1371
1372    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1373    private static final String TAG_ALL_GRANTS = "rt-grants";
1374    private static final String TAG_GRANT = "grant";
1375    private static final String ATTR_PACKAGE_NAME = "pkg";
1376
1377    private static final String TAG_PERMISSION = "perm";
1378    private static final String ATTR_PERMISSION_NAME = "name";
1379    private static final String ATTR_IS_GRANTED = "g";
1380    private static final String ATTR_USER_SET = "set";
1381    private static final String ATTR_USER_FIXED = "fixed";
1382    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1383
1384    // System/policy permission grants are not backed up
1385    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1386            FLAG_PERMISSION_POLICY_FIXED
1387            | FLAG_PERMISSION_SYSTEM_FIXED
1388            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1389
1390    // And we back up these user-adjusted states
1391    private static final int USER_RUNTIME_GRANT_MASK =
1392            FLAG_PERMISSION_USER_SET
1393            | FLAG_PERMISSION_USER_FIXED
1394            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1395
1396    final @Nullable String mRequiredVerifierPackage;
1397    final @NonNull String mRequiredInstallerPackage;
1398    final @NonNull String mRequiredUninstallerPackage;
1399    final @Nullable String mSetupWizardPackage;
1400    final @Nullable String mStorageManagerPackage;
1401    final @NonNull String mServicesSystemSharedLibraryPackageName;
1402    final @NonNull String mSharedSystemSharedLibraryPackageName;
1403
1404    final boolean mPermissionReviewRequired;
1405
1406    private final PackageUsage mPackageUsage = new PackageUsage();
1407    private final CompilerStats mCompilerStats = new CompilerStats();
1408
1409    class PackageHandler extends Handler {
1410        private boolean mBound = false;
1411        final ArrayList<HandlerParams> mPendingInstalls =
1412            new ArrayList<HandlerParams>();
1413
1414        private boolean connectToService() {
1415            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1416                    " DefaultContainerService");
1417            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1418            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1419            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1420                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1421                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422                mBound = true;
1423                return true;
1424            }
1425            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426            return false;
1427        }
1428
1429        private void disconnectService() {
1430            mContainerService = null;
1431            mBound = false;
1432            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1433            mContext.unbindService(mDefContainerConn);
1434            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1435        }
1436
1437        PackageHandler(Looper looper) {
1438            super(looper);
1439        }
1440
1441        public void handleMessage(Message msg) {
1442            try {
1443                doHandleMessage(msg);
1444            } finally {
1445                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1446            }
1447        }
1448
1449        void doHandleMessage(Message msg) {
1450            switch (msg.what) {
1451                case INIT_COPY: {
1452                    HandlerParams params = (HandlerParams) msg.obj;
1453                    int idx = mPendingInstalls.size();
1454                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1455                    // If a bind was already initiated we dont really
1456                    // need to do anything. The pending install
1457                    // will be processed later on.
1458                    if (!mBound) {
1459                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1460                                System.identityHashCode(mHandler));
1461                        // If this is the only one pending we might
1462                        // have to bind to the service again.
1463                        if (!connectToService()) {
1464                            Slog.e(TAG, "Failed to bind to media container service");
1465                            params.serviceError();
1466                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1467                                    System.identityHashCode(mHandler));
1468                            if (params.traceMethod != null) {
1469                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1470                                        params.traceCookie);
1471                            }
1472                            return;
1473                        } else {
1474                            // Once we bind to the service, the first
1475                            // pending request will be processed.
1476                            mPendingInstalls.add(idx, params);
1477                        }
1478                    } else {
1479                        mPendingInstalls.add(idx, params);
1480                        // Already bound to the service. Just make
1481                        // sure we trigger off processing the first request.
1482                        if (idx == 0) {
1483                            mHandler.sendEmptyMessage(MCS_BOUND);
1484                        }
1485                    }
1486                    break;
1487                }
1488                case MCS_BOUND: {
1489                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1490                    if (msg.obj != null) {
1491                        mContainerService = (IMediaContainerService) msg.obj;
1492                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1493                                System.identityHashCode(mHandler));
1494                    }
1495                    if (mContainerService == null) {
1496                        if (!mBound) {
1497                            // Something seriously wrong since we are not bound and we are not
1498                            // waiting for connection. Bail out.
1499                            Slog.e(TAG, "Cannot bind to media container service");
1500                            for (HandlerParams params : mPendingInstalls) {
1501                                // Indicate service bind error
1502                                params.serviceError();
1503                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1504                                        System.identityHashCode(params));
1505                                if (params.traceMethod != null) {
1506                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1507                                            params.traceMethod, params.traceCookie);
1508                                }
1509                                return;
1510                            }
1511                            mPendingInstalls.clear();
1512                        } else {
1513                            Slog.w(TAG, "Waiting to connect to media container service");
1514                        }
1515                    } else if (mPendingInstalls.size() > 0) {
1516                        HandlerParams params = mPendingInstalls.get(0);
1517                        if (params != null) {
1518                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1519                                    System.identityHashCode(params));
1520                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1521                            if (params.startCopy()) {
1522                                // We are done...  look for more work or to
1523                                // go idle.
1524                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1525                                        "Checking for more work or unbind...");
1526                                // Delete pending install
1527                                if (mPendingInstalls.size() > 0) {
1528                                    mPendingInstalls.remove(0);
1529                                }
1530                                if (mPendingInstalls.size() == 0) {
1531                                    if (mBound) {
1532                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1533                                                "Posting delayed MCS_UNBIND");
1534                                        removeMessages(MCS_UNBIND);
1535                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1536                                        // Unbind after a little delay, to avoid
1537                                        // continual thrashing.
1538                                        sendMessageDelayed(ubmsg, 10000);
1539                                    }
1540                                } else {
1541                                    // There are more pending requests in queue.
1542                                    // Just post MCS_BOUND message to trigger processing
1543                                    // of next pending install.
1544                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1545                                            "Posting MCS_BOUND for next work");
1546                                    mHandler.sendEmptyMessage(MCS_BOUND);
1547                                }
1548                            }
1549                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1550                        }
1551                    } else {
1552                        // Should never happen ideally.
1553                        Slog.w(TAG, "Empty queue");
1554                    }
1555                    break;
1556                }
1557                case MCS_RECONNECT: {
1558                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1559                    if (mPendingInstalls.size() > 0) {
1560                        if (mBound) {
1561                            disconnectService();
1562                        }
1563                        if (!connectToService()) {
1564                            Slog.e(TAG, "Failed to bind to media container service");
1565                            for (HandlerParams params : mPendingInstalls) {
1566                                // Indicate service bind error
1567                                params.serviceError();
1568                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1569                                        System.identityHashCode(params));
1570                            }
1571                            mPendingInstalls.clear();
1572                        }
1573                    }
1574                    break;
1575                }
1576                case MCS_UNBIND: {
1577                    // If there is no actual work left, then time to unbind.
1578                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1579
1580                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1581                        if (mBound) {
1582                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1583
1584                            disconnectService();
1585                        }
1586                    } else if (mPendingInstalls.size() > 0) {
1587                        // There are more pending requests in queue.
1588                        // Just post MCS_BOUND message to trigger processing
1589                        // of next pending install.
1590                        mHandler.sendEmptyMessage(MCS_BOUND);
1591                    }
1592
1593                    break;
1594                }
1595                case MCS_GIVE_UP: {
1596                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1597                    HandlerParams params = mPendingInstalls.remove(0);
1598                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1599                            System.identityHashCode(params));
1600                    break;
1601                }
1602                case SEND_PENDING_BROADCAST: {
1603                    String packages[];
1604                    ArrayList<String> components[];
1605                    int size = 0;
1606                    int uids[];
1607                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1608                    synchronized (mPackages) {
1609                        if (mPendingBroadcasts == null) {
1610                            return;
1611                        }
1612                        size = mPendingBroadcasts.size();
1613                        if (size <= 0) {
1614                            // Nothing to be done. Just return
1615                            return;
1616                        }
1617                        packages = new String[size];
1618                        components = new ArrayList[size];
1619                        uids = new int[size];
1620                        int i = 0;  // filling out the above arrays
1621
1622                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1623                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1624                            Iterator<Map.Entry<String, ArrayList<String>>> it
1625                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1626                                            .entrySet().iterator();
1627                            while (it.hasNext() && i < size) {
1628                                Map.Entry<String, ArrayList<String>> ent = it.next();
1629                                packages[i] = ent.getKey();
1630                                components[i] = ent.getValue();
1631                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1632                                uids[i] = (ps != null)
1633                                        ? UserHandle.getUid(packageUserId, ps.appId)
1634                                        : -1;
1635                                i++;
1636                            }
1637                        }
1638                        size = i;
1639                        mPendingBroadcasts.clear();
1640                    }
1641                    // Send broadcasts
1642                    for (int i = 0; i < size; i++) {
1643                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1644                    }
1645                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1646                    break;
1647                }
1648                case START_CLEANING_PACKAGE: {
1649                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1650                    final String packageName = (String)msg.obj;
1651                    final int userId = msg.arg1;
1652                    final boolean andCode = msg.arg2 != 0;
1653                    synchronized (mPackages) {
1654                        if (userId == UserHandle.USER_ALL) {
1655                            int[] users = sUserManager.getUserIds();
1656                            for (int user : users) {
1657                                mSettings.addPackageToCleanLPw(
1658                                        new PackageCleanItem(user, packageName, andCode));
1659                            }
1660                        } else {
1661                            mSettings.addPackageToCleanLPw(
1662                                    new PackageCleanItem(userId, packageName, andCode));
1663                        }
1664                    }
1665                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1666                    startCleaningPackages();
1667                } break;
1668                case POST_INSTALL: {
1669                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1670
1671                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1672                    final boolean didRestore = (msg.arg2 != 0);
1673                    mRunningInstalls.delete(msg.arg1);
1674
1675                    if (data != null) {
1676                        InstallArgs args = data.args;
1677                        PackageInstalledInfo parentRes = data.res;
1678
1679                        final boolean grantPermissions = (args.installFlags
1680                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1681                        final boolean killApp = (args.installFlags
1682                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1683                        final boolean virtualPreload = ((args.installFlags
1684                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1685                        final String[] grantedPermissions = args.installGrantPermissions;
1686
1687                        // Handle the parent package
1688                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1689                                virtualPreload, grantedPermissions, didRestore,
1690                                args.installerPackageName, args.observer);
1691
1692                        // Handle the child packages
1693                        final int childCount = (parentRes.addedChildPackages != null)
1694                                ? parentRes.addedChildPackages.size() : 0;
1695                        for (int i = 0; i < childCount; i++) {
1696                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1697                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1698                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1699                                    args.installerPackageName, args.observer);
1700                        }
1701
1702                        // Log tracing if needed
1703                        if (args.traceMethod != null) {
1704                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1705                                    args.traceCookie);
1706                        }
1707                    } else {
1708                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1709                    }
1710
1711                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1712                } break;
1713                case WRITE_SETTINGS: {
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1715                    synchronized (mPackages) {
1716                        removeMessages(WRITE_SETTINGS);
1717                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1718                        mSettings.writeLPr();
1719                        mDirtyUsers.clear();
1720                    }
1721                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1722                } break;
1723                case WRITE_PACKAGE_RESTRICTIONS: {
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1725                    synchronized (mPackages) {
1726                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1727                        for (int userId : mDirtyUsers) {
1728                            mSettings.writePackageRestrictionsLPr(userId);
1729                        }
1730                        mDirtyUsers.clear();
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case WRITE_PACKAGE_LIST: {
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1736                    synchronized (mPackages) {
1737                        removeMessages(WRITE_PACKAGE_LIST);
1738                        mSettings.writePackageListLPr(msg.arg1);
1739                    }
1740                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1741                } break;
1742                case CHECK_PENDING_VERIFICATION: {
1743                    final int verificationId = msg.arg1;
1744                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1745
1746                    if ((state != null) && !state.timeoutExtended()) {
1747                        final InstallArgs args = state.getInstallArgs();
1748                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1749
1750                        Slog.i(TAG, "Verification timed out for " + originUri);
1751                        mPendingVerification.remove(verificationId);
1752
1753                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1754
1755                        final UserHandle user = args.getUser();
1756                        if (getDefaultVerificationResponse(user)
1757                                == PackageManager.VERIFICATION_ALLOW) {
1758                            Slog.i(TAG, "Continuing with installation of " + originUri);
1759                            state.setVerifierResponse(Binder.getCallingUid(),
1760                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1761                            broadcastPackageVerified(verificationId, originUri,
1762                                    PackageManager.VERIFICATION_ALLOW, user);
1763                            try {
1764                                ret = args.copyApk(mContainerService, true);
1765                            } catch (RemoteException e) {
1766                                Slog.e(TAG, "Could not contact the ContainerService");
1767                            }
1768                        } else {
1769                            broadcastPackageVerified(verificationId, originUri,
1770                                    PackageManager.VERIFICATION_REJECT, user);
1771                        }
1772
1773                        Trace.asyncTraceEnd(
1774                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1775
1776                        processPendingInstall(args, ret);
1777                        mHandler.sendEmptyMessage(MCS_UNBIND);
1778                    }
1779                    break;
1780                }
1781                case PACKAGE_VERIFIED: {
1782                    final int verificationId = msg.arg1;
1783
1784                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1785                    if (state == null) {
1786                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1787                        break;
1788                    }
1789
1790                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1791
1792                    state.setVerifierResponse(response.callerUid, response.code);
1793
1794                    if (state.isVerificationComplete()) {
1795                        mPendingVerification.remove(verificationId);
1796
1797                        final InstallArgs args = state.getInstallArgs();
1798                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1799
1800                        int ret;
1801                        if (state.isInstallAllowed()) {
1802                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1803                            broadcastPackageVerified(verificationId, originUri,
1804                                    response.code, state.getInstallArgs().getUser());
1805                            try {
1806                                ret = args.copyApk(mContainerService, true);
1807                            } catch (RemoteException e) {
1808                                Slog.e(TAG, "Could not contact the ContainerService");
1809                            }
1810                        } else {
1811                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1812                        }
1813
1814                        Trace.asyncTraceEnd(
1815                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1816
1817                        processPendingInstall(args, ret);
1818                        mHandler.sendEmptyMessage(MCS_UNBIND);
1819                    }
1820
1821                    break;
1822                }
1823                case START_INTENT_FILTER_VERIFICATIONS: {
1824                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1825                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1826                            params.replacing, params.pkg);
1827                    break;
1828                }
1829                case INTENT_FILTER_VERIFIED: {
1830                    final int verificationId = msg.arg1;
1831
1832                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1833                            verificationId);
1834                    if (state == null) {
1835                        Slog.w(TAG, "Invalid IntentFilter verification token "
1836                                + verificationId + " received");
1837                        break;
1838                    }
1839
1840                    final int userId = state.getUserId();
1841
1842                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1843                            "Processing IntentFilter verification with token:"
1844                            + verificationId + " and userId:" + userId);
1845
1846                    final IntentFilterVerificationResponse response =
1847                            (IntentFilterVerificationResponse) msg.obj;
1848
1849                    state.setVerifierResponse(response.callerUid, response.code);
1850
1851                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1852                            "IntentFilter verification with token:" + verificationId
1853                            + " and userId:" + userId
1854                            + " is settings verifier response with response code:"
1855                            + response.code);
1856
1857                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1858                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1859                                + response.getFailedDomainsString());
1860                    }
1861
1862                    if (state.isVerificationComplete()) {
1863                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1864                    } else {
1865                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1866                                "IntentFilter verification with token:" + verificationId
1867                                + " was not said to be complete");
1868                    }
1869
1870                    break;
1871                }
1872                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1873                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1874                            mInstantAppResolverConnection,
1875                            (InstantAppRequest) msg.obj,
1876                            mInstantAppInstallerActivity,
1877                            mHandler);
1878                }
1879            }
1880        }
1881    }
1882
1883    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1884            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1885            boolean launchedForRestore, String installerPackage,
1886            IPackageInstallObserver2 installObserver) {
1887        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1888            // Send the removed broadcasts
1889            if (res.removedInfo != null) {
1890                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1891            }
1892
1893            // Now that we successfully installed the package, grant runtime
1894            // permissions if requested before broadcasting the install. Also
1895            // for legacy apps in permission review mode we clear the permission
1896            // review flag which is used to emulate runtime permissions for
1897            // legacy apps.
1898            if (grantPermissions) {
1899                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1900            }
1901
1902            final boolean update = res.removedInfo != null
1903                    && res.removedInfo.removedPackage != null;
1904            final String installerPackageName =
1905                    res.installerPackageName != null
1906                            ? res.installerPackageName
1907                            : res.removedInfo != null
1908                                    ? res.removedInfo.installerPackageName
1909                                    : null;
1910
1911            // If this is the first time we have child packages for a disabled privileged
1912            // app that had no children, we grant requested runtime permissions to the new
1913            // children if the parent on the system image had them already granted.
1914            if (res.pkg.parentPackage != null) {
1915                synchronized (mPackages) {
1916                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1917                }
1918            }
1919
1920            synchronized (mPackages) {
1921                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1922            }
1923
1924            final String packageName = res.pkg.applicationInfo.packageName;
1925
1926            // Determine the set of users who are adding this package for
1927            // the first time vs. those who are seeing an update.
1928            int[] firstUsers = EMPTY_INT_ARRAY;
1929            int[] updateUsers = EMPTY_INT_ARRAY;
1930            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1931            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1932            for (int newUser : res.newUsers) {
1933                if (ps.getInstantApp(newUser)) {
1934                    continue;
1935                }
1936                if (allNewUsers) {
1937                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1938                    continue;
1939                }
1940                boolean isNew = true;
1941                for (int origUser : res.origUsers) {
1942                    if (origUser == newUser) {
1943                        isNew = false;
1944                        break;
1945                    }
1946                }
1947                if (isNew) {
1948                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1949                } else {
1950                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1951                }
1952            }
1953
1954            // Send installed broadcasts if the package is not a static shared lib.
1955            if (res.pkg.staticSharedLibName == null) {
1956                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1957
1958                // Send added for users that see the package for the first time
1959                // sendPackageAddedForNewUsers also deals with system apps
1960                int appId = UserHandle.getAppId(res.uid);
1961                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1962                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1963                        virtualPreload /*startReceiver*/, appId, firstUsers);
1964
1965                // Send added for users that don't see the package for the first time
1966                Bundle extras = new Bundle(1);
1967                extras.putInt(Intent.EXTRA_UID, res.uid);
1968                if (update) {
1969                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1970                }
1971                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1972                        extras, 0 /*flags*/,
1973                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1974                if (installerPackageName != null) {
1975                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1976                            extras, 0 /*flags*/,
1977                            installerPackageName, null /*finishedReceiver*/, updateUsers);
1978                }
1979
1980                // Send replaced for users that don't see the package for the first time
1981                if (update) {
1982                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1983                            packageName, extras, 0 /*flags*/,
1984                            null /*targetPackage*/, null /*finishedReceiver*/,
1985                            updateUsers);
1986                    if (installerPackageName != null) {
1987                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1988                                extras, 0 /*flags*/,
1989                                installerPackageName, null /*finishedReceiver*/, updateUsers);
1990                    }
1991                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1992                            null /*package*/, null /*extras*/, 0 /*flags*/,
1993                            packageName /*targetPackage*/,
1994                            null /*finishedReceiver*/, updateUsers);
1995                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1996                    // First-install and we did a restore, so we're responsible for the
1997                    // first-launch broadcast.
1998                    if (DEBUG_BACKUP) {
1999                        Slog.i(TAG, "Post-restore of " + packageName
2000                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2001                    }
2002                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2003                }
2004
2005                // Send broadcast package appeared if forward locked/external for all users
2006                // treat asec-hosted packages like removable media on upgrade
2007                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2008                    if (DEBUG_INSTALL) {
2009                        Slog.i(TAG, "upgrading pkg " + res.pkg
2010                                + " is ASEC-hosted -> AVAILABLE");
2011                    }
2012                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2013                    ArrayList<String> pkgList = new ArrayList<>(1);
2014                    pkgList.add(packageName);
2015                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2016                }
2017            }
2018
2019            // Work that needs to happen on first install within each user
2020            if (firstUsers != null && firstUsers.length > 0) {
2021                synchronized (mPackages) {
2022                    for (int userId : firstUsers) {
2023                        // If this app is a browser and it's newly-installed for some
2024                        // users, clear any default-browser state in those users. The
2025                        // app's nature doesn't depend on the user, so we can just check
2026                        // its browser nature in any user and generalize.
2027                        if (packageIsBrowser(packageName, userId)) {
2028                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2029                        }
2030
2031                        // We may also need to apply pending (restored) runtime
2032                        // permission grants within these users.
2033                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2034                    }
2035                }
2036            }
2037
2038            // Log current value of "unknown sources" setting
2039            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2040                    getUnknownSourcesSettings());
2041
2042            // Remove the replaced package's older resources safely now
2043            // We delete after a gc for applications  on sdcard.
2044            if (res.removedInfo != null && res.removedInfo.args != null) {
2045                Runtime.getRuntime().gc();
2046                synchronized (mInstallLock) {
2047                    res.removedInfo.args.doPostDeleteLI(true);
2048                }
2049            } else {
2050                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2051                // and not block here.
2052                VMRuntime.getRuntime().requestConcurrentGC();
2053            }
2054
2055            // Notify DexManager that the package was installed for new users.
2056            // The updated users should already be indexed and the package code paths
2057            // should not change.
2058            // Don't notify the manager for ephemeral apps as they are not expected to
2059            // survive long enough to benefit of background optimizations.
2060            for (int userId : firstUsers) {
2061                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2062                // There's a race currently where some install events may interleave with an uninstall.
2063                // This can lead to package info being null (b/36642664).
2064                if (info != null) {
2065                    mDexManager.notifyPackageInstalled(info, userId);
2066                }
2067            }
2068        }
2069
2070        // If someone is watching installs - notify them
2071        if (installObserver != null) {
2072            try {
2073                Bundle extras = extrasForInstallResult(res);
2074                installObserver.onPackageInstalled(res.name, res.returnCode,
2075                        res.returnMsg, extras);
2076            } catch (RemoteException e) {
2077                Slog.i(TAG, "Observer no longer exists.");
2078            }
2079        }
2080    }
2081
2082    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2083            PackageParser.Package pkg) {
2084        if (pkg.parentPackage == null) {
2085            return;
2086        }
2087        if (pkg.requestedPermissions == null) {
2088            return;
2089        }
2090        final PackageSetting disabledSysParentPs = mSettings
2091                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2092        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2093                || !disabledSysParentPs.isPrivileged()
2094                || (disabledSysParentPs.childPackageNames != null
2095                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2096            return;
2097        }
2098        final int[] allUserIds = sUserManager.getUserIds();
2099        final int permCount = pkg.requestedPermissions.size();
2100        for (int i = 0; i < permCount; i++) {
2101            String permission = pkg.requestedPermissions.get(i);
2102            BasePermission bp = mSettings.mPermissions.get(permission);
2103            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2104                continue;
2105            }
2106            for (int userId : allUserIds) {
2107                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2108                        permission, userId)) {
2109                    grantRuntimePermission(pkg.packageName, permission, userId);
2110                }
2111            }
2112        }
2113    }
2114
2115    private StorageEventListener mStorageListener = new StorageEventListener() {
2116        @Override
2117        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2118            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2119                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2120                    final String volumeUuid = vol.getFsUuid();
2121
2122                    // Clean up any users or apps that were removed or recreated
2123                    // while this volume was missing
2124                    sUserManager.reconcileUsers(volumeUuid);
2125                    reconcileApps(volumeUuid);
2126
2127                    // Clean up any install sessions that expired or were
2128                    // cancelled while this volume was missing
2129                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2130
2131                    loadPrivatePackages(vol);
2132
2133                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2134                    unloadPrivatePackages(vol);
2135                }
2136            }
2137        }
2138
2139        @Override
2140        public void onVolumeForgotten(String fsUuid) {
2141            if (TextUtils.isEmpty(fsUuid)) {
2142                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2143                return;
2144            }
2145
2146            // Remove any apps installed on the forgotten volume
2147            synchronized (mPackages) {
2148                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2149                for (PackageSetting ps : packages) {
2150                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2151                    deletePackageVersioned(new VersionedPackage(ps.name,
2152                            PackageManager.VERSION_CODE_HIGHEST),
2153                            new LegacyPackageDeleteObserver(null).getBinder(),
2154                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2155                    // Try very hard to release any references to this package
2156                    // so we don't risk the system server being killed due to
2157                    // open FDs
2158                    AttributeCache.instance().removePackage(ps.name);
2159                }
2160
2161                mSettings.onVolumeForgotten(fsUuid);
2162                mSettings.writeLPr();
2163            }
2164        }
2165    };
2166
2167    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2168            String[] grantedPermissions) {
2169        for (int userId : userIds) {
2170            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2171        }
2172    }
2173
2174    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2175            String[] grantedPermissions) {
2176        PackageSetting ps = (PackageSetting) pkg.mExtras;
2177        if (ps == null) {
2178            return;
2179        }
2180
2181        PermissionsState permissionsState = ps.getPermissionsState();
2182
2183        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2184                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2185
2186        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2187                >= Build.VERSION_CODES.M;
2188
2189        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2190
2191        for (String permission : pkg.requestedPermissions) {
2192            final BasePermission bp;
2193            synchronized (mPackages) {
2194                bp = mSettings.mPermissions.get(permission);
2195            }
2196            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2197                    && (!instantApp || bp.isInstant())
2198                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2199                    && (grantedPermissions == null
2200                           || ArrayUtils.contains(grantedPermissions, permission))) {
2201                final int flags = permissionsState.getPermissionFlags(permission, userId);
2202                if (supportsRuntimePermissions) {
2203                    // Installer cannot change immutable permissions.
2204                    if ((flags & immutableFlags) == 0) {
2205                        grantRuntimePermission(pkg.packageName, permission, userId);
2206                    }
2207                } else if (mPermissionReviewRequired) {
2208                    // In permission review mode we clear the review flag when we
2209                    // are asked to install the app with all permissions granted.
2210                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2211                        updatePermissionFlags(permission, pkg.packageName,
2212                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2213                    }
2214                }
2215            }
2216        }
2217    }
2218
2219    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2220        Bundle extras = null;
2221        switch (res.returnCode) {
2222            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2223                extras = new Bundle();
2224                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2225                        res.origPermission);
2226                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2227                        res.origPackage);
2228                break;
2229            }
2230            case PackageManager.INSTALL_SUCCEEDED: {
2231                extras = new Bundle();
2232                extras.putBoolean(Intent.EXTRA_REPLACING,
2233                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2234                break;
2235            }
2236        }
2237        return extras;
2238    }
2239
2240    void scheduleWriteSettingsLocked() {
2241        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2242            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2243        }
2244    }
2245
2246    void scheduleWritePackageListLocked(int userId) {
2247        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2248            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2249            msg.arg1 = userId;
2250            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2251        }
2252    }
2253
2254    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2255        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2256        scheduleWritePackageRestrictionsLocked(userId);
2257    }
2258
2259    void scheduleWritePackageRestrictionsLocked(int userId) {
2260        final int[] userIds = (userId == UserHandle.USER_ALL)
2261                ? sUserManager.getUserIds() : new int[]{userId};
2262        for (int nextUserId : userIds) {
2263            if (!sUserManager.exists(nextUserId)) return;
2264            mDirtyUsers.add(nextUserId);
2265            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2266                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2267            }
2268        }
2269    }
2270
2271    public static PackageManagerService main(Context context, Installer installer,
2272            boolean factoryTest, boolean onlyCore) {
2273        // Self-check for initial settings.
2274        PackageManagerServiceCompilerMapping.checkProperties();
2275
2276        PackageManagerService m = new PackageManagerService(context, installer,
2277                factoryTest, onlyCore);
2278        m.enableSystemUserPackages();
2279        ServiceManager.addService("package", m);
2280        final PackageManagerNative pmn = m.new PackageManagerNative();
2281        ServiceManager.addService("package_native", pmn);
2282        return m;
2283    }
2284
2285    private void enableSystemUserPackages() {
2286        if (!UserManager.isSplitSystemUser()) {
2287            return;
2288        }
2289        // For system user, enable apps based on the following conditions:
2290        // - app is whitelisted or belong to one of these groups:
2291        //   -- system app which has no launcher icons
2292        //   -- system app which has INTERACT_ACROSS_USERS permission
2293        //   -- system IME app
2294        // - app is not in the blacklist
2295        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2296        Set<String> enableApps = new ArraySet<>();
2297        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2298                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2299                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2300        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2301        enableApps.addAll(wlApps);
2302        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2303                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2304        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2305        enableApps.removeAll(blApps);
2306        Log.i(TAG, "Applications installed for system user: " + enableApps);
2307        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2308                UserHandle.SYSTEM);
2309        final int allAppsSize = allAps.size();
2310        synchronized (mPackages) {
2311            for (int i = 0; i < allAppsSize; i++) {
2312                String pName = allAps.get(i);
2313                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2314                // Should not happen, but we shouldn't be failing if it does
2315                if (pkgSetting == null) {
2316                    continue;
2317                }
2318                boolean install = enableApps.contains(pName);
2319                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2320                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2321                            + " for system user");
2322                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2323                }
2324            }
2325            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2326        }
2327    }
2328
2329    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2330        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2331                Context.DISPLAY_SERVICE);
2332        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2333    }
2334
2335    /**
2336     * Requests that files preopted on a secondary system partition be copied to the data partition
2337     * if possible.  Note that the actual copying of the files is accomplished by init for security
2338     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2339     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2340     */
2341    private static void requestCopyPreoptedFiles() {
2342        final int WAIT_TIME_MS = 100;
2343        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2344        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2345            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2346            // We will wait for up to 100 seconds.
2347            final long timeStart = SystemClock.uptimeMillis();
2348            final long timeEnd = timeStart + 100 * 1000;
2349            long timeNow = timeStart;
2350            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2351                try {
2352                    Thread.sleep(WAIT_TIME_MS);
2353                } catch (InterruptedException e) {
2354                    // Do nothing
2355                }
2356                timeNow = SystemClock.uptimeMillis();
2357                if (timeNow > timeEnd) {
2358                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2359                    Slog.wtf(TAG, "cppreopt did not finish!");
2360                    break;
2361                }
2362            }
2363
2364            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2365        }
2366    }
2367
2368    public PackageManagerService(Context context, Installer installer,
2369            boolean factoryTest, boolean onlyCore) {
2370        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2371        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2372        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2373                SystemClock.uptimeMillis());
2374
2375        if (mSdkVersion <= 0) {
2376            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2377        }
2378
2379        mContext = context;
2380
2381        mPermissionReviewRequired = context.getResources().getBoolean(
2382                R.bool.config_permissionReviewRequired);
2383
2384        mFactoryTest = factoryTest;
2385        mOnlyCore = onlyCore;
2386        mMetrics = new DisplayMetrics();
2387        mSettings = new Settings(mPackages);
2388        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2389                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2390        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2391                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2392        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2393                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2394        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2395                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2396        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2397                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2398        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2399                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2400
2401        String separateProcesses = SystemProperties.get("debug.separate_processes");
2402        if (separateProcesses != null && separateProcesses.length() > 0) {
2403            if ("*".equals(separateProcesses)) {
2404                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2405                mSeparateProcesses = null;
2406                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2407            } else {
2408                mDefParseFlags = 0;
2409                mSeparateProcesses = separateProcesses.split(",");
2410                Slog.w(TAG, "Running with debug.separate_processes: "
2411                        + separateProcesses);
2412            }
2413        } else {
2414            mDefParseFlags = 0;
2415            mSeparateProcesses = null;
2416        }
2417
2418        mInstaller = installer;
2419        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2420                "*dexopt*");
2421        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2422        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2423
2424        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2425                FgThread.get().getLooper());
2426
2427        getDefaultDisplayMetrics(context, mMetrics);
2428
2429        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2430        SystemConfig systemConfig = SystemConfig.getInstance();
2431        mGlobalGids = systemConfig.getGlobalGids();
2432        mSystemPermissions = systemConfig.getSystemPermissions();
2433        mAvailableFeatures = systemConfig.getAvailableFeatures();
2434        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2435
2436        mProtectedPackages = new ProtectedPackages(mContext);
2437
2438        synchronized (mInstallLock) {
2439        // writer
2440        synchronized (mPackages) {
2441            mHandlerThread = new ServiceThread(TAG,
2442                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2443            mHandlerThread.start();
2444            mHandler = new PackageHandler(mHandlerThread.getLooper());
2445            mProcessLoggingHandler = new ProcessLoggingHandler();
2446            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2447
2448            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2449            mInstantAppRegistry = new InstantAppRegistry(this);
2450
2451            File dataDir = Environment.getDataDirectory();
2452            mAppInstallDir = new File(dataDir, "app");
2453            mAppLib32InstallDir = new File(dataDir, "app-lib");
2454            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2455            sUserManager = new UserManagerService(context, this,
2456                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2457
2458            // Propagate permission configuration in to package manager.
2459            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2460                    = systemConfig.getPermissions();
2461            for (int i=0; i<permConfig.size(); i++) {
2462                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2463                BasePermission bp = mSettings.mPermissions.get(perm.name);
2464                if (bp == null) {
2465                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2466                    mSettings.mPermissions.put(perm.name, bp);
2467                }
2468                if (perm.gids != null) {
2469                    bp.setGids(perm.gids, perm.perUser);
2470                }
2471            }
2472
2473            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2474            final int builtInLibCount = libConfig.size();
2475            for (int i = 0; i < builtInLibCount; i++) {
2476                String name = libConfig.keyAt(i);
2477                String path = libConfig.valueAt(i);
2478                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2479                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2480            }
2481
2482            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2483
2484            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2485            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2486            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2487
2488            // Clean up orphaned packages for which the code path doesn't exist
2489            // and they are an update to a system app - caused by bug/32321269
2490            final int packageSettingCount = mSettings.mPackages.size();
2491            for (int i = packageSettingCount - 1; i >= 0; i--) {
2492                PackageSetting ps = mSettings.mPackages.valueAt(i);
2493                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2494                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2495                    mSettings.mPackages.removeAt(i);
2496                    mSettings.enableSystemPackageLPw(ps.name);
2497                }
2498            }
2499
2500            if (mFirstBoot) {
2501                requestCopyPreoptedFiles();
2502            }
2503
2504            String customResolverActivity = Resources.getSystem().getString(
2505                    R.string.config_customResolverActivity);
2506            if (TextUtils.isEmpty(customResolverActivity)) {
2507                customResolverActivity = null;
2508            } else {
2509                mCustomResolverComponentName = ComponentName.unflattenFromString(
2510                        customResolverActivity);
2511            }
2512
2513            long startTime = SystemClock.uptimeMillis();
2514
2515            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2516                    startTime);
2517
2518            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2519            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2520
2521            if (bootClassPath == null) {
2522                Slog.w(TAG, "No BOOTCLASSPATH found!");
2523            }
2524
2525            if (systemServerClassPath == null) {
2526                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2527            }
2528
2529            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2530
2531            final VersionInfo ver = mSettings.getInternalVersion();
2532            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2533            if (mIsUpgrade) {
2534                logCriticalInfo(Log.INFO,
2535                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2536            }
2537
2538            // when upgrading from pre-M, promote system app permissions from install to runtime
2539            mPromoteSystemApps =
2540                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2541
2542            // When upgrading from pre-N, we need to handle package extraction like first boot,
2543            // as there is no profiling data available.
2544            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2545
2546            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2547
2548            // save off the names of pre-existing system packages prior to scanning; we don't
2549            // want to automatically grant runtime permissions for new system apps
2550            if (mPromoteSystemApps) {
2551                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2552                while (pkgSettingIter.hasNext()) {
2553                    PackageSetting ps = pkgSettingIter.next();
2554                    if (isSystemApp(ps)) {
2555                        mExistingSystemPackages.add(ps.name);
2556                    }
2557                }
2558            }
2559
2560            mCacheDir = preparePackageParserCache(mIsUpgrade);
2561
2562            // Set flag to monitor and not change apk file paths when
2563            // scanning install directories.
2564            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2565
2566            if (mIsUpgrade || mFirstBoot) {
2567                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2568            }
2569
2570            // Collect vendor overlay packages. (Do this before scanning any apps.)
2571            // For security and version matching reason, only consider
2572            // overlay packages if they reside in the right directory.
2573            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2574                    | PackageParser.PARSE_IS_SYSTEM
2575                    | PackageParser.PARSE_IS_SYSTEM_DIR
2576                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2577
2578            mParallelPackageParserCallback.findStaticOverlayPackages();
2579
2580            // Find base frameworks (resource packages without code).
2581            scanDirTracedLI(frameworkDir, mDefParseFlags
2582                    | PackageParser.PARSE_IS_SYSTEM
2583                    | PackageParser.PARSE_IS_SYSTEM_DIR
2584                    | PackageParser.PARSE_IS_PRIVILEGED,
2585                    scanFlags | SCAN_NO_DEX, 0);
2586
2587            // Collected privileged system packages.
2588            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2589            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2590                    | PackageParser.PARSE_IS_SYSTEM
2591                    | PackageParser.PARSE_IS_SYSTEM_DIR
2592                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2593
2594            // Collect ordinary system packages.
2595            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2596            scanDirTracedLI(systemAppDir, mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM
2598                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2599
2600            // Collect all vendor packages.
2601            File vendorAppDir = new File("/vendor/app");
2602            try {
2603                vendorAppDir = vendorAppDir.getCanonicalFile();
2604            } catch (IOException e) {
2605                // failed to look up canonical path, continue with original one
2606            }
2607            scanDirTracedLI(vendorAppDir, mDefParseFlags
2608                    | PackageParser.PARSE_IS_SYSTEM
2609                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2610
2611            // Collect all OEM packages.
2612            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2613            scanDirTracedLI(oemAppDir, mDefParseFlags
2614                    | PackageParser.PARSE_IS_SYSTEM
2615                    | PackageParser.PARSE_IS_SYSTEM_DIR
2616                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2617
2618            // Prune any system packages that no longer exist.
2619            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2620            // Stub packages must either be replaced with full versions in the /data
2621            // partition or be disabled.
2622            final List<String> stubSystemApps = new ArrayList<>();
2623            if (!mOnlyCore) {
2624                // do this first before mucking with mPackages for the "expecting better" case
2625                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2626                while (pkgIterator.hasNext()) {
2627                    final PackageParser.Package pkg = pkgIterator.next();
2628                    if (pkg.isStub) {
2629                        stubSystemApps.add(pkg.packageName);
2630                    }
2631                }
2632
2633                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2634                while (psit.hasNext()) {
2635                    PackageSetting ps = psit.next();
2636
2637                    /*
2638                     * If this is not a system app, it can't be a
2639                     * disable system app.
2640                     */
2641                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2642                        continue;
2643                    }
2644
2645                    /*
2646                     * If the package is scanned, it's not erased.
2647                     */
2648                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2649                    if (scannedPkg != null) {
2650                        /*
2651                         * If the system app is both scanned and in the
2652                         * disabled packages list, then it must have been
2653                         * added via OTA. Remove it from the currently
2654                         * scanned package so the previously user-installed
2655                         * application can be scanned.
2656                         */
2657                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2658                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2659                                    + ps.name + "; removing system app.  Last known codePath="
2660                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2661                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2662                                    + scannedPkg.mVersionCode);
2663                            removePackageLI(scannedPkg, true);
2664                            mExpectingBetter.put(ps.name, ps.codePath);
2665                        }
2666
2667                        continue;
2668                    }
2669
2670                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2671                        psit.remove();
2672                        logCriticalInfo(Log.WARN, "System package " + ps.name
2673                                + " no longer exists; it's data will be wiped");
2674                        // Actual deletion of code and data will be handled by later
2675                        // reconciliation step
2676                    } else {
2677                        // we still have a disabled system package, but, it still might have
2678                        // been removed. check the code path still exists and check there's
2679                        // still a package. the latter can happen if an OTA keeps the same
2680                        // code path, but, changes the package name.
2681                        final PackageSetting disabledPs =
2682                                mSettings.getDisabledSystemPkgLPr(ps.name);
2683                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2684                                || disabledPs.pkg == null) {
2685                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2686                        }
2687                    }
2688                }
2689            }
2690
2691            //look for any incomplete package installations
2692            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2693            for (int i = 0; i < deletePkgsList.size(); i++) {
2694                // Actual deletion of code and data will be handled by later
2695                // reconciliation step
2696                final String packageName = deletePkgsList.get(i).name;
2697                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2698                synchronized (mPackages) {
2699                    mSettings.removePackageLPw(packageName);
2700                }
2701            }
2702
2703            //delete tmp files
2704            deleteTempPackageFiles();
2705
2706            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2707
2708            // Remove any shared userIDs that have no associated packages
2709            mSettings.pruneSharedUsersLPw();
2710            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2711            final int systemPackagesCount = mPackages.size();
2712            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2713                    + " ms, packageCount: " + systemPackagesCount
2714                    + " , timePerPackage: "
2715                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2716                    + " , cached: " + cachedSystemApps);
2717            if (mIsUpgrade && systemPackagesCount > 0) {
2718                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2719                        ((int) systemScanTime) / systemPackagesCount);
2720            }
2721            if (!mOnlyCore) {
2722                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2723                        SystemClock.uptimeMillis());
2724                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2725
2726                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2727                        | PackageParser.PARSE_FORWARD_LOCK,
2728                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2729
2730                // Remove disable package settings for updated system apps that were
2731                // removed via an OTA. If the update is no longer present, remove the
2732                // app completely. Otherwise, revoke their system privileges.
2733                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2734                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2735                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2736
2737                    final String msg;
2738                    if (deletedPkg == null) {
2739                        // should have found an update, but, we didn't; remove everything
2740                        msg = "Updated system package " + deletedAppName
2741                                + " no longer exists; removing its data";
2742                        // Actual deletion of code and data will be handled by later
2743                        // reconciliation step
2744                    } else {
2745                        // found an update; revoke system privileges
2746                        msg = "Updated system package + " + deletedAppName
2747                                + " no longer exists; revoking system privileges";
2748
2749                        // Don't do anything if a stub is removed from the system image. If
2750                        // we were to remove the uncompressed version from the /data partition,
2751                        // this is where it'd be done.
2752
2753                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2754                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2755                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2756                    }
2757                    logCriticalInfo(Log.WARN, msg);
2758                }
2759
2760                /*
2761                 * Make sure all system apps that we expected to appear on
2762                 * the userdata partition actually showed up. If they never
2763                 * appeared, crawl back and revive the system version.
2764                 */
2765                for (int i = 0; i < mExpectingBetter.size(); i++) {
2766                    final String packageName = mExpectingBetter.keyAt(i);
2767                    if (!mPackages.containsKey(packageName)) {
2768                        final File scanFile = mExpectingBetter.valueAt(i);
2769
2770                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2771                                + " but never showed up; reverting to system");
2772
2773                        int reparseFlags = mDefParseFlags;
2774                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2775                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2776                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2777                                    | PackageParser.PARSE_IS_PRIVILEGED;
2778                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2779                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2780                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2781                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2782                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2783                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2784                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2785                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2786                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2787                                    | PackageParser.PARSE_IS_OEM;
2788                        } else {
2789                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2790                            continue;
2791                        }
2792
2793                        mSettings.enableSystemPackageLPw(packageName);
2794
2795                        try {
2796                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2797                        } catch (PackageManagerException e) {
2798                            Slog.e(TAG, "Failed to parse original system package: "
2799                                    + e.getMessage());
2800                        }
2801                    }
2802                }
2803
2804                // Uncompress and install any stubbed system applications.
2805                // This must be done last to ensure all stubs are replaced or disabled.
2806                decompressSystemApplications(stubSystemApps, scanFlags);
2807
2808                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2809                                - cachedSystemApps;
2810
2811                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2812                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2813                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2814                        + " ms, packageCount: " + dataPackagesCount
2815                        + " , timePerPackage: "
2816                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2817                        + " , cached: " + cachedNonSystemApps);
2818                if (mIsUpgrade && dataPackagesCount > 0) {
2819                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2820                            ((int) dataScanTime) / dataPackagesCount);
2821                }
2822            }
2823            mExpectingBetter.clear();
2824
2825            // Resolve the storage manager.
2826            mStorageManagerPackage = getStorageManagerPackageName();
2827
2828            // Resolve protected action filters. Only the setup wizard is allowed to
2829            // have a high priority filter for these actions.
2830            mSetupWizardPackage = getSetupWizardPackageName();
2831            if (mProtectedFilters.size() > 0) {
2832                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2833                    Slog.i(TAG, "No setup wizard;"
2834                        + " All protected intents capped to priority 0");
2835                }
2836                for (ActivityIntentInfo filter : mProtectedFilters) {
2837                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2838                        if (DEBUG_FILTERS) {
2839                            Slog.i(TAG, "Found setup wizard;"
2840                                + " allow priority " + filter.getPriority() + ";"
2841                                + " package: " + filter.activity.info.packageName
2842                                + " activity: " + filter.activity.className
2843                                + " priority: " + filter.getPriority());
2844                        }
2845                        // skip setup wizard; allow it to keep the high priority filter
2846                        continue;
2847                    }
2848                    if (DEBUG_FILTERS) {
2849                        Slog.i(TAG, "Protected action; cap priority to 0;"
2850                                + " package: " + filter.activity.info.packageName
2851                                + " activity: " + filter.activity.className
2852                                + " origPrio: " + filter.getPriority());
2853                    }
2854                    filter.setPriority(0);
2855                }
2856            }
2857            mDeferProtectedFilters = false;
2858            mProtectedFilters.clear();
2859
2860            // Now that we know all of the shared libraries, update all clients to have
2861            // the correct library paths.
2862            updateAllSharedLibrariesLPw(null);
2863
2864            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2865                // NOTE: We ignore potential failures here during a system scan (like
2866                // the rest of the commands above) because there's precious little we
2867                // can do about it. A settings error is reported, though.
2868                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2869            }
2870
2871            // Now that we know all the packages we are keeping,
2872            // read and update their last usage times.
2873            mPackageUsage.read(mPackages);
2874            mCompilerStats.read();
2875
2876            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2877                    SystemClock.uptimeMillis());
2878            Slog.i(TAG, "Time to scan packages: "
2879                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2880                    + " seconds");
2881
2882            // If the platform SDK has changed since the last time we booted,
2883            // we need to re-grant app permission to catch any new ones that
2884            // appear.  This is really a hack, and means that apps can in some
2885            // cases get permissions that the user didn't initially explicitly
2886            // allow...  it would be nice to have some better way to handle
2887            // this situation.
2888            int updateFlags = UPDATE_PERMISSIONS_ALL;
2889            if (ver.sdkVersion != mSdkVersion) {
2890                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2891                        + mSdkVersion + "; regranting permissions for internal storage");
2892                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2893            }
2894            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2895            ver.sdkVersion = mSdkVersion;
2896
2897            // If this is the first boot or an update from pre-M, and it is a normal
2898            // boot, then we need to initialize the default preferred apps across
2899            // all defined users.
2900            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2901                for (UserInfo user : sUserManager.getUsers(true)) {
2902                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2903                    applyFactoryDefaultBrowserLPw(user.id);
2904                    primeDomainVerificationsLPw(user.id);
2905                }
2906            }
2907
2908            // Prepare storage for system user really early during boot,
2909            // since core system apps like SettingsProvider and SystemUI
2910            // can't wait for user to start
2911            final int storageFlags;
2912            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2913                storageFlags = StorageManager.FLAG_STORAGE_DE;
2914            } else {
2915                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2916            }
2917            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2918                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2919                    true /* onlyCoreApps */);
2920            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2921                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2922                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2923                traceLog.traceBegin("AppDataFixup");
2924                try {
2925                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2926                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2927                } catch (InstallerException e) {
2928                    Slog.w(TAG, "Trouble fixing GIDs", e);
2929                }
2930                traceLog.traceEnd();
2931
2932                traceLog.traceBegin("AppDataPrepare");
2933                if (deferPackages == null || deferPackages.isEmpty()) {
2934                    return;
2935                }
2936                int count = 0;
2937                for (String pkgName : deferPackages) {
2938                    PackageParser.Package pkg = null;
2939                    synchronized (mPackages) {
2940                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2941                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2942                            pkg = ps.pkg;
2943                        }
2944                    }
2945                    if (pkg != null) {
2946                        synchronized (mInstallLock) {
2947                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2948                                    true /* maybeMigrateAppData */);
2949                        }
2950                        count++;
2951                    }
2952                }
2953                traceLog.traceEnd();
2954                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2955            }, "prepareAppData");
2956
2957            // If this is first boot after an OTA, and a normal boot, then
2958            // we need to clear code cache directories.
2959            // Note that we do *not* clear the application profiles. These remain valid
2960            // across OTAs and are used to drive profile verification (post OTA) and
2961            // profile compilation (without waiting to collect a fresh set of profiles).
2962            if (mIsUpgrade && !onlyCore) {
2963                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2964                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2965                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2966                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2967                        // No apps are running this early, so no need to freeze
2968                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2969                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2970                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2971                    }
2972                }
2973                ver.fingerprint = Build.FINGERPRINT;
2974            }
2975
2976            checkDefaultBrowser();
2977
2978            // clear only after permissions and other defaults have been updated
2979            mExistingSystemPackages.clear();
2980            mPromoteSystemApps = false;
2981
2982            // All the changes are done during package scanning.
2983            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2984
2985            // can downgrade to reader
2986            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2987            mSettings.writeLPr();
2988            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2989            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2990                    SystemClock.uptimeMillis());
2991
2992            if (!mOnlyCore) {
2993                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2994                mRequiredInstallerPackage = getRequiredInstallerLPr();
2995                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2996                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2997                if (mIntentFilterVerifierComponent != null) {
2998                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2999                            mIntentFilterVerifierComponent);
3000                } else {
3001                    mIntentFilterVerifier = null;
3002                }
3003                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3004                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3005                        SharedLibraryInfo.VERSION_UNDEFINED);
3006                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3007                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3008                        SharedLibraryInfo.VERSION_UNDEFINED);
3009            } else {
3010                mRequiredVerifierPackage = null;
3011                mRequiredInstallerPackage = null;
3012                mRequiredUninstallerPackage = null;
3013                mIntentFilterVerifierComponent = null;
3014                mIntentFilterVerifier = null;
3015                mServicesSystemSharedLibraryPackageName = null;
3016                mSharedSystemSharedLibraryPackageName = null;
3017            }
3018
3019            mInstallerService = new PackageInstallerService(context, this);
3020            final Pair<ComponentName, String> instantAppResolverComponent =
3021                    getInstantAppResolverLPr();
3022            if (instantAppResolverComponent != null) {
3023                if (DEBUG_EPHEMERAL) {
3024                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3025                }
3026                mInstantAppResolverConnection = new EphemeralResolverConnection(
3027                        mContext, instantAppResolverComponent.first,
3028                        instantAppResolverComponent.second);
3029                mInstantAppResolverSettingsComponent =
3030                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3031            } else {
3032                mInstantAppResolverConnection = null;
3033                mInstantAppResolverSettingsComponent = null;
3034            }
3035            updateInstantAppInstallerLocked(null);
3036
3037            // Read and update the usage of dex files.
3038            // Do this at the end of PM init so that all the packages have their
3039            // data directory reconciled.
3040            // At this point we know the code paths of the packages, so we can validate
3041            // the disk file and build the internal cache.
3042            // The usage file is expected to be small so loading and verifying it
3043            // should take a fairly small time compare to the other activities (e.g. package
3044            // scanning).
3045            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3046            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3047            for (int userId : currentUserIds) {
3048                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3049            }
3050            mDexManager.load(userPackages);
3051            if (mIsUpgrade) {
3052                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3053                        (int) (SystemClock.uptimeMillis() - startTime));
3054            }
3055        } // synchronized (mPackages)
3056        } // synchronized (mInstallLock)
3057
3058        // Now after opening every single application zip, make sure they
3059        // are all flushed.  Not really needed, but keeps things nice and
3060        // tidy.
3061        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3062        Runtime.getRuntime().gc();
3063        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3064
3065        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3066        FallbackCategoryProvider.loadFallbacks();
3067        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3068
3069        // The initial scanning above does many calls into installd while
3070        // holding the mPackages lock, but we're mostly interested in yelling
3071        // once we have a booted system.
3072        mInstaller.setWarnIfHeld(mPackages);
3073
3074        // Expose private service for system components to use.
3075        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3076        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3077    }
3078
3079    /**
3080     * Uncompress and install stub applications.
3081     * <p>In order to save space on the system partition, some applications are shipped in a
3082     * compressed form. In addition the compressed bits for the full application, the
3083     * system image contains a tiny stub comprised of only the Android manifest.
3084     * <p>During the first boot, attempt to uncompress and install the full application. If
3085     * the application can't be installed for any reason, disable the stub and prevent
3086     * uncompressing the full application during future boots.
3087     * <p>In order to forcefully attempt an installation of a full application, go to app
3088     * settings and enable the application.
3089     */
3090    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3091        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3092            final String pkgName = stubSystemApps.get(i);
3093            // skip if the system package is already disabled
3094            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3095                stubSystemApps.remove(i);
3096                continue;
3097            }
3098            // skip if the package isn't installed (?!); this should never happen
3099            final PackageParser.Package pkg = mPackages.get(pkgName);
3100            if (pkg == null) {
3101                stubSystemApps.remove(i);
3102                continue;
3103            }
3104            // skip if the package has been disabled by the user
3105            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3106            if (ps != null) {
3107                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3108                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3109                    stubSystemApps.remove(i);
3110                    continue;
3111                }
3112            }
3113
3114            if (DEBUG_COMPRESSION) {
3115                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3116            }
3117
3118            // uncompress the binary to its eventual destination on /data
3119            final File scanFile = decompressPackage(pkg);
3120            if (scanFile == null) {
3121                continue;
3122            }
3123
3124            // install the package to replace the stub on /system
3125            try {
3126                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3127                removePackageLI(pkg, true /*chatty*/);
3128                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3129                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3130                        UserHandle.USER_SYSTEM, "android");
3131                stubSystemApps.remove(i);
3132                continue;
3133            } catch (PackageManagerException e) {
3134                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3135            }
3136
3137            // any failed attempt to install the package will be cleaned up later
3138        }
3139
3140        // disable any stub still left; these failed to install the full application
3141        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3142            final String pkgName = stubSystemApps.get(i);
3143            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3144            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3145                    UserHandle.USER_SYSTEM, "android");
3146            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3147        }
3148    }
3149
3150    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3151        if (DEBUG_COMPRESSION) {
3152            Slog.i(TAG, "Decompress file"
3153                    + "; src: " + srcFile.getAbsolutePath()
3154                    + ", dst: " + dstFile.getAbsolutePath());
3155        }
3156        try (
3157                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3158                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3159        ) {
3160            Streams.copy(fileIn, fileOut);
3161            Os.chmod(dstFile.getAbsolutePath(), 0644);
3162            return PackageManager.INSTALL_SUCCEEDED;
3163        } catch (IOException e) {
3164            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3165                    + "; src: " + srcFile.getAbsolutePath()
3166                    + ", dst: " + dstFile.getAbsolutePath());
3167        }
3168        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3169    }
3170
3171    private File[] getCompressedFiles(String codePath) {
3172        final File stubCodePath = new File(codePath);
3173        final String stubName = stubCodePath.getName();
3174
3175        // The layout of a compressed package on a given partition is as follows :
3176        //
3177        // Compressed artifacts:
3178        //
3179        // /partition/ModuleName/foo.gz
3180        // /partation/ModuleName/bar.gz
3181        //
3182        // Stub artifact:
3183        //
3184        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3185        //
3186        // In other words, stub is on the same partition as the compressed artifacts
3187        // and in a directory that's suffixed with "-Stub".
3188        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3189        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3190            return null;
3191        }
3192
3193        final File stubParentDir = stubCodePath.getParentFile();
3194        if (stubParentDir == null) {
3195            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3196            return null;
3197        }
3198
3199        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3200        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3201            @Override
3202            public boolean accept(File dir, String name) {
3203                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3204            }
3205        });
3206
3207        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3208            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3209        }
3210
3211        return files;
3212    }
3213
3214    private boolean compressedFileExists(String codePath) {
3215        final File[] compressedFiles = getCompressedFiles(codePath);
3216        return compressedFiles != null && compressedFiles.length > 0;
3217    }
3218
3219    /**
3220     * Decompresses the given package on the system image onto
3221     * the /data partition.
3222     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3223     */
3224    private File decompressPackage(PackageParser.Package pkg) {
3225        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3226        if (compressedFiles == null || compressedFiles.length == 0) {
3227            if (DEBUG_COMPRESSION) {
3228                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3229            }
3230            return null;
3231        }
3232        final File dstCodePath =
3233                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3234        int ret = PackageManager.INSTALL_SUCCEEDED;
3235        try {
3236            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3237            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3238            for (File srcFile : compressedFiles) {
3239                final String srcFileName = srcFile.getName();
3240                final String dstFileName = srcFileName.substring(
3241                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3242                final File dstFile = new File(dstCodePath, dstFileName);
3243                ret = decompressFile(srcFile, dstFile);
3244                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3245                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3246                            + "; pkg: " + pkg.packageName
3247                            + ", file: " + dstFileName);
3248                    break;
3249                }
3250            }
3251        } catch (ErrnoException e) {
3252            logCriticalInfo(Log.ERROR, "Failed to decompress"
3253                    + "; pkg: " + pkg.packageName
3254                    + ", err: " + e.errno);
3255        }
3256        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3257            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3258            NativeLibraryHelper.Handle handle = null;
3259            try {
3260                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3261                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3262                        null /*abiOverride*/);
3263            } catch (IOException e) {
3264                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3265                        + "; pkg: " + pkg.packageName);
3266                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3267            } finally {
3268                IoUtils.closeQuietly(handle);
3269            }
3270        }
3271        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3272            if (dstCodePath == null || !dstCodePath.exists()) {
3273                return null;
3274            }
3275            removeCodePathLI(dstCodePath);
3276            return null;
3277        }
3278
3279        // If we have a profile for a compressed APK, copy it to the reference location.
3280        // Since the package is the stub one, remove the stub suffix to get the normal package and
3281        // APK name.
3282        File profileFile = new File(getPrebuildProfilePath(pkg).replace(STUB_SUFFIX, ""));
3283        if (profileFile.exists()) {
3284            try {
3285                // We could also do this lazily before calling dexopt in
3286                // PackageDexOptimizer to prevent this happening on first boot. The issue
3287                // is that we don't have a good way to say "do this only once".
3288                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
3289                        pkg.applicationInfo.uid, pkg.packageName)) {
3290                    Log.e(TAG, "decompressPackage failed to copy system profile!");
3291                }
3292            } catch (Exception e) {
3293                Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", e);
3294            }
3295        }
3296        return dstCodePath;
3297    }
3298
3299    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3300        // we're only interested in updating the installer appliction when 1) it's not
3301        // already set or 2) the modified package is the installer
3302        if (mInstantAppInstallerActivity != null
3303                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3304                        .equals(modifiedPackage)) {
3305            return;
3306        }
3307        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3308    }
3309
3310    private static File preparePackageParserCache(boolean isUpgrade) {
3311        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3312            return null;
3313        }
3314
3315        // Disable package parsing on eng builds to allow for faster incremental development.
3316        if (Build.IS_ENG) {
3317            return null;
3318        }
3319
3320        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3321            Slog.i(TAG, "Disabling package parser cache due to system property.");
3322            return null;
3323        }
3324
3325        // The base directory for the package parser cache lives under /data/system/.
3326        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3327                "package_cache");
3328        if (cacheBaseDir == null) {
3329            return null;
3330        }
3331
3332        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3333        // This also serves to "GC" unused entries when the package cache version changes (which
3334        // can only happen during upgrades).
3335        if (isUpgrade) {
3336            FileUtils.deleteContents(cacheBaseDir);
3337        }
3338
3339
3340        // Return the versioned package cache directory. This is something like
3341        // "/data/system/package_cache/1"
3342        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3343
3344        // The following is a workaround to aid development on non-numbered userdebug
3345        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3346        // the system partition is newer.
3347        //
3348        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3349        // that starts with "eng." to signify that this is an engineering build and not
3350        // destined for release.
3351        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3352            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3353
3354            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3355            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3356            // in general and should not be used for production changes. In this specific case,
3357            // we know that they will work.
3358            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3359            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3360                FileUtils.deleteContents(cacheBaseDir);
3361                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3362            }
3363        }
3364
3365        return cacheDir;
3366    }
3367
3368    @Override
3369    public boolean isFirstBoot() {
3370        // allow instant applications
3371        return mFirstBoot;
3372    }
3373
3374    @Override
3375    public boolean isOnlyCoreApps() {
3376        // allow instant applications
3377        return mOnlyCore;
3378    }
3379
3380    @Override
3381    public boolean isUpgrade() {
3382        // allow instant applications
3383        return mIsUpgrade;
3384    }
3385
3386    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3387        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3388
3389        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3390                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3391                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3392        if (matches.size() == 1) {
3393            return matches.get(0).getComponentInfo().packageName;
3394        } else if (matches.size() == 0) {
3395            Log.e(TAG, "There should probably be a verifier, but, none were found");
3396            return null;
3397        }
3398        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3399    }
3400
3401    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3402        synchronized (mPackages) {
3403            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3404            if (libraryEntry == null) {
3405                throw new IllegalStateException("Missing required shared library:" + name);
3406            }
3407            return libraryEntry.apk;
3408        }
3409    }
3410
3411    private @NonNull String getRequiredInstallerLPr() {
3412        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3413        intent.addCategory(Intent.CATEGORY_DEFAULT);
3414        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3415
3416        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3417                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3418                UserHandle.USER_SYSTEM);
3419        if (matches.size() == 1) {
3420            ResolveInfo resolveInfo = matches.get(0);
3421            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3422                throw new RuntimeException("The installer must be a privileged app");
3423            }
3424            return matches.get(0).getComponentInfo().packageName;
3425        } else {
3426            throw new RuntimeException("There must be exactly one installer; found " + matches);
3427        }
3428    }
3429
3430    private @NonNull String getRequiredUninstallerLPr() {
3431        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3432        intent.addCategory(Intent.CATEGORY_DEFAULT);
3433        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3434
3435        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3436                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3437                UserHandle.USER_SYSTEM);
3438        if (resolveInfo == null ||
3439                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3440            throw new RuntimeException("There must be exactly one uninstaller; found "
3441                    + resolveInfo);
3442        }
3443        return resolveInfo.getComponentInfo().packageName;
3444    }
3445
3446    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3447        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3448
3449        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3450                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3451                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3452        ResolveInfo best = null;
3453        final int N = matches.size();
3454        for (int i = 0; i < N; i++) {
3455            final ResolveInfo cur = matches.get(i);
3456            final String packageName = cur.getComponentInfo().packageName;
3457            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3458                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3459                continue;
3460            }
3461
3462            if (best == null || cur.priority > best.priority) {
3463                best = cur;
3464            }
3465        }
3466
3467        if (best != null) {
3468            return best.getComponentInfo().getComponentName();
3469        }
3470        Slog.w(TAG, "Intent filter verifier not found");
3471        return null;
3472    }
3473
3474    @Override
3475    public @Nullable ComponentName getInstantAppResolverComponent() {
3476        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3477            return null;
3478        }
3479        synchronized (mPackages) {
3480            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3481            if (instantAppResolver == null) {
3482                return null;
3483            }
3484            return instantAppResolver.first;
3485        }
3486    }
3487
3488    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3489        final String[] packageArray =
3490                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3491        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3492            if (DEBUG_EPHEMERAL) {
3493                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3494            }
3495            return null;
3496        }
3497
3498        final int callingUid = Binder.getCallingUid();
3499        final int resolveFlags =
3500                MATCH_DIRECT_BOOT_AWARE
3501                | MATCH_DIRECT_BOOT_UNAWARE
3502                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3503        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3504        final Intent resolverIntent = new Intent(actionName);
3505        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3506                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3507        // temporarily look for the old action
3508        if (resolvers.size() == 0) {
3509            if (DEBUG_EPHEMERAL) {
3510                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3511            }
3512            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3513            resolverIntent.setAction(actionName);
3514            resolvers = queryIntentServicesInternal(resolverIntent, null,
3515                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3516        }
3517        final int N = resolvers.size();
3518        if (N == 0) {
3519            if (DEBUG_EPHEMERAL) {
3520                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3521            }
3522            return null;
3523        }
3524
3525        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3526        for (int i = 0; i < N; i++) {
3527            final ResolveInfo info = resolvers.get(i);
3528
3529            if (info.serviceInfo == null) {
3530                continue;
3531            }
3532
3533            final String packageName = info.serviceInfo.packageName;
3534            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3535                if (DEBUG_EPHEMERAL) {
3536                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3537                            + " pkg: " + packageName + ", info:" + info);
3538                }
3539                continue;
3540            }
3541
3542            if (DEBUG_EPHEMERAL) {
3543                Slog.v(TAG, "Ephemeral resolver found;"
3544                        + " pkg: " + packageName + ", info:" + info);
3545            }
3546            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3547        }
3548        if (DEBUG_EPHEMERAL) {
3549            Slog.v(TAG, "Ephemeral resolver NOT found");
3550        }
3551        return null;
3552    }
3553
3554    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3555        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3556        intent.addCategory(Intent.CATEGORY_DEFAULT);
3557        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3558
3559        final int resolveFlags =
3560                MATCH_DIRECT_BOOT_AWARE
3561                | MATCH_DIRECT_BOOT_UNAWARE
3562                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3563        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3564                resolveFlags, UserHandle.USER_SYSTEM);
3565        // temporarily look for the old action
3566        if (matches.isEmpty()) {
3567            if (DEBUG_EPHEMERAL) {
3568                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3569            }
3570            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3571            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3572                    resolveFlags, UserHandle.USER_SYSTEM);
3573        }
3574        Iterator<ResolveInfo> iter = matches.iterator();
3575        while (iter.hasNext()) {
3576            final ResolveInfo rInfo = iter.next();
3577            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3578            if (ps != null) {
3579                final PermissionsState permissionsState = ps.getPermissionsState();
3580                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3581                    continue;
3582                }
3583            }
3584            iter.remove();
3585        }
3586        if (matches.size() == 0) {
3587            return null;
3588        } else if (matches.size() == 1) {
3589            return (ActivityInfo) matches.get(0).getComponentInfo();
3590        } else {
3591            throw new RuntimeException(
3592                    "There must be at most one ephemeral installer; found " + matches);
3593        }
3594    }
3595
3596    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3597            @NonNull ComponentName resolver) {
3598        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3599                .addCategory(Intent.CATEGORY_DEFAULT)
3600                .setPackage(resolver.getPackageName());
3601        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3602        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3603                UserHandle.USER_SYSTEM);
3604        // temporarily look for the old action
3605        if (matches.isEmpty()) {
3606            if (DEBUG_EPHEMERAL) {
3607                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3608            }
3609            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3610            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3611                    UserHandle.USER_SYSTEM);
3612        }
3613        if (matches.isEmpty()) {
3614            return null;
3615        }
3616        return matches.get(0).getComponentInfo().getComponentName();
3617    }
3618
3619    private void primeDomainVerificationsLPw(int userId) {
3620        if (DEBUG_DOMAIN_VERIFICATION) {
3621            Slog.d(TAG, "Priming domain verifications in user " + userId);
3622        }
3623
3624        SystemConfig systemConfig = SystemConfig.getInstance();
3625        ArraySet<String> packages = systemConfig.getLinkedApps();
3626
3627        for (String packageName : packages) {
3628            PackageParser.Package pkg = mPackages.get(packageName);
3629            if (pkg != null) {
3630                if (!pkg.isSystemApp()) {
3631                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3632                    continue;
3633                }
3634
3635                ArraySet<String> domains = null;
3636                for (PackageParser.Activity a : pkg.activities) {
3637                    for (ActivityIntentInfo filter : a.intents) {
3638                        if (hasValidDomains(filter)) {
3639                            if (domains == null) {
3640                                domains = new ArraySet<String>();
3641                            }
3642                            domains.addAll(filter.getHostsList());
3643                        }
3644                    }
3645                }
3646
3647                if (domains != null && domains.size() > 0) {
3648                    if (DEBUG_DOMAIN_VERIFICATION) {
3649                        Slog.v(TAG, "      + " + packageName);
3650                    }
3651                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3652                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3653                    // and then 'always' in the per-user state actually used for intent resolution.
3654                    final IntentFilterVerificationInfo ivi;
3655                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3656                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3657                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3658                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3659                } else {
3660                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3661                            + "' does not handle web links");
3662                }
3663            } else {
3664                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3665            }
3666        }
3667
3668        scheduleWritePackageRestrictionsLocked(userId);
3669        scheduleWriteSettingsLocked();
3670    }
3671
3672    private void applyFactoryDefaultBrowserLPw(int userId) {
3673        // The default browser app's package name is stored in a string resource,
3674        // with a product-specific overlay used for vendor customization.
3675        String browserPkg = mContext.getResources().getString(
3676                com.android.internal.R.string.default_browser);
3677        if (!TextUtils.isEmpty(browserPkg)) {
3678            // non-empty string => required to be a known package
3679            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3680            if (ps == null) {
3681                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3682                browserPkg = null;
3683            } else {
3684                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3685            }
3686        }
3687
3688        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3689        // default.  If there's more than one, just leave everything alone.
3690        if (browserPkg == null) {
3691            calculateDefaultBrowserLPw(userId);
3692        }
3693    }
3694
3695    private void calculateDefaultBrowserLPw(int userId) {
3696        List<String> allBrowsers = resolveAllBrowserApps(userId);
3697        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3698        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3699    }
3700
3701    private List<String> resolveAllBrowserApps(int userId) {
3702        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3703        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3704                PackageManager.MATCH_ALL, userId);
3705
3706        final int count = list.size();
3707        List<String> result = new ArrayList<String>(count);
3708        for (int i=0; i<count; i++) {
3709            ResolveInfo info = list.get(i);
3710            if (info.activityInfo == null
3711                    || !info.handleAllWebDataURI
3712                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3713                    || result.contains(info.activityInfo.packageName)) {
3714                continue;
3715            }
3716            result.add(info.activityInfo.packageName);
3717        }
3718
3719        return result;
3720    }
3721
3722    private boolean packageIsBrowser(String packageName, int userId) {
3723        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3724                PackageManager.MATCH_ALL, userId);
3725        final int N = list.size();
3726        for (int i = 0; i < N; i++) {
3727            ResolveInfo info = list.get(i);
3728            if (packageName.equals(info.activityInfo.packageName)) {
3729                return true;
3730            }
3731        }
3732        return false;
3733    }
3734
3735    private void checkDefaultBrowser() {
3736        final int myUserId = UserHandle.myUserId();
3737        final String packageName = getDefaultBrowserPackageName(myUserId);
3738        if (packageName != null) {
3739            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3740            if (info == null) {
3741                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3742                synchronized (mPackages) {
3743                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3744                }
3745            }
3746        }
3747    }
3748
3749    @Override
3750    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3751            throws RemoteException {
3752        try {
3753            return super.onTransact(code, data, reply, flags);
3754        } catch (RuntimeException e) {
3755            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3756                Slog.wtf(TAG, "Package Manager Crash", e);
3757            }
3758            throw e;
3759        }
3760    }
3761
3762    static int[] appendInts(int[] cur, int[] add) {
3763        if (add == null) return cur;
3764        if (cur == null) return add;
3765        final int N = add.length;
3766        for (int i=0; i<N; i++) {
3767            cur = appendInt(cur, add[i]);
3768        }
3769        return cur;
3770    }
3771
3772    /**
3773     * Returns whether or not a full application can see an instant application.
3774     * <p>
3775     * Currently, there are three cases in which this can occur:
3776     * <ol>
3777     * <li>The calling application is a "special" process. The special
3778     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3779     *     and {@code 0}</li>
3780     * <li>The calling application has the permission
3781     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3782     * <li>The calling application is the default launcher on the
3783     *     system partition.</li>
3784     * </ol>
3785     */
3786    private boolean canViewInstantApps(int callingUid, int userId) {
3787        if (callingUid == Process.SYSTEM_UID
3788                || callingUid == Process.SHELL_UID
3789                || callingUid == Process.ROOT_UID) {
3790            return true;
3791        }
3792        if (mContext.checkCallingOrSelfPermission(
3793                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3794            return true;
3795        }
3796        if (mContext.checkCallingOrSelfPermission(
3797                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3798            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3799            if (homeComponent != null
3800                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3801                return true;
3802            }
3803        }
3804        return false;
3805    }
3806
3807    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3808        if (!sUserManager.exists(userId)) return null;
3809        if (ps == null) {
3810            return null;
3811        }
3812        PackageParser.Package p = ps.pkg;
3813        if (p == null) {
3814            return null;
3815        }
3816        final int callingUid = Binder.getCallingUid();
3817        // Filter out ephemeral app metadata:
3818        //   * The system/shell/root can see metadata for any app
3819        //   * An installed app can see metadata for 1) other installed apps
3820        //     and 2) ephemeral apps that have explicitly interacted with it
3821        //   * Ephemeral apps can only see their own data and exposed installed apps
3822        //   * Holding a signature permission allows seeing instant apps
3823        if (filterAppAccessLPr(ps, callingUid, userId)) {
3824            return null;
3825        }
3826
3827        final PermissionsState permissionsState = ps.getPermissionsState();
3828
3829        // Compute GIDs only if requested
3830        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3831                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3832        // Compute granted permissions only if package has requested permissions
3833        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3834                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3835        final PackageUserState state = ps.readUserState(userId);
3836
3837        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3838                && ps.isSystem()) {
3839            flags |= MATCH_ANY_USER;
3840        }
3841
3842        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3843                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3844
3845        if (packageInfo == null) {
3846            return null;
3847        }
3848
3849        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3850                resolveExternalPackageNameLPr(p);
3851
3852        return packageInfo;
3853    }
3854
3855    @Override
3856    public void checkPackageStartable(String packageName, int userId) {
3857        final int callingUid = Binder.getCallingUid();
3858        if (getInstantAppPackageName(callingUid) != null) {
3859            throw new SecurityException("Instant applications don't have access to this method");
3860        }
3861        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3862        synchronized (mPackages) {
3863            final PackageSetting ps = mSettings.mPackages.get(packageName);
3864            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3865                throw new SecurityException("Package " + packageName + " was not found!");
3866            }
3867
3868            if (!ps.getInstalled(userId)) {
3869                throw new SecurityException(
3870                        "Package " + packageName + " was not installed for user " + userId + "!");
3871            }
3872
3873            if (mSafeMode && !ps.isSystem()) {
3874                throw new SecurityException("Package " + packageName + " not a system app!");
3875            }
3876
3877            if (mFrozenPackages.contains(packageName)) {
3878                throw new SecurityException("Package " + packageName + " is currently frozen!");
3879            }
3880
3881            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3882                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3883            }
3884        }
3885    }
3886
3887    @Override
3888    public boolean isPackageAvailable(String packageName, int userId) {
3889        if (!sUserManager.exists(userId)) return false;
3890        final int callingUid = Binder.getCallingUid();
3891        enforceCrossUserPermission(callingUid, userId,
3892                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3893        synchronized (mPackages) {
3894            PackageParser.Package p = mPackages.get(packageName);
3895            if (p != null) {
3896                final PackageSetting ps = (PackageSetting) p.mExtras;
3897                if (filterAppAccessLPr(ps, callingUid, userId)) {
3898                    return false;
3899                }
3900                if (ps != null) {
3901                    final PackageUserState state = ps.readUserState(userId);
3902                    if (state != null) {
3903                        return PackageParser.isAvailable(state);
3904                    }
3905                }
3906            }
3907        }
3908        return false;
3909    }
3910
3911    @Override
3912    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3913        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3914                flags, Binder.getCallingUid(), userId);
3915    }
3916
3917    @Override
3918    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3919            int flags, int userId) {
3920        return getPackageInfoInternal(versionedPackage.getPackageName(),
3921                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3922    }
3923
3924    /**
3925     * Important: The provided filterCallingUid is used exclusively to filter out packages
3926     * that can be seen based on user state. It's typically the original caller uid prior
3927     * to clearing. Because it can only be provided by trusted code, it's value can be
3928     * trusted and will be used as-is; unlike userId which will be validated by this method.
3929     */
3930    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3931            int flags, int filterCallingUid, int userId) {
3932        if (!sUserManager.exists(userId)) return null;
3933        flags = updateFlagsForPackage(flags, userId, packageName);
3934        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3935                false /* requireFullPermission */, false /* checkShell */, "get package info");
3936
3937        // reader
3938        synchronized (mPackages) {
3939            // Normalize package name to handle renamed packages and static libs
3940            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3941
3942            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3943            if (matchFactoryOnly) {
3944                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3945                if (ps != null) {
3946                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3947                        return null;
3948                    }
3949                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3950                        return null;
3951                    }
3952                    return generatePackageInfo(ps, flags, userId);
3953                }
3954            }
3955
3956            PackageParser.Package p = mPackages.get(packageName);
3957            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3958                return null;
3959            }
3960            if (DEBUG_PACKAGE_INFO)
3961                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3962            if (p != null) {
3963                final PackageSetting ps = (PackageSetting) p.mExtras;
3964                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3965                    return null;
3966                }
3967                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3968                    return null;
3969                }
3970                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3971            }
3972            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3973                final PackageSetting ps = mSettings.mPackages.get(packageName);
3974                if (ps == null) return null;
3975                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3976                    return null;
3977                }
3978                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3979                    return null;
3980                }
3981                return generatePackageInfo(ps, flags, userId);
3982            }
3983        }
3984        return null;
3985    }
3986
3987    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3988        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3989            return true;
3990        }
3991        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3992            return true;
3993        }
3994        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3995            return true;
3996        }
3997        return false;
3998    }
3999
4000    private boolean isComponentVisibleToInstantApp(
4001            @Nullable ComponentName component, @ComponentType int type) {
4002        if (type == TYPE_ACTIVITY) {
4003            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4004            return activity != null
4005                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4006                    : false;
4007        } else if (type == TYPE_RECEIVER) {
4008            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4009            return activity != null
4010                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4011                    : false;
4012        } else if (type == TYPE_SERVICE) {
4013            final PackageParser.Service service = mServices.mServices.get(component);
4014            return service != null
4015                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4016                    : false;
4017        } else if (type == TYPE_PROVIDER) {
4018            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4019            return provider != null
4020                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4021                    : false;
4022        } else if (type == TYPE_UNKNOWN) {
4023            return isComponentVisibleToInstantApp(component);
4024        }
4025        return false;
4026    }
4027
4028    /**
4029     * Returns whether or not access to the application should be filtered.
4030     * <p>
4031     * Access may be limited based upon whether the calling or target applications
4032     * are instant applications.
4033     *
4034     * @see #canAccessInstantApps(int)
4035     */
4036    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4037            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4038        // if we're in an isolated process, get the real calling UID
4039        if (Process.isIsolated(callingUid)) {
4040            callingUid = mIsolatedOwners.get(callingUid);
4041        }
4042        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4043        final boolean callerIsInstantApp = instantAppPkgName != null;
4044        if (ps == null) {
4045            if (callerIsInstantApp) {
4046                // pretend the application exists, but, needs to be filtered
4047                return true;
4048            }
4049            return false;
4050        }
4051        // if the target and caller are the same application, don't filter
4052        if (isCallerSameApp(ps.name, callingUid)) {
4053            return false;
4054        }
4055        if (callerIsInstantApp) {
4056            // request for a specific component; if it hasn't been explicitly exposed, filter
4057            if (component != null) {
4058                return !isComponentVisibleToInstantApp(component, componentType);
4059            }
4060            // request for application; if no components have been explicitly exposed, filter
4061            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4062        }
4063        if (ps.getInstantApp(userId)) {
4064            // caller can see all components of all instant applications, don't filter
4065            if (canViewInstantApps(callingUid, userId)) {
4066                return false;
4067            }
4068            // request for a specific instant application component, filter
4069            if (component != null) {
4070                return true;
4071            }
4072            // request for an instant application; if the caller hasn't been granted access, filter
4073            return !mInstantAppRegistry.isInstantAccessGranted(
4074                    userId, UserHandle.getAppId(callingUid), ps.appId);
4075        }
4076        return false;
4077    }
4078
4079    /**
4080     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4081     */
4082    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4083        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4084    }
4085
4086    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4087            int flags) {
4088        // Callers can access only the libs they depend on, otherwise they need to explicitly
4089        // ask for the shared libraries given the caller is allowed to access all static libs.
4090        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4091            // System/shell/root get to see all static libs
4092            final int appId = UserHandle.getAppId(uid);
4093            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4094                    || appId == Process.ROOT_UID) {
4095                return false;
4096            }
4097        }
4098
4099        // No package means no static lib as it is always on internal storage
4100        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4101            return false;
4102        }
4103
4104        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4105                ps.pkg.staticSharedLibVersion);
4106        if (libEntry == null) {
4107            return false;
4108        }
4109
4110        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4111        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4112        if (uidPackageNames == null) {
4113            return true;
4114        }
4115
4116        for (String uidPackageName : uidPackageNames) {
4117            if (ps.name.equals(uidPackageName)) {
4118                return false;
4119            }
4120            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4121            if (uidPs != null) {
4122                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4123                        libEntry.info.getName());
4124                if (index < 0) {
4125                    continue;
4126                }
4127                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4128                    return false;
4129                }
4130            }
4131        }
4132        return true;
4133    }
4134
4135    @Override
4136    public String[] currentToCanonicalPackageNames(String[] names) {
4137        final int callingUid = Binder.getCallingUid();
4138        if (getInstantAppPackageName(callingUid) != null) {
4139            return names;
4140        }
4141        final String[] out = new String[names.length];
4142        // reader
4143        synchronized (mPackages) {
4144            final int callingUserId = UserHandle.getUserId(callingUid);
4145            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4146            for (int i=names.length-1; i>=0; i--) {
4147                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4148                boolean translateName = false;
4149                if (ps != null && ps.realName != null) {
4150                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4151                    translateName = !targetIsInstantApp
4152                            || canViewInstantApps
4153                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4154                                    UserHandle.getAppId(callingUid), ps.appId);
4155                }
4156                out[i] = translateName ? ps.realName : names[i];
4157            }
4158        }
4159        return out;
4160    }
4161
4162    @Override
4163    public String[] canonicalToCurrentPackageNames(String[] names) {
4164        final int callingUid = Binder.getCallingUid();
4165        if (getInstantAppPackageName(callingUid) != null) {
4166            return names;
4167        }
4168        final String[] out = new String[names.length];
4169        // reader
4170        synchronized (mPackages) {
4171            final int callingUserId = UserHandle.getUserId(callingUid);
4172            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4173            for (int i=names.length-1; i>=0; i--) {
4174                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4175                boolean translateName = false;
4176                if (cur != null) {
4177                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4178                    final boolean targetIsInstantApp =
4179                            ps != null && ps.getInstantApp(callingUserId);
4180                    translateName = !targetIsInstantApp
4181                            || canViewInstantApps
4182                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4183                                    UserHandle.getAppId(callingUid), ps.appId);
4184                }
4185                out[i] = translateName ? cur : names[i];
4186            }
4187        }
4188        return out;
4189    }
4190
4191    @Override
4192    public int getPackageUid(String packageName, int flags, int userId) {
4193        if (!sUserManager.exists(userId)) return -1;
4194        final int callingUid = Binder.getCallingUid();
4195        flags = updateFlagsForPackage(flags, userId, packageName);
4196        enforceCrossUserPermission(callingUid, userId,
4197                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4198
4199        // reader
4200        synchronized (mPackages) {
4201            final PackageParser.Package p = mPackages.get(packageName);
4202            if (p != null && p.isMatch(flags)) {
4203                PackageSetting ps = (PackageSetting) p.mExtras;
4204                if (filterAppAccessLPr(ps, callingUid, userId)) {
4205                    return -1;
4206                }
4207                return UserHandle.getUid(userId, p.applicationInfo.uid);
4208            }
4209            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4210                final PackageSetting ps = mSettings.mPackages.get(packageName);
4211                if (ps != null && ps.isMatch(flags)
4212                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4213                    return UserHandle.getUid(userId, ps.appId);
4214                }
4215            }
4216        }
4217
4218        return -1;
4219    }
4220
4221    @Override
4222    public int[] getPackageGids(String packageName, int flags, int userId) {
4223        if (!sUserManager.exists(userId)) return null;
4224        final int callingUid = Binder.getCallingUid();
4225        flags = updateFlagsForPackage(flags, userId, packageName);
4226        enforceCrossUserPermission(callingUid, userId,
4227                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4228
4229        // reader
4230        synchronized (mPackages) {
4231            final PackageParser.Package p = mPackages.get(packageName);
4232            if (p != null && p.isMatch(flags)) {
4233                PackageSetting ps = (PackageSetting) p.mExtras;
4234                if (filterAppAccessLPr(ps, callingUid, userId)) {
4235                    return null;
4236                }
4237                // TODO: Shouldn't this be checking for package installed state for userId and
4238                // return null?
4239                return ps.getPermissionsState().computeGids(userId);
4240            }
4241            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4242                final PackageSetting ps = mSettings.mPackages.get(packageName);
4243                if (ps != null && ps.isMatch(flags)
4244                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4245                    return ps.getPermissionsState().computeGids(userId);
4246                }
4247            }
4248        }
4249
4250        return null;
4251    }
4252
4253    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4254        if (bp.perm != null) {
4255            return PackageParser.generatePermissionInfo(bp.perm, flags);
4256        }
4257        PermissionInfo pi = new PermissionInfo();
4258        pi.name = bp.name;
4259        pi.packageName = bp.sourcePackage;
4260        pi.nonLocalizedLabel = bp.name;
4261        pi.protectionLevel = bp.protectionLevel;
4262        return pi;
4263    }
4264
4265    @Override
4266    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4267        final int callingUid = Binder.getCallingUid();
4268        if (getInstantAppPackageName(callingUid) != null) {
4269            return null;
4270        }
4271        // reader
4272        synchronized (mPackages) {
4273            final BasePermission p = mSettings.mPermissions.get(name);
4274            if (p == null) {
4275                return null;
4276            }
4277            // If the caller is an app that targets pre 26 SDK drop protection flags.
4278            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4279            if (permissionInfo != null) {
4280                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4281                        permissionInfo.protectionLevel, packageName, callingUid);
4282                if (permissionInfo.protectionLevel != protectionLevel) {
4283                    // If we return different protection level, don't use the cached info
4284                    if (p.perm != null && p.perm.info == permissionInfo) {
4285                        permissionInfo = new PermissionInfo(permissionInfo);
4286                    }
4287                    permissionInfo.protectionLevel = protectionLevel;
4288                }
4289            }
4290            return permissionInfo;
4291        }
4292    }
4293
4294    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4295            String packageName, int uid) {
4296        // Signature permission flags area always reported
4297        final int protectionLevelMasked = protectionLevel
4298                & (PermissionInfo.PROTECTION_NORMAL
4299                | PermissionInfo.PROTECTION_DANGEROUS
4300                | PermissionInfo.PROTECTION_SIGNATURE);
4301        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4302            return protectionLevel;
4303        }
4304
4305        // System sees all flags.
4306        final int appId = UserHandle.getAppId(uid);
4307        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4308                || appId == Process.SHELL_UID) {
4309            return protectionLevel;
4310        }
4311
4312        // Normalize package name to handle renamed packages and static libs
4313        packageName = resolveInternalPackageNameLPr(packageName,
4314                PackageManager.VERSION_CODE_HIGHEST);
4315
4316        // Apps that target O see flags for all protection levels.
4317        final PackageSetting ps = mSettings.mPackages.get(packageName);
4318        if (ps == null) {
4319            return protectionLevel;
4320        }
4321        if (ps.appId != appId) {
4322            return protectionLevel;
4323        }
4324
4325        final PackageParser.Package pkg = mPackages.get(packageName);
4326        if (pkg == null) {
4327            return protectionLevel;
4328        }
4329        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4330            return protectionLevelMasked;
4331        }
4332
4333        return protectionLevel;
4334    }
4335
4336    @Override
4337    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4338            int flags) {
4339        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4340            return null;
4341        }
4342        // reader
4343        synchronized (mPackages) {
4344            if (group != null && !mPermissionGroups.containsKey(group)) {
4345                // This is thrown as NameNotFoundException
4346                return null;
4347            }
4348
4349            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4350            for (BasePermission p : mSettings.mPermissions.values()) {
4351                if (group == null) {
4352                    if (p.perm == null || p.perm.info.group == null) {
4353                        out.add(generatePermissionInfo(p, flags));
4354                    }
4355                } else {
4356                    if (p.perm != null && group.equals(p.perm.info.group)) {
4357                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4358                    }
4359                }
4360            }
4361            return new ParceledListSlice<>(out);
4362        }
4363    }
4364
4365    @Override
4366    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4367        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4368            return null;
4369        }
4370        // reader
4371        synchronized (mPackages) {
4372            return PackageParser.generatePermissionGroupInfo(
4373                    mPermissionGroups.get(name), flags);
4374        }
4375    }
4376
4377    @Override
4378    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4379        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4380            return ParceledListSlice.emptyList();
4381        }
4382        // reader
4383        synchronized (mPackages) {
4384            final int N = mPermissionGroups.size();
4385            ArrayList<PermissionGroupInfo> out
4386                    = new ArrayList<PermissionGroupInfo>(N);
4387            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4388                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4389            }
4390            return new ParceledListSlice<>(out);
4391        }
4392    }
4393
4394    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4395            int filterCallingUid, int userId) {
4396        if (!sUserManager.exists(userId)) return null;
4397        PackageSetting ps = mSettings.mPackages.get(packageName);
4398        if (ps != null) {
4399            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4400                return null;
4401            }
4402            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4403                return null;
4404            }
4405            if (ps.pkg == null) {
4406                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4407                if (pInfo != null) {
4408                    return pInfo.applicationInfo;
4409                }
4410                return null;
4411            }
4412            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4413                    ps.readUserState(userId), userId);
4414            if (ai != null) {
4415                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4416            }
4417            return ai;
4418        }
4419        return null;
4420    }
4421
4422    @Override
4423    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4424        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4425    }
4426
4427    /**
4428     * Important: The provided filterCallingUid is used exclusively to filter out applications
4429     * that can be seen based on user state. It's typically the original caller uid prior
4430     * to clearing. Because it can only be provided by trusted code, it's value can be
4431     * trusted and will be used as-is; unlike userId which will be validated by this method.
4432     */
4433    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4434            int filterCallingUid, int userId) {
4435        if (!sUserManager.exists(userId)) return null;
4436        flags = updateFlagsForApplication(flags, userId, packageName);
4437        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4438                false /* requireFullPermission */, false /* checkShell */, "get application info");
4439
4440        // writer
4441        synchronized (mPackages) {
4442            // Normalize package name to handle renamed packages and static libs
4443            packageName = resolveInternalPackageNameLPr(packageName,
4444                    PackageManager.VERSION_CODE_HIGHEST);
4445
4446            PackageParser.Package p = mPackages.get(packageName);
4447            if (DEBUG_PACKAGE_INFO) Log.v(
4448                    TAG, "getApplicationInfo " + packageName
4449                    + ": " + p);
4450            if (p != null) {
4451                PackageSetting ps = mSettings.mPackages.get(packageName);
4452                if (ps == null) return null;
4453                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4454                    return null;
4455                }
4456                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4457                    return null;
4458                }
4459                // Note: isEnabledLP() does not apply here - always return info
4460                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4461                        p, flags, ps.readUserState(userId), userId);
4462                if (ai != null) {
4463                    ai.packageName = resolveExternalPackageNameLPr(p);
4464                }
4465                return ai;
4466            }
4467            if ("android".equals(packageName)||"system".equals(packageName)) {
4468                return mAndroidApplication;
4469            }
4470            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4471                // Already generates the external package name
4472                return generateApplicationInfoFromSettingsLPw(packageName,
4473                        flags, filterCallingUid, userId);
4474            }
4475        }
4476        return null;
4477    }
4478
4479    private String normalizePackageNameLPr(String packageName) {
4480        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4481        return normalizedPackageName != null ? normalizedPackageName : packageName;
4482    }
4483
4484    @Override
4485    public void deletePreloadsFileCache() {
4486        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4487            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4488        }
4489        File dir = Environment.getDataPreloadsFileCacheDirectory();
4490        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4491        FileUtils.deleteContents(dir);
4492    }
4493
4494    @Override
4495    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4496            final int storageFlags, final IPackageDataObserver observer) {
4497        mContext.enforceCallingOrSelfPermission(
4498                android.Manifest.permission.CLEAR_APP_CACHE, null);
4499        mHandler.post(() -> {
4500            boolean success = false;
4501            try {
4502                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4503                success = true;
4504            } catch (IOException e) {
4505                Slog.w(TAG, e);
4506            }
4507            if (observer != null) {
4508                try {
4509                    observer.onRemoveCompleted(null, success);
4510                } catch (RemoteException e) {
4511                    Slog.w(TAG, e);
4512                }
4513            }
4514        });
4515    }
4516
4517    @Override
4518    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4519            final int storageFlags, final IntentSender pi) {
4520        mContext.enforceCallingOrSelfPermission(
4521                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4522        mHandler.post(() -> {
4523            boolean success = false;
4524            try {
4525                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4526                success = true;
4527            } catch (IOException e) {
4528                Slog.w(TAG, e);
4529            }
4530            if (pi != null) {
4531                try {
4532                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4533                } catch (SendIntentException e) {
4534                    Slog.w(TAG, e);
4535                }
4536            }
4537        });
4538    }
4539
4540    /**
4541     * Blocking call to clear various types of cached data across the system
4542     * until the requested bytes are available.
4543     */
4544    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4545        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4546        final File file = storage.findPathForUuid(volumeUuid);
4547        if (file.getUsableSpace() >= bytes) return;
4548
4549        if (ENABLE_FREE_CACHE_V2) {
4550            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4551                    volumeUuid);
4552            final boolean aggressive = (storageFlags
4553                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4554            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4555
4556            // 1. Pre-flight to determine if we have any chance to succeed
4557            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4558            if (internalVolume && (aggressive || SystemProperties
4559                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4560                deletePreloadsFileCache();
4561                if (file.getUsableSpace() >= bytes) return;
4562            }
4563
4564            // 3. Consider parsed APK data (aggressive only)
4565            if (internalVolume && aggressive) {
4566                FileUtils.deleteContents(mCacheDir);
4567                if (file.getUsableSpace() >= bytes) return;
4568            }
4569
4570            // 4. Consider cached app data (above quotas)
4571            try {
4572                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4573                        Installer.FLAG_FREE_CACHE_V2);
4574            } catch (InstallerException ignored) {
4575            }
4576            if (file.getUsableSpace() >= bytes) return;
4577
4578            // 5. Consider shared libraries with refcount=0 and age>min cache period
4579            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4580                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4581                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4582                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4583                return;
4584            }
4585
4586            // 6. Consider dexopt output (aggressive only)
4587            // TODO: Implement
4588
4589            // 7. Consider installed instant apps unused longer than min cache period
4590            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4591                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4592                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4593                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4594                return;
4595            }
4596
4597            // 8. Consider cached app data (below quotas)
4598            try {
4599                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4600                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4601            } catch (InstallerException ignored) {
4602            }
4603            if (file.getUsableSpace() >= bytes) return;
4604
4605            // 9. Consider DropBox entries
4606            // TODO: Implement
4607
4608            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4609            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4610                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4611                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4612                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4613                return;
4614            }
4615        } else {
4616            try {
4617                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4618            } catch (InstallerException ignored) {
4619            }
4620            if (file.getUsableSpace() >= bytes) return;
4621        }
4622
4623        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4624    }
4625
4626    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4627            throws IOException {
4628        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4629        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4630
4631        List<VersionedPackage> packagesToDelete = null;
4632        final long now = System.currentTimeMillis();
4633
4634        synchronized (mPackages) {
4635            final int[] allUsers = sUserManager.getUserIds();
4636            final int libCount = mSharedLibraries.size();
4637            for (int i = 0; i < libCount; i++) {
4638                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4639                if (versionedLib == null) {
4640                    continue;
4641                }
4642                final int versionCount = versionedLib.size();
4643                for (int j = 0; j < versionCount; j++) {
4644                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4645                    // Skip packages that are not static shared libs.
4646                    if (!libInfo.isStatic()) {
4647                        break;
4648                    }
4649                    // Important: We skip static shared libs used for some user since
4650                    // in such a case we need to keep the APK on the device. The check for
4651                    // a lib being used for any user is performed by the uninstall call.
4652                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4653                    // Resolve the package name - we use synthetic package names internally
4654                    final String internalPackageName = resolveInternalPackageNameLPr(
4655                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4656                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4657                    // Skip unused static shared libs cached less than the min period
4658                    // to prevent pruning a lib needed by a subsequently installed package.
4659                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4660                        continue;
4661                    }
4662                    if (packagesToDelete == null) {
4663                        packagesToDelete = new ArrayList<>();
4664                    }
4665                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4666                            declaringPackage.getVersionCode()));
4667                }
4668            }
4669        }
4670
4671        if (packagesToDelete != null) {
4672            final int packageCount = packagesToDelete.size();
4673            for (int i = 0; i < packageCount; i++) {
4674                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4675                // Delete the package synchronously (will fail of the lib used for any user).
4676                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4677                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4678                                == PackageManager.DELETE_SUCCEEDED) {
4679                    if (volume.getUsableSpace() >= neededSpace) {
4680                        return true;
4681                    }
4682                }
4683            }
4684        }
4685
4686        return false;
4687    }
4688
4689    /**
4690     * Update given flags based on encryption status of current user.
4691     */
4692    private int updateFlags(int flags, int userId) {
4693        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4694                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4695            // Caller expressed an explicit opinion about what encryption
4696            // aware/unaware components they want to see, so fall through and
4697            // give them what they want
4698        } else {
4699            // Caller expressed no opinion, so match based on user state
4700            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4701                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4702            } else {
4703                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4704            }
4705        }
4706        return flags;
4707    }
4708
4709    private UserManagerInternal getUserManagerInternal() {
4710        if (mUserManagerInternal == null) {
4711            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4712        }
4713        return mUserManagerInternal;
4714    }
4715
4716    private DeviceIdleController.LocalService getDeviceIdleController() {
4717        if (mDeviceIdleController == null) {
4718            mDeviceIdleController =
4719                    LocalServices.getService(DeviceIdleController.LocalService.class);
4720        }
4721        return mDeviceIdleController;
4722    }
4723
4724    /**
4725     * Update given flags when being used to request {@link PackageInfo}.
4726     */
4727    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4728        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4729        boolean triaged = true;
4730        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4731                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4732            // Caller is asking for component details, so they'd better be
4733            // asking for specific encryption matching behavior, or be triaged
4734            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4735                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4736                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4737                triaged = false;
4738            }
4739        }
4740        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4741                | PackageManager.MATCH_SYSTEM_ONLY
4742                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4743            triaged = false;
4744        }
4745        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4746            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4747                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4748                    + Debug.getCallers(5));
4749        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4750                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4751            // If the caller wants all packages and has a restricted profile associated with it,
4752            // then match all users. This is to make sure that launchers that need to access work
4753            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4754            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4755            flags |= PackageManager.MATCH_ANY_USER;
4756        }
4757        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4758            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4759                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4760        }
4761        return updateFlags(flags, userId);
4762    }
4763
4764    /**
4765     * Update given flags when being used to request {@link ApplicationInfo}.
4766     */
4767    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4768        return updateFlagsForPackage(flags, userId, cookie);
4769    }
4770
4771    /**
4772     * Update given flags when being used to request {@link ComponentInfo}.
4773     */
4774    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4775        if (cookie instanceof Intent) {
4776            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4777                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4778            }
4779        }
4780
4781        boolean triaged = true;
4782        // Caller is asking for component details, so they'd better be
4783        // asking for specific encryption matching behavior, or be triaged
4784        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4785                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4786                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4787            triaged = false;
4788        }
4789        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4790            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4791                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4792        }
4793
4794        return updateFlags(flags, userId);
4795    }
4796
4797    /**
4798     * Update given intent when being used to request {@link ResolveInfo}.
4799     */
4800    private Intent updateIntentForResolve(Intent intent) {
4801        if (intent.getSelector() != null) {
4802            intent = intent.getSelector();
4803        }
4804        if (DEBUG_PREFERRED) {
4805            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4806        }
4807        return intent;
4808    }
4809
4810    /**
4811     * Update given flags when being used to request {@link ResolveInfo}.
4812     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4813     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4814     * flag set. However, this flag is only honoured in three circumstances:
4815     * <ul>
4816     * <li>when called from a system process</li>
4817     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4818     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4819     * action and a {@code android.intent.category.BROWSABLE} category</li>
4820     * </ul>
4821     */
4822    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4823        return updateFlagsForResolve(flags, userId, intent, callingUid,
4824                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4825    }
4826    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4827            boolean wantInstantApps) {
4828        return updateFlagsForResolve(flags, userId, intent, callingUid,
4829                wantInstantApps, false /*onlyExposedExplicitly*/);
4830    }
4831    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4832            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4833        // Safe mode means we shouldn't match any third-party components
4834        if (mSafeMode) {
4835            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4836        }
4837        if (getInstantAppPackageName(callingUid) != null) {
4838            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4839            if (onlyExposedExplicitly) {
4840                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4841            }
4842            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4843            flags |= PackageManager.MATCH_INSTANT;
4844        } else {
4845            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4846            final boolean allowMatchInstant =
4847                    (wantInstantApps
4848                            && Intent.ACTION_VIEW.equals(intent.getAction())
4849                            && hasWebURI(intent))
4850                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4851            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4852                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4853            if (!allowMatchInstant) {
4854                flags &= ~PackageManager.MATCH_INSTANT;
4855            }
4856        }
4857        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4858    }
4859
4860    @Override
4861    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4862        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4863    }
4864
4865    /**
4866     * Important: The provided filterCallingUid is used exclusively to filter out activities
4867     * that can be seen based on user state. It's typically the original caller uid prior
4868     * to clearing. Because it can only be provided by trusted code, it's value can be
4869     * trusted and will be used as-is; unlike userId which will be validated by this method.
4870     */
4871    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4872            int filterCallingUid, int userId) {
4873        if (!sUserManager.exists(userId)) return null;
4874        flags = updateFlagsForComponent(flags, userId, component);
4875        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4876                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4877        synchronized (mPackages) {
4878            PackageParser.Activity a = mActivities.mActivities.get(component);
4879
4880            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4881            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4882                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4883                if (ps == null) return null;
4884                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4885                    return null;
4886                }
4887                return PackageParser.generateActivityInfo(
4888                        a, flags, ps.readUserState(userId), userId);
4889            }
4890            if (mResolveComponentName.equals(component)) {
4891                return PackageParser.generateActivityInfo(
4892                        mResolveActivity, flags, new PackageUserState(), userId);
4893            }
4894        }
4895        return null;
4896    }
4897
4898    @Override
4899    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4900            String resolvedType) {
4901        synchronized (mPackages) {
4902            if (component.equals(mResolveComponentName)) {
4903                // The resolver supports EVERYTHING!
4904                return true;
4905            }
4906            final int callingUid = Binder.getCallingUid();
4907            final int callingUserId = UserHandle.getUserId(callingUid);
4908            PackageParser.Activity a = mActivities.mActivities.get(component);
4909            if (a == null) {
4910                return false;
4911            }
4912            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4913            if (ps == null) {
4914                return false;
4915            }
4916            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4917                return false;
4918            }
4919            for (int i=0; i<a.intents.size(); i++) {
4920                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4921                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4922                    return true;
4923                }
4924            }
4925            return false;
4926        }
4927    }
4928
4929    @Override
4930    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4931        if (!sUserManager.exists(userId)) return null;
4932        final int callingUid = Binder.getCallingUid();
4933        flags = updateFlagsForComponent(flags, userId, component);
4934        enforceCrossUserPermission(callingUid, userId,
4935                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4936        synchronized (mPackages) {
4937            PackageParser.Activity a = mReceivers.mActivities.get(component);
4938            if (DEBUG_PACKAGE_INFO) Log.v(
4939                TAG, "getReceiverInfo " + component + ": " + a);
4940            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4941                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4942                if (ps == null) return null;
4943                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4944                    return null;
4945                }
4946                return PackageParser.generateActivityInfo(
4947                        a, flags, ps.readUserState(userId), userId);
4948            }
4949        }
4950        return null;
4951    }
4952
4953    @Override
4954    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4955            int flags, int userId) {
4956        if (!sUserManager.exists(userId)) return null;
4957        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4958        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4959            return null;
4960        }
4961
4962        flags = updateFlagsForPackage(flags, userId, null);
4963
4964        final boolean canSeeStaticLibraries =
4965                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4966                        == PERMISSION_GRANTED
4967                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4968                        == PERMISSION_GRANTED
4969                || canRequestPackageInstallsInternal(packageName,
4970                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4971                        false  /* throwIfPermNotDeclared*/)
4972                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4973                        == PERMISSION_GRANTED;
4974
4975        synchronized (mPackages) {
4976            List<SharedLibraryInfo> result = null;
4977
4978            final int libCount = mSharedLibraries.size();
4979            for (int i = 0; i < libCount; i++) {
4980                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4981                if (versionedLib == null) {
4982                    continue;
4983                }
4984
4985                final int versionCount = versionedLib.size();
4986                for (int j = 0; j < versionCount; j++) {
4987                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4988                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4989                        break;
4990                    }
4991                    final long identity = Binder.clearCallingIdentity();
4992                    try {
4993                        PackageInfo packageInfo = getPackageInfoVersioned(
4994                                libInfo.getDeclaringPackage(), flags
4995                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4996                        if (packageInfo == null) {
4997                            continue;
4998                        }
4999                    } finally {
5000                        Binder.restoreCallingIdentity(identity);
5001                    }
5002
5003                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5004                            libInfo.getVersion(), libInfo.getType(),
5005                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5006                            flags, userId));
5007
5008                    if (result == null) {
5009                        result = new ArrayList<>();
5010                    }
5011                    result.add(resLibInfo);
5012                }
5013            }
5014
5015            return result != null ? new ParceledListSlice<>(result) : null;
5016        }
5017    }
5018
5019    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5020            SharedLibraryInfo libInfo, int flags, int userId) {
5021        List<VersionedPackage> versionedPackages = null;
5022        final int packageCount = mSettings.mPackages.size();
5023        for (int i = 0; i < packageCount; i++) {
5024            PackageSetting ps = mSettings.mPackages.valueAt(i);
5025
5026            if (ps == null) {
5027                continue;
5028            }
5029
5030            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5031                continue;
5032            }
5033
5034            final String libName = libInfo.getName();
5035            if (libInfo.isStatic()) {
5036                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5037                if (libIdx < 0) {
5038                    continue;
5039                }
5040                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5041                    continue;
5042                }
5043                if (versionedPackages == null) {
5044                    versionedPackages = new ArrayList<>();
5045                }
5046                // If the dependent is a static shared lib, use the public package name
5047                String dependentPackageName = ps.name;
5048                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5049                    dependentPackageName = ps.pkg.manifestPackageName;
5050                }
5051                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5052            } else if (ps.pkg != null) {
5053                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5054                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5055                    if (versionedPackages == null) {
5056                        versionedPackages = new ArrayList<>();
5057                    }
5058                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5059                }
5060            }
5061        }
5062
5063        return versionedPackages;
5064    }
5065
5066    @Override
5067    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5068        if (!sUserManager.exists(userId)) return null;
5069        final int callingUid = Binder.getCallingUid();
5070        flags = updateFlagsForComponent(flags, userId, component);
5071        enforceCrossUserPermission(callingUid, userId,
5072                false /* requireFullPermission */, false /* checkShell */, "get service info");
5073        synchronized (mPackages) {
5074            PackageParser.Service s = mServices.mServices.get(component);
5075            if (DEBUG_PACKAGE_INFO) Log.v(
5076                TAG, "getServiceInfo " + component + ": " + s);
5077            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5078                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5079                if (ps == null) return null;
5080                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5081                    return null;
5082                }
5083                return PackageParser.generateServiceInfo(
5084                        s, flags, ps.readUserState(userId), userId);
5085            }
5086        }
5087        return null;
5088    }
5089
5090    @Override
5091    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5092        if (!sUserManager.exists(userId)) return null;
5093        final int callingUid = Binder.getCallingUid();
5094        flags = updateFlagsForComponent(flags, userId, component);
5095        enforceCrossUserPermission(callingUid, userId,
5096                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5097        synchronized (mPackages) {
5098            PackageParser.Provider p = mProviders.mProviders.get(component);
5099            if (DEBUG_PACKAGE_INFO) Log.v(
5100                TAG, "getProviderInfo " + component + ": " + p);
5101            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5102                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5103                if (ps == null) return null;
5104                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5105                    return null;
5106                }
5107                return PackageParser.generateProviderInfo(
5108                        p, flags, ps.readUserState(userId), userId);
5109            }
5110        }
5111        return null;
5112    }
5113
5114    @Override
5115    public String[] getSystemSharedLibraryNames() {
5116        // allow instant applications
5117        synchronized (mPackages) {
5118            Set<String> libs = null;
5119            final int libCount = mSharedLibraries.size();
5120            for (int i = 0; i < libCount; i++) {
5121                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5122                if (versionedLib == null) {
5123                    continue;
5124                }
5125                final int versionCount = versionedLib.size();
5126                for (int j = 0; j < versionCount; j++) {
5127                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5128                    if (!libEntry.info.isStatic()) {
5129                        if (libs == null) {
5130                            libs = new ArraySet<>();
5131                        }
5132                        libs.add(libEntry.info.getName());
5133                        break;
5134                    }
5135                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5136                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5137                            UserHandle.getUserId(Binder.getCallingUid()),
5138                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5139                        if (libs == null) {
5140                            libs = new ArraySet<>();
5141                        }
5142                        libs.add(libEntry.info.getName());
5143                        break;
5144                    }
5145                }
5146            }
5147
5148            if (libs != null) {
5149                String[] libsArray = new String[libs.size()];
5150                libs.toArray(libsArray);
5151                return libsArray;
5152            }
5153
5154            return null;
5155        }
5156    }
5157
5158    @Override
5159    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5160        // allow instant applications
5161        synchronized (mPackages) {
5162            return mServicesSystemSharedLibraryPackageName;
5163        }
5164    }
5165
5166    @Override
5167    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5168        // allow instant applications
5169        synchronized (mPackages) {
5170            return mSharedSystemSharedLibraryPackageName;
5171        }
5172    }
5173
5174    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5175        for (int i = userList.length - 1; i >= 0; --i) {
5176            final int userId = userList[i];
5177            // don't add instant app to the list of updates
5178            if (pkgSetting.getInstantApp(userId)) {
5179                continue;
5180            }
5181            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5182            if (changedPackages == null) {
5183                changedPackages = new SparseArray<>();
5184                mChangedPackages.put(userId, changedPackages);
5185            }
5186            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5187            if (sequenceNumbers == null) {
5188                sequenceNumbers = new HashMap<>();
5189                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5190            }
5191            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5192            if (sequenceNumber != null) {
5193                changedPackages.remove(sequenceNumber);
5194            }
5195            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5196            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5197        }
5198        mChangedPackagesSequenceNumber++;
5199    }
5200
5201    @Override
5202    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5203        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5204            return null;
5205        }
5206        synchronized (mPackages) {
5207            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5208                return null;
5209            }
5210            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5211            if (changedPackages == null) {
5212                return null;
5213            }
5214            final List<String> packageNames =
5215                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5216            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5217                final String packageName = changedPackages.get(i);
5218                if (packageName != null) {
5219                    packageNames.add(packageName);
5220                }
5221            }
5222            return packageNames.isEmpty()
5223                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5224        }
5225    }
5226
5227    @Override
5228    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5229        // allow instant applications
5230        ArrayList<FeatureInfo> res;
5231        synchronized (mAvailableFeatures) {
5232            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5233            res.addAll(mAvailableFeatures.values());
5234        }
5235        final FeatureInfo fi = new FeatureInfo();
5236        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5237                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5238        res.add(fi);
5239
5240        return new ParceledListSlice<>(res);
5241    }
5242
5243    @Override
5244    public boolean hasSystemFeature(String name, int version) {
5245        // allow instant applications
5246        synchronized (mAvailableFeatures) {
5247            final FeatureInfo feat = mAvailableFeatures.get(name);
5248            if (feat == null) {
5249                return false;
5250            } else {
5251                return feat.version >= version;
5252            }
5253        }
5254    }
5255
5256    @Override
5257    public int checkPermission(String permName, String pkgName, int userId) {
5258        if (!sUserManager.exists(userId)) {
5259            return PackageManager.PERMISSION_DENIED;
5260        }
5261        final int callingUid = Binder.getCallingUid();
5262
5263        synchronized (mPackages) {
5264            final PackageParser.Package p = mPackages.get(pkgName);
5265            if (p != null && p.mExtras != null) {
5266                final PackageSetting ps = (PackageSetting) p.mExtras;
5267                if (filterAppAccessLPr(ps, callingUid, userId)) {
5268                    return PackageManager.PERMISSION_DENIED;
5269                }
5270                final boolean instantApp = ps.getInstantApp(userId);
5271                final PermissionsState permissionsState = ps.getPermissionsState();
5272                if (permissionsState.hasPermission(permName, userId)) {
5273                    if (instantApp) {
5274                        BasePermission bp = mSettings.mPermissions.get(permName);
5275                        if (bp != null && bp.isInstant()) {
5276                            return PackageManager.PERMISSION_GRANTED;
5277                        }
5278                    } else {
5279                        return PackageManager.PERMISSION_GRANTED;
5280                    }
5281                }
5282                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5283                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5284                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5285                    return PackageManager.PERMISSION_GRANTED;
5286                }
5287            }
5288        }
5289
5290        return PackageManager.PERMISSION_DENIED;
5291    }
5292
5293    @Override
5294    public int checkUidPermission(String permName, int uid) {
5295        final int callingUid = Binder.getCallingUid();
5296        final int callingUserId = UserHandle.getUserId(callingUid);
5297        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5298        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5299        final int userId = UserHandle.getUserId(uid);
5300        if (!sUserManager.exists(userId)) {
5301            return PackageManager.PERMISSION_DENIED;
5302        }
5303
5304        synchronized (mPackages) {
5305            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5306            if (obj != null) {
5307                if (obj instanceof SharedUserSetting) {
5308                    if (isCallerInstantApp) {
5309                        return PackageManager.PERMISSION_DENIED;
5310                    }
5311                } else if (obj instanceof PackageSetting) {
5312                    final PackageSetting ps = (PackageSetting) obj;
5313                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5314                        return PackageManager.PERMISSION_DENIED;
5315                    }
5316                }
5317                final SettingBase settingBase = (SettingBase) obj;
5318                final PermissionsState permissionsState = settingBase.getPermissionsState();
5319                if (permissionsState.hasPermission(permName, userId)) {
5320                    if (isUidInstantApp) {
5321                        BasePermission bp = mSettings.mPermissions.get(permName);
5322                        if (bp != null && bp.isInstant()) {
5323                            return PackageManager.PERMISSION_GRANTED;
5324                        }
5325                    } else {
5326                        return PackageManager.PERMISSION_GRANTED;
5327                    }
5328                }
5329                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5330                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5331                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5332                    return PackageManager.PERMISSION_GRANTED;
5333                }
5334            } else {
5335                ArraySet<String> perms = mSystemPermissions.get(uid);
5336                if (perms != null) {
5337                    if (perms.contains(permName)) {
5338                        return PackageManager.PERMISSION_GRANTED;
5339                    }
5340                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5341                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5342                        return PackageManager.PERMISSION_GRANTED;
5343                    }
5344                }
5345            }
5346        }
5347
5348        return PackageManager.PERMISSION_DENIED;
5349    }
5350
5351    @Override
5352    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5353        if (UserHandle.getCallingUserId() != userId) {
5354            mContext.enforceCallingPermission(
5355                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5356                    "isPermissionRevokedByPolicy for user " + userId);
5357        }
5358
5359        if (checkPermission(permission, packageName, userId)
5360                == PackageManager.PERMISSION_GRANTED) {
5361            return false;
5362        }
5363
5364        final int callingUid = Binder.getCallingUid();
5365        if (getInstantAppPackageName(callingUid) != null) {
5366            if (!isCallerSameApp(packageName, callingUid)) {
5367                return false;
5368            }
5369        } else {
5370            if (isInstantApp(packageName, userId)) {
5371                return false;
5372            }
5373        }
5374
5375        final long identity = Binder.clearCallingIdentity();
5376        try {
5377            final int flags = getPermissionFlags(permission, packageName, userId);
5378            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5379        } finally {
5380            Binder.restoreCallingIdentity(identity);
5381        }
5382    }
5383
5384    @Override
5385    public String getPermissionControllerPackageName() {
5386        synchronized (mPackages) {
5387            return mRequiredInstallerPackage;
5388        }
5389    }
5390
5391    /**
5392     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5393     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5394     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5395     * @param message the message to log on security exception
5396     */
5397    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5398            boolean checkShell, String message) {
5399        if (userId < 0) {
5400            throw new IllegalArgumentException("Invalid userId " + userId);
5401        }
5402        if (checkShell) {
5403            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5404        }
5405        if (userId == UserHandle.getUserId(callingUid)) return;
5406        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5407            if (requireFullPermission) {
5408                mContext.enforceCallingOrSelfPermission(
5409                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5410            } else {
5411                try {
5412                    mContext.enforceCallingOrSelfPermission(
5413                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5414                } catch (SecurityException se) {
5415                    mContext.enforceCallingOrSelfPermission(
5416                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5417                }
5418            }
5419        }
5420    }
5421
5422    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5423        if (callingUid == Process.SHELL_UID) {
5424            if (userHandle >= 0
5425                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5426                throw new SecurityException("Shell does not have permission to access user "
5427                        + userHandle);
5428            } else if (userHandle < 0) {
5429                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5430                        + Debug.getCallers(3));
5431            }
5432        }
5433    }
5434
5435    private BasePermission findPermissionTreeLP(String permName) {
5436        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5437            if (permName.startsWith(bp.name) &&
5438                    permName.length() > bp.name.length() &&
5439                    permName.charAt(bp.name.length()) == '.') {
5440                return bp;
5441            }
5442        }
5443        return null;
5444    }
5445
5446    private BasePermission checkPermissionTreeLP(String permName) {
5447        if (permName != null) {
5448            BasePermission bp = findPermissionTreeLP(permName);
5449            if (bp != null) {
5450                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5451                    return bp;
5452                }
5453                throw new SecurityException("Calling uid "
5454                        + Binder.getCallingUid()
5455                        + " is not allowed to add to permission tree "
5456                        + bp.name + " owned by uid " + bp.uid);
5457            }
5458        }
5459        throw new SecurityException("No permission tree found for " + permName);
5460    }
5461
5462    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5463        if (s1 == null) {
5464            return s2 == null;
5465        }
5466        if (s2 == null) {
5467            return false;
5468        }
5469        if (s1.getClass() != s2.getClass()) {
5470            return false;
5471        }
5472        return s1.equals(s2);
5473    }
5474
5475    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5476        if (pi1.icon != pi2.icon) return false;
5477        if (pi1.logo != pi2.logo) return false;
5478        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5479        if (!compareStrings(pi1.name, pi2.name)) return false;
5480        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5481        // We'll take care of setting this one.
5482        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5483        // These are not currently stored in settings.
5484        //if (!compareStrings(pi1.group, pi2.group)) return false;
5485        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5486        //if (pi1.labelRes != pi2.labelRes) return false;
5487        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5488        return true;
5489    }
5490
5491    int permissionInfoFootprint(PermissionInfo info) {
5492        int size = info.name.length();
5493        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5494        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5495        return size;
5496    }
5497
5498    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5499        int size = 0;
5500        for (BasePermission perm : mSettings.mPermissions.values()) {
5501            if (perm.uid == tree.uid) {
5502                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5503            }
5504        }
5505        return size;
5506    }
5507
5508    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5509        // We calculate the max size of permissions defined by this uid and throw
5510        // if that plus the size of 'info' would exceed our stated maximum.
5511        if (tree.uid != Process.SYSTEM_UID) {
5512            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5513            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5514                throw new SecurityException("Permission tree size cap exceeded");
5515            }
5516        }
5517    }
5518
5519    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5520        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5521            throw new SecurityException("Instant apps can't add permissions");
5522        }
5523        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5524            throw new SecurityException("Label must be specified in permission");
5525        }
5526        BasePermission tree = checkPermissionTreeLP(info.name);
5527        BasePermission bp = mSettings.mPermissions.get(info.name);
5528        boolean added = bp == null;
5529        boolean changed = true;
5530        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5531        if (added) {
5532            enforcePermissionCapLocked(info, tree);
5533            bp = new BasePermission(info.name, tree.sourcePackage,
5534                    BasePermission.TYPE_DYNAMIC);
5535        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5536            throw new SecurityException(
5537                    "Not allowed to modify non-dynamic permission "
5538                    + info.name);
5539        } else {
5540            if (bp.protectionLevel == fixedLevel
5541                    && bp.perm.owner.equals(tree.perm.owner)
5542                    && bp.uid == tree.uid
5543                    && comparePermissionInfos(bp.perm.info, info)) {
5544                changed = false;
5545            }
5546        }
5547        bp.protectionLevel = fixedLevel;
5548        info = new PermissionInfo(info);
5549        info.protectionLevel = fixedLevel;
5550        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5551        bp.perm.info.packageName = tree.perm.info.packageName;
5552        bp.uid = tree.uid;
5553        if (added) {
5554            mSettings.mPermissions.put(info.name, bp);
5555        }
5556        if (changed) {
5557            if (!async) {
5558                mSettings.writeLPr();
5559            } else {
5560                scheduleWriteSettingsLocked();
5561            }
5562        }
5563        return added;
5564    }
5565
5566    @Override
5567    public boolean addPermission(PermissionInfo info) {
5568        synchronized (mPackages) {
5569            return addPermissionLocked(info, false);
5570        }
5571    }
5572
5573    @Override
5574    public boolean addPermissionAsync(PermissionInfo info) {
5575        synchronized (mPackages) {
5576            return addPermissionLocked(info, true);
5577        }
5578    }
5579
5580    @Override
5581    public void removePermission(String name) {
5582        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5583            throw new SecurityException("Instant applications don't have access to this method");
5584        }
5585        synchronized (mPackages) {
5586            checkPermissionTreeLP(name);
5587            BasePermission bp = mSettings.mPermissions.get(name);
5588            if (bp != null) {
5589                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5590                    throw new SecurityException(
5591                            "Not allowed to modify non-dynamic permission "
5592                            + name);
5593                }
5594                mSettings.mPermissions.remove(name);
5595                mSettings.writeLPr();
5596            }
5597        }
5598    }
5599
5600    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5601            PackageParser.Package pkg, BasePermission bp) {
5602        int index = pkg.requestedPermissions.indexOf(bp.name);
5603        if (index == -1) {
5604            throw new SecurityException("Package " + pkg.packageName
5605                    + " has not requested permission " + bp.name);
5606        }
5607        if (!bp.isRuntime() && !bp.isDevelopment()) {
5608            throw new SecurityException("Permission " + bp.name
5609                    + " is not a changeable permission type");
5610        }
5611    }
5612
5613    @Override
5614    public void grantRuntimePermission(String packageName, String name, final int userId) {
5615        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5616    }
5617
5618    private void grantRuntimePermission(String packageName, String name, final int userId,
5619            boolean overridePolicy) {
5620        if (!sUserManager.exists(userId)) {
5621            Log.e(TAG, "No such user:" + userId);
5622            return;
5623        }
5624        final int callingUid = Binder.getCallingUid();
5625
5626        mContext.enforceCallingOrSelfPermission(
5627                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5628                "grantRuntimePermission");
5629
5630        enforceCrossUserPermission(callingUid, userId,
5631                true /* requireFullPermission */, true /* checkShell */,
5632                "grantRuntimePermission");
5633
5634        final int uid;
5635        final PackageSetting ps;
5636
5637        synchronized (mPackages) {
5638            final PackageParser.Package pkg = mPackages.get(packageName);
5639            if (pkg == null) {
5640                throw new IllegalArgumentException("Unknown package: " + packageName);
5641            }
5642            final BasePermission bp = mSettings.mPermissions.get(name);
5643            if (bp == null) {
5644                throw new IllegalArgumentException("Unknown permission: " + name);
5645            }
5646            ps = (PackageSetting) pkg.mExtras;
5647            if (ps == null
5648                    || filterAppAccessLPr(ps, callingUid, userId)) {
5649                throw new IllegalArgumentException("Unknown package: " + packageName);
5650            }
5651
5652            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5653
5654            // If a permission review is required for legacy apps we represent
5655            // their permissions as always granted runtime ones since we need
5656            // to keep the review required permission flag per user while an
5657            // install permission's state is shared across all users.
5658            if (mPermissionReviewRequired
5659                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5660                    && bp.isRuntime()) {
5661                return;
5662            }
5663
5664            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5665
5666            final PermissionsState permissionsState = ps.getPermissionsState();
5667
5668            final int flags = permissionsState.getPermissionFlags(name, userId);
5669            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5670                throw new SecurityException("Cannot grant system fixed permission "
5671                        + name + " for package " + packageName);
5672            }
5673            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5674                throw new SecurityException("Cannot grant policy fixed permission "
5675                        + name + " for package " + packageName);
5676            }
5677
5678            if (bp.isDevelopment()) {
5679                // Development permissions must be handled specially, since they are not
5680                // normal runtime permissions.  For now they apply to all users.
5681                if (permissionsState.grantInstallPermission(bp) !=
5682                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5683                    scheduleWriteSettingsLocked();
5684                }
5685                return;
5686            }
5687
5688            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5689                throw new SecurityException("Cannot grant non-ephemeral permission"
5690                        + name + " for package " + packageName);
5691            }
5692
5693            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5694                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5695                return;
5696            }
5697
5698            final int result = permissionsState.grantRuntimePermission(bp, userId);
5699            switch (result) {
5700                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5701                    return;
5702                }
5703
5704                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5705                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5706                    mHandler.post(new Runnable() {
5707                        @Override
5708                        public void run() {
5709                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5710                        }
5711                    });
5712                }
5713                break;
5714            }
5715
5716            if (bp.isRuntime()) {
5717                logPermissionGranted(mContext, name, packageName);
5718            }
5719
5720            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5721
5722            // Not critical if that is lost - app has to request again.
5723            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5724        }
5725
5726        // Only need to do this if user is initialized. Otherwise it's a new user
5727        // and there are no processes running as the user yet and there's no need
5728        // to make an expensive call to remount processes for the changed permissions.
5729        if (READ_EXTERNAL_STORAGE.equals(name)
5730                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5731            final long token = Binder.clearCallingIdentity();
5732            try {
5733                if (sUserManager.isInitialized(userId)) {
5734                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5735                            StorageManagerInternal.class);
5736                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5737                }
5738            } finally {
5739                Binder.restoreCallingIdentity(token);
5740            }
5741        }
5742    }
5743
5744    @Override
5745    public void revokeRuntimePermission(String packageName, String name, int userId) {
5746        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5747    }
5748
5749    private void revokeRuntimePermission(String packageName, String name, int userId,
5750            boolean overridePolicy) {
5751        if (!sUserManager.exists(userId)) {
5752            Log.e(TAG, "No such user:" + userId);
5753            return;
5754        }
5755
5756        mContext.enforceCallingOrSelfPermission(
5757                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5758                "revokeRuntimePermission");
5759
5760        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5761                true /* requireFullPermission */, true /* checkShell */,
5762                "revokeRuntimePermission");
5763
5764        final int appId;
5765
5766        synchronized (mPackages) {
5767            final PackageParser.Package pkg = mPackages.get(packageName);
5768            if (pkg == null) {
5769                throw new IllegalArgumentException("Unknown package: " + packageName);
5770            }
5771            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5772            if (ps == null
5773                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5774                throw new IllegalArgumentException("Unknown package: " + packageName);
5775            }
5776            final BasePermission bp = mSettings.mPermissions.get(name);
5777            if (bp == null) {
5778                throw new IllegalArgumentException("Unknown permission: " + name);
5779            }
5780
5781            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5782
5783            // If a permission review is required for legacy apps we represent
5784            // their permissions as always granted runtime ones since we need
5785            // to keep the review required permission flag per user while an
5786            // install permission's state is shared across all users.
5787            if (mPermissionReviewRequired
5788                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5789                    && bp.isRuntime()) {
5790                return;
5791            }
5792
5793            final PermissionsState permissionsState = ps.getPermissionsState();
5794
5795            final int flags = permissionsState.getPermissionFlags(name, userId);
5796            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5797                throw new SecurityException("Cannot revoke system fixed permission "
5798                        + name + " for package " + packageName);
5799            }
5800            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5801                throw new SecurityException("Cannot revoke policy fixed permission "
5802                        + name + " for package " + packageName);
5803            }
5804
5805            if (bp.isDevelopment()) {
5806                // Development permissions must be handled specially, since they are not
5807                // normal runtime permissions.  For now they apply to all users.
5808                if (permissionsState.revokeInstallPermission(bp) !=
5809                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5810                    scheduleWriteSettingsLocked();
5811                }
5812                return;
5813            }
5814
5815            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5816                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5817                return;
5818            }
5819
5820            if (bp.isRuntime()) {
5821                logPermissionRevoked(mContext, name, packageName);
5822            }
5823
5824            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5825
5826            // Critical, after this call app should never have the permission.
5827            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5828
5829            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5830        }
5831
5832        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5833    }
5834
5835    /**
5836     * Get the first event id for the permission.
5837     *
5838     * <p>There are four events for each permission: <ul>
5839     *     <li>Request permission: first id + 0</li>
5840     *     <li>Grant permission: first id + 1</li>
5841     *     <li>Request for permission denied: first id + 2</li>
5842     *     <li>Revoke permission: first id + 3</li>
5843     * </ul></p>
5844     *
5845     * @param name name of the permission
5846     *
5847     * @return The first event id for the permission
5848     */
5849    private static int getBaseEventId(@NonNull String name) {
5850        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5851
5852        if (eventIdIndex == -1) {
5853            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5854                    || Build.IS_USER) {
5855                Log.i(TAG, "Unknown permission " + name);
5856
5857                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5858            } else {
5859                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5860                //
5861                // Also update
5862                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5863                // - metrics_constants.proto
5864                throw new IllegalStateException("Unknown permission " + name);
5865            }
5866        }
5867
5868        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5869    }
5870
5871    /**
5872     * Log that a permission was revoked.
5873     *
5874     * @param context Context of the caller
5875     * @param name name of the permission
5876     * @param packageName package permission if for
5877     */
5878    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5879            @NonNull String packageName) {
5880        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5881    }
5882
5883    /**
5884     * Log that a permission request was granted.
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 logPermissionGranted(@NonNull Context context, @NonNull String name,
5891            @NonNull String packageName) {
5892        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5893    }
5894
5895    @Override
5896    public void resetRuntimePermissions() {
5897        mContext.enforceCallingOrSelfPermission(
5898                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5899                "revokeRuntimePermission");
5900
5901        int callingUid = Binder.getCallingUid();
5902        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5903            mContext.enforceCallingOrSelfPermission(
5904                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5905                    "resetRuntimePermissions");
5906        }
5907
5908        synchronized (mPackages) {
5909            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5910            for (int userId : UserManagerService.getInstance().getUserIds()) {
5911                final int packageCount = mPackages.size();
5912                for (int i = 0; i < packageCount; i++) {
5913                    PackageParser.Package pkg = mPackages.valueAt(i);
5914                    if (!(pkg.mExtras instanceof PackageSetting)) {
5915                        continue;
5916                    }
5917                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5918                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5919                }
5920            }
5921        }
5922    }
5923
5924    @Override
5925    public int getPermissionFlags(String name, String packageName, int userId) {
5926        if (!sUserManager.exists(userId)) {
5927            return 0;
5928        }
5929
5930        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5931
5932        final int callingUid = Binder.getCallingUid();
5933        enforceCrossUserPermission(callingUid, userId,
5934                true /* requireFullPermission */, false /* checkShell */,
5935                "getPermissionFlags");
5936
5937        synchronized (mPackages) {
5938            final PackageParser.Package pkg = mPackages.get(packageName);
5939            if (pkg == null) {
5940                return 0;
5941            }
5942            final BasePermission bp = mSettings.mPermissions.get(name);
5943            if (bp == null) {
5944                return 0;
5945            }
5946            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5947            if (ps == null
5948                    || filterAppAccessLPr(ps, callingUid, userId)) {
5949                return 0;
5950            }
5951            PermissionsState permissionsState = ps.getPermissionsState();
5952            return permissionsState.getPermissionFlags(name, userId);
5953        }
5954    }
5955
5956    @Override
5957    public void updatePermissionFlags(String name, String packageName, int flagMask,
5958            int flagValues, int userId) {
5959        if (!sUserManager.exists(userId)) {
5960            return;
5961        }
5962
5963        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5964
5965        final int callingUid = Binder.getCallingUid();
5966        enforceCrossUserPermission(callingUid, userId,
5967                true /* requireFullPermission */, true /* checkShell */,
5968                "updatePermissionFlags");
5969
5970        // Only the system can change these flags and nothing else.
5971        if (getCallingUid() != Process.SYSTEM_UID) {
5972            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5973            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5974            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5975            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5976            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5977        }
5978
5979        synchronized (mPackages) {
5980            final PackageParser.Package pkg = mPackages.get(packageName);
5981            if (pkg == null) {
5982                throw new IllegalArgumentException("Unknown package: " + packageName);
5983            }
5984            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5985            if (ps == null
5986                    || filterAppAccessLPr(ps, callingUid, userId)) {
5987                throw new IllegalArgumentException("Unknown package: " + packageName);
5988            }
5989
5990            final BasePermission bp = mSettings.mPermissions.get(name);
5991            if (bp == null) {
5992                throw new IllegalArgumentException("Unknown permission: " + name);
5993            }
5994
5995            PermissionsState permissionsState = ps.getPermissionsState();
5996
5997            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5998
5999            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6000                // Install and runtime permissions are stored in different places,
6001                // so figure out what permission changed and persist the change.
6002                if (permissionsState.getInstallPermissionState(name) != null) {
6003                    scheduleWriteSettingsLocked();
6004                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6005                        || hadState) {
6006                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6007                }
6008            }
6009        }
6010    }
6011
6012    /**
6013     * Update the permission flags for all packages and runtime permissions of a user in order
6014     * to allow device or profile owner to remove POLICY_FIXED.
6015     */
6016    @Override
6017    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6018        if (!sUserManager.exists(userId)) {
6019            return;
6020        }
6021
6022        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6023
6024        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6025                true /* requireFullPermission */, true /* checkShell */,
6026                "updatePermissionFlagsForAllApps");
6027
6028        // Only the system can change system fixed flags.
6029        if (getCallingUid() != Process.SYSTEM_UID) {
6030            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6031            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6032        }
6033
6034        synchronized (mPackages) {
6035            boolean changed = false;
6036            final int packageCount = mPackages.size();
6037            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6038                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6039                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6040                if (ps == null) {
6041                    continue;
6042                }
6043                PermissionsState permissionsState = ps.getPermissionsState();
6044                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6045                        userId, flagMask, flagValues);
6046            }
6047            if (changed) {
6048                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6049            }
6050        }
6051    }
6052
6053    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6054        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6055                != PackageManager.PERMISSION_GRANTED
6056            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6057                != PackageManager.PERMISSION_GRANTED) {
6058            throw new SecurityException(message + " requires "
6059                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6060                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6061        }
6062    }
6063
6064    @Override
6065    public boolean shouldShowRequestPermissionRationale(String permissionName,
6066            String packageName, int userId) {
6067        if (UserHandle.getCallingUserId() != userId) {
6068            mContext.enforceCallingPermission(
6069                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6070                    "canShowRequestPermissionRationale for user " + userId);
6071        }
6072
6073        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6074        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6075            return false;
6076        }
6077
6078        if (checkPermission(permissionName, packageName, userId)
6079                == PackageManager.PERMISSION_GRANTED) {
6080            return false;
6081        }
6082
6083        final int flags;
6084
6085        final long identity = Binder.clearCallingIdentity();
6086        try {
6087            flags = getPermissionFlags(permissionName,
6088                    packageName, userId);
6089        } finally {
6090            Binder.restoreCallingIdentity(identity);
6091        }
6092
6093        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6094                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6095                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6096
6097        if ((flags & fixedFlags) != 0) {
6098            return false;
6099        }
6100
6101        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6102    }
6103
6104    @Override
6105    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6106        mContext.enforceCallingOrSelfPermission(
6107                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6108                "addOnPermissionsChangeListener");
6109
6110        synchronized (mPackages) {
6111            mOnPermissionChangeListeners.addListenerLocked(listener);
6112        }
6113    }
6114
6115    @Override
6116    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6117        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6118            throw new SecurityException("Instant applications don't have access to this method");
6119        }
6120        synchronized (mPackages) {
6121            mOnPermissionChangeListeners.removeListenerLocked(listener);
6122        }
6123    }
6124
6125    @Override
6126    public boolean isProtectedBroadcast(String actionName) {
6127        // allow instant applications
6128        synchronized (mProtectedBroadcasts) {
6129            if (mProtectedBroadcasts.contains(actionName)) {
6130                return true;
6131            } else if (actionName != null) {
6132                // TODO: remove these terrible hacks
6133                if (actionName.startsWith("android.net.netmon.lingerExpired")
6134                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6135                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6136                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6137                    return true;
6138                }
6139            }
6140        }
6141        return false;
6142    }
6143
6144    @Override
6145    public int checkSignatures(String pkg1, String pkg2) {
6146        synchronized (mPackages) {
6147            final PackageParser.Package p1 = mPackages.get(pkg1);
6148            final PackageParser.Package p2 = mPackages.get(pkg2);
6149            if (p1 == null || p1.mExtras == null
6150                    || p2 == null || p2.mExtras == null) {
6151                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6152            }
6153            final int callingUid = Binder.getCallingUid();
6154            final int callingUserId = UserHandle.getUserId(callingUid);
6155            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6156            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6157            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6158                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6159                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6160            }
6161            return compareSignatures(p1.mSignatures, p2.mSignatures);
6162        }
6163    }
6164
6165    @Override
6166    public int checkUidSignatures(int uid1, int uid2) {
6167        final int callingUid = Binder.getCallingUid();
6168        final int callingUserId = UserHandle.getUserId(callingUid);
6169        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6170        // Map to base uids.
6171        uid1 = UserHandle.getAppId(uid1);
6172        uid2 = UserHandle.getAppId(uid2);
6173        // reader
6174        synchronized (mPackages) {
6175            Signature[] s1;
6176            Signature[] s2;
6177            Object obj = mSettings.getUserIdLPr(uid1);
6178            if (obj != null) {
6179                if (obj instanceof SharedUserSetting) {
6180                    if (isCallerInstantApp) {
6181                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6182                    }
6183                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6184                } else if (obj instanceof PackageSetting) {
6185                    final PackageSetting ps = (PackageSetting) obj;
6186                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6187                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6188                    }
6189                    s1 = ps.signatures.mSignatures;
6190                } else {
6191                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6192                }
6193            } else {
6194                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6195            }
6196            obj = mSettings.getUserIdLPr(uid2);
6197            if (obj != null) {
6198                if (obj instanceof SharedUserSetting) {
6199                    if (isCallerInstantApp) {
6200                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6201                    }
6202                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6203                } else if (obj instanceof PackageSetting) {
6204                    final PackageSetting ps = (PackageSetting) obj;
6205                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6206                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6207                    }
6208                    s2 = ps.signatures.mSignatures;
6209                } else {
6210                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6211                }
6212            } else {
6213                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6214            }
6215            return compareSignatures(s1, s2);
6216        }
6217    }
6218
6219    /**
6220     * This method should typically only be used when granting or revoking
6221     * permissions, since the app may immediately restart after this call.
6222     * <p>
6223     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6224     * guard your work against the app being relaunched.
6225     */
6226    private void killUid(int appId, int userId, String reason) {
6227        final long identity = Binder.clearCallingIdentity();
6228        try {
6229            IActivityManager am = ActivityManager.getService();
6230            if (am != null) {
6231                try {
6232                    am.killUid(appId, userId, reason);
6233                } catch (RemoteException e) {
6234                    /* ignore - same process */
6235                }
6236            }
6237        } finally {
6238            Binder.restoreCallingIdentity(identity);
6239        }
6240    }
6241
6242    /**
6243     * Compares two sets of signatures. Returns:
6244     * <br />
6245     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6246     * <br />
6247     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6248     * <br />
6249     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6250     * <br />
6251     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6252     * <br />
6253     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6254     */
6255    static int compareSignatures(Signature[] s1, Signature[] s2) {
6256        if (s1 == null) {
6257            return s2 == null
6258                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6259                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6260        }
6261
6262        if (s2 == null) {
6263            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6264        }
6265
6266        if (s1.length != s2.length) {
6267            return PackageManager.SIGNATURE_NO_MATCH;
6268        }
6269
6270        // Since both signature sets are of size 1, we can compare without HashSets.
6271        if (s1.length == 1) {
6272            return s1[0].equals(s2[0]) ?
6273                    PackageManager.SIGNATURE_MATCH :
6274                    PackageManager.SIGNATURE_NO_MATCH;
6275        }
6276
6277        ArraySet<Signature> set1 = new ArraySet<Signature>();
6278        for (Signature sig : s1) {
6279            set1.add(sig);
6280        }
6281        ArraySet<Signature> set2 = new ArraySet<Signature>();
6282        for (Signature sig : s2) {
6283            set2.add(sig);
6284        }
6285        // Make sure s2 contains all signatures in s1.
6286        if (set1.equals(set2)) {
6287            return PackageManager.SIGNATURE_MATCH;
6288        }
6289        return PackageManager.SIGNATURE_NO_MATCH;
6290    }
6291
6292    /**
6293     * If the database version for this type of package (internal storage or
6294     * external storage) is less than the version where package signatures
6295     * were updated, return true.
6296     */
6297    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6298        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6299        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6300    }
6301
6302    /**
6303     * Used for backward compatibility to make sure any packages with
6304     * certificate chains get upgraded to the new style. {@code existingSigs}
6305     * will be in the old format (since they were stored on disk from before the
6306     * system upgrade) and {@code scannedSigs} will be in the newer format.
6307     */
6308    private int compareSignaturesCompat(PackageSignatures existingSigs,
6309            PackageParser.Package scannedPkg) {
6310        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6311            return PackageManager.SIGNATURE_NO_MATCH;
6312        }
6313
6314        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6315        for (Signature sig : existingSigs.mSignatures) {
6316            existingSet.add(sig);
6317        }
6318        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6319        for (Signature sig : scannedPkg.mSignatures) {
6320            try {
6321                Signature[] chainSignatures = sig.getChainSignatures();
6322                for (Signature chainSig : chainSignatures) {
6323                    scannedCompatSet.add(chainSig);
6324                }
6325            } catch (CertificateEncodingException e) {
6326                scannedCompatSet.add(sig);
6327            }
6328        }
6329        /*
6330         * Make sure the expanded scanned set contains all signatures in the
6331         * existing one.
6332         */
6333        if (scannedCompatSet.equals(existingSet)) {
6334            // Migrate the old signatures to the new scheme.
6335            existingSigs.assignSignatures(scannedPkg.mSignatures);
6336            // The new KeySets will be re-added later in the scanning process.
6337            synchronized (mPackages) {
6338                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6339            }
6340            return PackageManager.SIGNATURE_MATCH;
6341        }
6342        return PackageManager.SIGNATURE_NO_MATCH;
6343    }
6344
6345    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6346        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6347        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6348    }
6349
6350    private int compareSignaturesRecover(PackageSignatures existingSigs,
6351            PackageParser.Package scannedPkg) {
6352        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6353            return PackageManager.SIGNATURE_NO_MATCH;
6354        }
6355
6356        String msg = null;
6357        try {
6358            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6359                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6360                        + scannedPkg.packageName);
6361                return PackageManager.SIGNATURE_MATCH;
6362            }
6363        } catch (CertificateException e) {
6364            msg = e.getMessage();
6365        }
6366
6367        logCriticalInfo(Log.INFO,
6368                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6369        return PackageManager.SIGNATURE_NO_MATCH;
6370    }
6371
6372    @Override
6373    public List<String> getAllPackages() {
6374        final int callingUid = Binder.getCallingUid();
6375        final int callingUserId = UserHandle.getUserId(callingUid);
6376        synchronized (mPackages) {
6377            if (canViewInstantApps(callingUid, callingUserId)) {
6378                return new ArrayList<String>(mPackages.keySet());
6379            }
6380            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6381            final List<String> result = new ArrayList<>();
6382            if (instantAppPkgName != null) {
6383                // caller is an instant application; filter unexposed applications
6384                for (PackageParser.Package pkg : mPackages.values()) {
6385                    if (!pkg.visibleToInstantApps) {
6386                        continue;
6387                    }
6388                    result.add(pkg.packageName);
6389                }
6390            } else {
6391                // caller is a normal application; filter instant applications
6392                for (PackageParser.Package pkg : mPackages.values()) {
6393                    final PackageSetting ps =
6394                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6395                    if (ps != null
6396                            && ps.getInstantApp(callingUserId)
6397                            && !mInstantAppRegistry.isInstantAccessGranted(
6398                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6399                        continue;
6400                    }
6401                    result.add(pkg.packageName);
6402                }
6403            }
6404            return result;
6405        }
6406    }
6407
6408    @Override
6409    public String[] getPackagesForUid(int uid) {
6410        final int callingUid = Binder.getCallingUid();
6411        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6412        final int userId = UserHandle.getUserId(uid);
6413        uid = UserHandle.getAppId(uid);
6414        // reader
6415        synchronized (mPackages) {
6416            Object obj = mSettings.getUserIdLPr(uid);
6417            if (obj instanceof SharedUserSetting) {
6418                if (isCallerInstantApp) {
6419                    return null;
6420                }
6421                final SharedUserSetting sus = (SharedUserSetting) obj;
6422                final int N = sus.packages.size();
6423                String[] res = new String[N];
6424                final Iterator<PackageSetting> it = sus.packages.iterator();
6425                int i = 0;
6426                while (it.hasNext()) {
6427                    PackageSetting ps = it.next();
6428                    if (ps.getInstalled(userId)) {
6429                        res[i++] = ps.name;
6430                    } else {
6431                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6432                    }
6433                }
6434                return res;
6435            } else if (obj instanceof PackageSetting) {
6436                final PackageSetting ps = (PackageSetting) obj;
6437                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6438                    return new String[]{ps.name};
6439                }
6440            }
6441        }
6442        return null;
6443    }
6444
6445    @Override
6446    public String getNameForUid(int uid) {
6447        final int callingUid = Binder.getCallingUid();
6448        if (getInstantAppPackageName(callingUid) != null) {
6449            return null;
6450        }
6451        synchronized (mPackages) {
6452            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6453            if (obj instanceof SharedUserSetting) {
6454                final SharedUserSetting sus = (SharedUserSetting) obj;
6455                return sus.name + ":" + sus.userId;
6456            } else if (obj instanceof PackageSetting) {
6457                final PackageSetting ps = (PackageSetting) obj;
6458                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6459                    return null;
6460                }
6461                return ps.name;
6462            }
6463            return null;
6464        }
6465    }
6466
6467    @Override
6468    public String[] getNamesForUids(int[] uids) {
6469        if (uids == null || uids.length == 0) {
6470            return null;
6471        }
6472        final int callingUid = Binder.getCallingUid();
6473        if (getInstantAppPackageName(callingUid) != null) {
6474            return null;
6475        }
6476        final String[] names = new String[uids.length];
6477        synchronized (mPackages) {
6478            for (int i = uids.length - 1; i >= 0; i--) {
6479                final int uid = uids[i];
6480                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6481                if (obj instanceof SharedUserSetting) {
6482                    final SharedUserSetting sus = (SharedUserSetting) obj;
6483                    names[i] = "shared:" + sus.name;
6484                } else if (obj instanceof PackageSetting) {
6485                    final PackageSetting ps = (PackageSetting) obj;
6486                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6487                        names[i] = null;
6488                    } else {
6489                        names[i] = ps.name;
6490                    }
6491                } else {
6492                    names[i] = null;
6493                }
6494            }
6495        }
6496        return names;
6497    }
6498
6499    @Override
6500    public int getUidForSharedUser(String sharedUserName) {
6501        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6502            return -1;
6503        }
6504        if (sharedUserName == null) {
6505            return -1;
6506        }
6507        // reader
6508        synchronized (mPackages) {
6509            SharedUserSetting suid;
6510            try {
6511                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6512                if (suid != null) {
6513                    return suid.userId;
6514                }
6515            } catch (PackageManagerException ignore) {
6516                // can't happen, but, still need to catch it
6517            }
6518            return -1;
6519        }
6520    }
6521
6522    @Override
6523    public int getFlagsForUid(int uid) {
6524        final int callingUid = Binder.getCallingUid();
6525        if (getInstantAppPackageName(callingUid) != null) {
6526            return 0;
6527        }
6528        synchronized (mPackages) {
6529            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6530            if (obj instanceof SharedUserSetting) {
6531                final SharedUserSetting sus = (SharedUserSetting) obj;
6532                return sus.pkgFlags;
6533            } else if (obj instanceof PackageSetting) {
6534                final PackageSetting ps = (PackageSetting) obj;
6535                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6536                    return 0;
6537                }
6538                return ps.pkgFlags;
6539            }
6540        }
6541        return 0;
6542    }
6543
6544    @Override
6545    public int getPrivateFlagsForUid(int uid) {
6546        final int callingUid = Binder.getCallingUid();
6547        if (getInstantAppPackageName(callingUid) != null) {
6548            return 0;
6549        }
6550        synchronized (mPackages) {
6551            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6552            if (obj instanceof SharedUserSetting) {
6553                final SharedUserSetting sus = (SharedUserSetting) obj;
6554                return sus.pkgPrivateFlags;
6555            } else if (obj instanceof PackageSetting) {
6556                final PackageSetting ps = (PackageSetting) obj;
6557                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6558                    return 0;
6559                }
6560                return ps.pkgPrivateFlags;
6561            }
6562        }
6563        return 0;
6564    }
6565
6566    @Override
6567    public boolean isUidPrivileged(int uid) {
6568        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6569            return false;
6570        }
6571        uid = UserHandle.getAppId(uid);
6572        // reader
6573        synchronized (mPackages) {
6574            Object obj = mSettings.getUserIdLPr(uid);
6575            if (obj instanceof SharedUserSetting) {
6576                final SharedUserSetting sus = (SharedUserSetting) obj;
6577                final Iterator<PackageSetting> it = sus.packages.iterator();
6578                while (it.hasNext()) {
6579                    if (it.next().isPrivileged()) {
6580                        return true;
6581                    }
6582                }
6583            } else if (obj instanceof PackageSetting) {
6584                final PackageSetting ps = (PackageSetting) obj;
6585                return ps.isPrivileged();
6586            }
6587        }
6588        return false;
6589    }
6590
6591    @Override
6592    public String[] getAppOpPermissionPackages(String permissionName) {
6593        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6594            return null;
6595        }
6596        synchronized (mPackages) {
6597            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6598            if (pkgs == null) {
6599                return null;
6600            }
6601            return pkgs.toArray(new String[pkgs.size()]);
6602        }
6603    }
6604
6605    @Override
6606    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6607            int flags, int userId) {
6608        return resolveIntentInternal(
6609                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6610    }
6611
6612    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6613            int flags, int userId, boolean resolveForStart) {
6614        try {
6615            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6616
6617            if (!sUserManager.exists(userId)) return null;
6618            final int callingUid = Binder.getCallingUid();
6619            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6620            enforceCrossUserPermission(callingUid, userId,
6621                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6622
6623            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6624            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6625                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6626            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6627
6628            final ResolveInfo bestChoice =
6629                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6630            return bestChoice;
6631        } finally {
6632            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6633        }
6634    }
6635
6636    @Override
6637    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6638        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6639            throw new SecurityException(
6640                    "findPersistentPreferredActivity can only be run by the system");
6641        }
6642        if (!sUserManager.exists(userId)) {
6643            return null;
6644        }
6645        final int callingUid = Binder.getCallingUid();
6646        intent = updateIntentForResolve(intent);
6647        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6648        final int flags = updateFlagsForResolve(
6649                0, userId, intent, callingUid, false /*includeInstantApps*/);
6650        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6651                userId);
6652        synchronized (mPackages) {
6653            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6654                    userId);
6655        }
6656    }
6657
6658    @Override
6659    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6660            IntentFilter filter, int match, ComponentName activity) {
6661        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6662            return;
6663        }
6664        final int userId = UserHandle.getCallingUserId();
6665        if (DEBUG_PREFERRED) {
6666            Log.v(TAG, "setLastChosenActivity intent=" + intent
6667                + " resolvedType=" + resolvedType
6668                + " flags=" + flags
6669                + " filter=" + filter
6670                + " match=" + match
6671                + " activity=" + activity);
6672            filter.dump(new PrintStreamPrinter(System.out), "    ");
6673        }
6674        intent.setComponent(null);
6675        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6676                userId);
6677        // Find any earlier preferred or last chosen entries and nuke them
6678        findPreferredActivity(intent, resolvedType,
6679                flags, query, 0, false, true, false, userId);
6680        // Add the new activity as the last chosen for this filter
6681        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6682                "Setting last chosen");
6683    }
6684
6685    @Override
6686    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6687        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6688            return null;
6689        }
6690        final int userId = UserHandle.getCallingUserId();
6691        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6692        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6693                userId);
6694        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6695                false, false, false, userId);
6696    }
6697
6698    /**
6699     * Returns whether or not instant apps have been disabled remotely.
6700     */
6701    private boolean isEphemeralDisabled() {
6702        return mEphemeralAppsDisabled;
6703    }
6704
6705    private boolean isInstantAppAllowed(
6706            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6707            boolean skipPackageCheck) {
6708        if (mInstantAppResolverConnection == null) {
6709            return false;
6710        }
6711        if (mInstantAppInstallerActivity == null) {
6712            return false;
6713        }
6714        if (intent.getComponent() != null) {
6715            return false;
6716        }
6717        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6718            return false;
6719        }
6720        if (!skipPackageCheck && intent.getPackage() != null) {
6721            return false;
6722        }
6723        final boolean isWebUri = hasWebURI(intent);
6724        if (!isWebUri || intent.getData().getHost() == null) {
6725            return false;
6726        }
6727        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6728        // Or if there's already an ephemeral app installed that handles the action
6729        synchronized (mPackages) {
6730            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6731            for (int n = 0; n < count; n++) {
6732                final ResolveInfo info = resolvedActivities.get(n);
6733                final String packageName = info.activityInfo.packageName;
6734                final PackageSetting ps = mSettings.mPackages.get(packageName);
6735                if (ps != null) {
6736                    // only check domain verification status if the app is not a browser
6737                    if (!info.handleAllWebDataURI) {
6738                        // Try to get the status from User settings first
6739                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6740                        final int status = (int) (packedStatus >> 32);
6741                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6742                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6743                            if (DEBUG_EPHEMERAL) {
6744                                Slog.v(TAG, "DENY instant app;"
6745                                    + " pkg: " + packageName + ", status: " + status);
6746                            }
6747                            return false;
6748                        }
6749                    }
6750                    if (ps.getInstantApp(userId)) {
6751                        if (DEBUG_EPHEMERAL) {
6752                            Slog.v(TAG, "DENY instant app installed;"
6753                                    + " pkg: " + packageName);
6754                        }
6755                        return false;
6756                    }
6757                }
6758            }
6759        }
6760        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6761        return true;
6762    }
6763
6764    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6765            Intent origIntent, String resolvedType, String callingPackage,
6766            Bundle verificationBundle, int userId) {
6767        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6768                new InstantAppRequest(responseObj, origIntent, resolvedType,
6769                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6770        mHandler.sendMessage(msg);
6771    }
6772
6773    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6774            int flags, List<ResolveInfo> query, int userId) {
6775        if (query != null) {
6776            final int N = query.size();
6777            if (N == 1) {
6778                return query.get(0);
6779            } else if (N > 1) {
6780                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6781                // If there is more than one activity with the same priority,
6782                // then let the user decide between them.
6783                ResolveInfo r0 = query.get(0);
6784                ResolveInfo r1 = query.get(1);
6785                if (DEBUG_INTENT_MATCHING || debug) {
6786                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6787                            + r1.activityInfo.name + "=" + r1.priority);
6788                }
6789                // If the first activity has a higher priority, or a different
6790                // default, then it is always desirable to pick it.
6791                if (r0.priority != r1.priority
6792                        || r0.preferredOrder != r1.preferredOrder
6793                        || r0.isDefault != r1.isDefault) {
6794                    return query.get(0);
6795                }
6796                // If we have saved a preference for a preferred activity for
6797                // this Intent, use that.
6798                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6799                        flags, query, r0.priority, true, false, debug, userId);
6800                if (ri != null) {
6801                    return ri;
6802                }
6803                // If we have an ephemeral app, use it
6804                for (int i = 0; i < N; i++) {
6805                    ri = query.get(i);
6806                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6807                        final String packageName = ri.activityInfo.packageName;
6808                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6809                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6810                        final int status = (int)(packedStatus >> 32);
6811                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6812                            return ri;
6813                        }
6814                    }
6815                }
6816                ri = new ResolveInfo(mResolveInfo);
6817                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6818                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6819                // If all of the options come from the same package, show the application's
6820                // label and icon instead of the generic resolver's.
6821                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6822                // and then throw away the ResolveInfo itself, meaning that the caller loses
6823                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6824                // a fallback for this case; we only set the target package's resources on
6825                // the ResolveInfo, not the ActivityInfo.
6826                final String intentPackage = intent.getPackage();
6827                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6828                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6829                    ri.resolvePackageName = intentPackage;
6830                    if (userNeedsBadging(userId)) {
6831                        ri.noResourceId = true;
6832                    } else {
6833                        ri.icon = appi.icon;
6834                    }
6835                    ri.iconResourceId = appi.icon;
6836                    ri.labelRes = appi.labelRes;
6837                }
6838                ri.activityInfo.applicationInfo = new ApplicationInfo(
6839                        ri.activityInfo.applicationInfo);
6840                if (userId != 0) {
6841                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6842                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6843                }
6844                // Make sure that the resolver is displayable in car mode
6845                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6846                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6847                return ri;
6848            }
6849        }
6850        return null;
6851    }
6852
6853    /**
6854     * Return true if the given list is not empty and all of its contents have
6855     * an activityInfo with the given package name.
6856     */
6857    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6858        if (ArrayUtils.isEmpty(list)) {
6859            return false;
6860        }
6861        for (int i = 0, N = list.size(); i < N; i++) {
6862            final ResolveInfo ri = list.get(i);
6863            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6864            if (ai == null || !packageName.equals(ai.packageName)) {
6865                return false;
6866            }
6867        }
6868        return true;
6869    }
6870
6871    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6872            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6873        final int N = query.size();
6874        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6875                .get(userId);
6876        // Get the list of persistent preferred activities that handle the intent
6877        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6878        List<PersistentPreferredActivity> pprefs = ppir != null
6879                ? ppir.queryIntent(intent, resolvedType,
6880                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6881                        userId)
6882                : null;
6883        if (pprefs != null && pprefs.size() > 0) {
6884            final int M = pprefs.size();
6885            for (int i=0; i<M; i++) {
6886                final PersistentPreferredActivity ppa = pprefs.get(i);
6887                if (DEBUG_PREFERRED || debug) {
6888                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6889                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6890                            + "\n  component=" + ppa.mComponent);
6891                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6892                }
6893                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6894                        flags | MATCH_DISABLED_COMPONENTS, userId);
6895                if (DEBUG_PREFERRED || debug) {
6896                    Slog.v(TAG, "Found persistent preferred activity:");
6897                    if (ai != null) {
6898                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6899                    } else {
6900                        Slog.v(TAG, "  null");
6901                    }
6902                }
6903                if (ai == null) {
6904                    // This previously registered persistent preferred activity
6905                    // component is no longer known. Ignore it and do NOT remove it.
6906                    continue;
6907                }
6908                for (int j=0; j<N; j++) {
6909                    final ResolveInfo ri = query.get(j);
6910                    if (!ri.activityInfo.applicationInfo.packageName
6911                            .equals(ai.applicationInfo.packageName)) {
6912                        continue;
6913                    }
6914                    if (!ri.activityInfo.name.equals(ai.name)) {
6915                        continue;
6916                    }
6917                    //  Found a persistent preference that can handle the intent.
6918                    if (DEBUG_PREFERRED || debug) {
6919                        Slog.v(TAG, "Returning persistent preferred activity: " +
6920                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6921                    }
6922                    return ri;
6923                }
6924            }
6925        }
6926        return null;
6927    }
6928
6929    // TODO: handle preferred activities missing while user has amnesia
6930    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6931            List<ResolveInfo> query, int priority, boolean always,
6932            boolean removeMatches, boolean debug, int userId) {
6933        if (!sUserManager.exists(userId)) return null;
6934        final int callingUid = Binder.getCallingUid();
6935        flags = updateFlagsForResolve(
6936                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6937        intent = updateIntentForResolve(intent);
6938        // writer
6939        synchronized (mPackages) {
6940            // Try to find a matching persistent preferred activity.
6941            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6942                    debug, userId);
6943
6944            // If a persistent preferred activity matched, use it.
6945            if (pri != null) {
6946                return pri;
6947            }
6948
6949            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6950            // Get the list of preferred activities that handle the intent
6951            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6952            List<PreferredActivity> prefs = pir != null
6953                    ? pir.queryIntent(intent, resolvedType,
6954                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6955                            userId)
6956                    : null;
6957            if (prefs != null && prefs.size() > 0) {
6958                boolean changed = false;
6959                try {
6960                    // First figure out how good the original match set is.
6961                    // We will only allow preferred activities that came
6962                    // from the same match quality.
6963                    int match = 0;
6964
6965                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6966
6967                    final int N = query.size();
6968                    for (int j=0; j<N; j++) {
6969                        final ResolveInfo ri = query.get(j);
6970                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6971                                + ": 0x" + Integer.toHexString(match));
6972                        if (ri.match > match) {
6973                            match = ri.match;
6974                        }
6975                    }
6976
6977                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6978                            + Integer.toHexString(match));
6979
6980                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6981                    final int M = prefs.size();
6982                    for (int i=0; i<M; i++) {
6983                        final PreferredActivity pa = prefs.get(i);
6984                        if (DEBUG_PREFERRED || debug) {
6985                            Slog.v(TAG, "Checking PreferredActivity ds="
6986                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6987                                    + "\n  component=" + pa.mPref.mComponent);
6988                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6989                        }
6990                        if (pa.mPref.mMatch != match) {
6991                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6992                                    + Integer.toHexString(pa.mPref.mMatch));
6993                            continue;
6994                        }
6995                        // If it's not an "always" type preferred activity and that's what we're
6996                        // looking for, skip it.
6997                        if (always && !pa.mPref.mAlways) {
6998                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6999                            continue;
7000                        }
7001                        final ActivityInfo ai = getActivityInfo(
7002                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7003                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7004                                userId);
7005                        if (DEBUG_PREFERRED || debug) {
7006                            Slog.v(TAG, "Found preferred activity:");
7007                            if (ai != null) {
7008                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7009                            } else {
7010                                Slog.v(TAG, "  null");
7011                            }
7012                        }
7013                        if (ai == null) {
7014                            // This previously registered preferred activity
7015                            // component is no longer known.  Most likely an update
7016                            // to the app was installed and in the new version this
7017                            // component no longer exists.  Clean it up by removing
7018                            // it from the preferred activities list, and skip it.
7019                            Slog.w(TAG, "Removing dangling preferred activity: "
7020                                    + pa.mPref.mComponent);
7021                            pir.removeFilter(pa);
7022                            changed = true;
7023                            continue;
7024                        }
7025                        for (int j=0; j<N; j++) {
7026                            final ResolveInfo ri = query.get(j);
7027                            if (!ri.activityInfo.applicationInfo.packageName
7028                                    .equals(ai.applicationInfo.packageName)) {
7029                                continue;
7030                            }
7031                            if (!ri.activityInfo.name.equals(ai.name)) {
7032                                continue;
7033                            }
7034
7035                            if (removeMatches) {
7036                                pir.removeFilter(pa);
7037                                changed = true;
7038                                if (DEBUG_PREFERRED) {
7039                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7040                                }
7041                                break;
7042                            }
7043
7044                            // Okay we found a previously set preferred or last chosen app.
7045                            // If the result set is different from when this
7046                            // was created, and is not a subset of the preferred set, we need to
7047                            // clear it and re-ask the user their preference, if we're looking for
7048                            // an "always" type entry.
7049                            if (always && !pa.mPref.sameSet(query)) {
7050                                if (pa.mPref.isSuperset(query)) {
7051                                    // some components of the set are no longer present in
7052                                    // the query, but the preferred activity can still be reused
7053                                    if (DEBUG_PREFERRED) {
7054                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7055                                                + " still valid as only non-preferred components"
7056                                                + " were removed for " + intent + " type "
7057                                                + resolvedType);
7058                                    }
7059                                    // remove obsolete components and re-add the up-to-date filter
7060                                    PreferredActivity freshPa = new PreferredActivity(pa,
7061                                            pa.mPref.mMatch,
7062                                            pa.mPref.discardObsoleteComponents(query),
7063                                            pa.mPref.mComponent,
7064                                            pa.mPref.mAlways);
7065                                    pir.removeFilter(pa);
7066                                    pir.addFilter(freshPa);
7067                                    changed = true;
7068                                } else {
7069                                    Slog.i(TAG,
7070                                            "Result set changed, dropping preferred activity for "
7071                                                    + intent + " type " + resolvedType);
7072                                    if (DEBUG_PREFERRED) {
7073                                        Slog.v(TAG, "Removing preferred activity since set changed "
7074                                                + pa.mPref.mComponent);
7075                                    }
7076                                    pir.removeFilter(pa);
7077                                    // Re-add the filter as a "last chosen" entry (!always)
7078                                    PreferredActivity lastChosen = new PreferredActivity(
7079                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7080                                    pir.addFilter(lastChosen);
7081                                    changed = true;
7082                                    return null;
7083                                }
7084                            }
7085
7086                            // Yay! Either the set matched or we're looking for the last chosen
7087                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7088                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7089                            return ri;
7090                        }
7091                    }
7092                } finally {
7093                    if (changed) {
7094                        if (DEBUG_PREFERRED) {
7095                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7096                        }
7097                        scheduleWritePackageRestrictionsLocked(userId);
7098                    }
7099                }
7100            }
7101        }
7102        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7103        return null;
7104    }
7105
7106    /*
7107     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7108     */
7109    @Override
7110    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7111            int targetUserId) {
7112        mContext.enforceCallingOrSelfPermission(
7113                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7114        List<CrossProfileIntentFilter> matches =
7115                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7116        if (matches != null) {
7117            int size = matches.size();
7118            for (int i = 0; i < size; i++) {
7119                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7120            }
7121        }
7122        if (hasWebURI(intent)) {
7123            // cross-profile app linking works only towards the parent.
7124            final int callingUid = Binder.getCallingUid();
7125            final UserInfo parent = getProfileParent(sourceUserId);
7126            synchronized(mPackages) {
7127                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7128                        false /*includeInstantApps*/);
7129                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7130                        intent, resolvedType, flags, sourceUserId, parent.id);
7131                return xpDomainInfo != null;
7132            }
7133        }
7134        return false;
7135    }
7136
7137    private UserInfo getProfileParent(int userId) {
7138        final long identity = Binder.clearCallingIdentity();
7139        try {
7140            return sUserManager.getProfileParent(userId);
7141        } finally {
7142            Binder.restoreCallingIdentity(identity);
7143        }
7144    }
7145
7146    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7147            String resolvedType, int userId) {
7148        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7149        if (resolver != null) {
7150            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7151        }
7152        return null;
7153    }
7154
7155    @Override
7156    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7157            String resolvedType, int flags, int userId) {
7158        try {
7159            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7160
7161            return new ParceledListSlice<>(
7162                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7163        } finally {
7164            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7165        }
7166    }
7167
7168    /**
7169     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7170     * instant, returns {@code null}.
7171     */
7172    private String getInstantAppPackageName(int callingUid) {
7173        synchronized (mPackages) {
7174            // If the caller is an isolated app use the owner's uid for the lookup.
7175            if (Process.isIsolated(callingUid)) {
7176                callingUid = mIsolatedOwners.get(callingUid);
7177            }
7178            final int appId = UserHandle.getAppId(callingUid);
7179            final Object obj = mSettings.getUserIdLPr(appId);
7180            if (obj instanceof PackageSetting) {
7181                final PackageSetting ps = (PackageSetting) obj;
7182                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7183                return isInstantApp ? ps.pkg.packageName : null;
7184            }
7185        }
7186        return null;
7187    }
7188
7189    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7190            String resolvedType, int flags, int userId) {
7191        return queryIntentActivitiesInternal(
7192                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7193                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7194    }
7195
7196    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7197            String resolvedType, int flags, int filterCallingUid, int userId,
7198            boolean resolveForStart, boolean allowDynamicSplits) {
7199        if (!sUserManager.exists(userId)) return Collections.emptyList();
7200        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7201        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7202                false /* requireFullPermission */, false /* checkShell */,
7203                "query intent activities");
7204        final String pkgName = intent.getPackage();
7205        ComponentName comp = intent.getComponent();
7206        if (comp == null) {
7207            if (intent.getSelector() != null) {
7208                intent = intent.getSelector();
7209                comp = intent.getComponent();
7210            }
7211        }
7212
7213        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7214                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7215        if (comp != null) {
7216            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7217            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7218            if (ai != null) {
7219                // When specifying an explicit component, we prevent the activity from being
7220                // used when either 1) the calling package is normal and the activity is within
7221                // an ephemeral application or 2) the calling package is ephemeral and the
7222                // activity is not visible to ephemeral applications.
7223                final boolean matchInstantApp =
7224                        (flags & PackageManager.MATCH_INSTANT) != 0;
7225                final boolean matchVisibleToInstantAppOnly =
7226                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7227                final boolean matchExplicitlyVisibleOnly =
7228                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7229                final boolean isCallerInstantApp =
7230                        instantAppPkgName != null;
7231                final boolean isTargetSameInstantApp =
7232                        comp.getPackageName().equals(instantAppPkgName);
7233                final boolean isTargetInstantApp =
7234                        (ai.applicationInfo.privateFlags
7235                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7236                final boolean isTargetVisibleToInstantApp =
7237                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7238                final boolean isTargetExplicitlyVisibleToInstantApp =
7239                        isTargetVisibleToInstantApp
7240                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7241                final boolean isTargetHiddenFromInstantApp =
7242                        !isTargetVisibleToInstantApp
7243                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7244                final boolean blockResolution =
7245                        !isTargetSameInstantApp
7246                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7247                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7248                                        && isTargetHiddenFromInstantApp));
7249                if (!blockResolution) {
7250                    final ResolveInfo ri = new ResolveInfo();
7251                    ri.activityInfo = ai;
7252                    list.add(ri);
7253                }
7254            }
7255            return applyPostResolutionFilter(
7256                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7257        }
7258
7259        // reader
7260        boolean sortResult = false;
7261        boolean addEphemeral = false;
7262        List<ResolveInfo> result;
7263        final boolean ephemeralDisabled = isEphemeralDisabled();
7264        synchronized (mPackages) {
7265            if (pkgName == null) {
7266                List<CrossProfileIntentFilter> matchingFilters =
7267                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7268                // Check for results that need to skip the current profile.
7269                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7270                        resolvedType, flags, userId);
7271                if (xpResolveInfo != null) {
7272                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7273                    xpResult.add(xpResolveInfo);
7274                    return applyPostResolutionFilter(
7275                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7276                            allowDynamicSplits, filterCallingUid, userId);
7277                }
7278
7279                // Check for results in the current profile.
7280                result = filterIfNotSystemUser(mActivities.queryIntent(
7281                        intent, resolvedType, flags, userId), userId);
7282                addEphemeral = !ephemeralDisabled
7283                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7284                // Check for cross profile results.
7285                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7286                xpResolveInfo = queryCrossProfileIntents(
7287                        matchingFilters, intent, resolvedType, flags, userId,
7288                        hasNonNegativePriorityResult);
7289                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7290                    boolean isVisibleToUser = filterIfNotSystemUser(
7291                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7292                    if (isVisibleToUser) {
7293                        result.add(xpResolveInfo);
7294                        sortResult = true;
7295                    }
7296                }
7297                if (hasWebURI(intent)) {
7298                    CrossProfileDomainInfo xpDomainInfo = null;
7299                    final UserInfo parent = getProfileParent(userId);
7300                    if (parent != null) {
7301                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7302                                flags, userId, parent.id);
7303                    }
7304                    if (xpDomainInfo != null) {
7305                        if (xpResolveInfo != null) {
7306                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7307                            // in the result.
7308                            result.remove(xpResolveInfo);
7309                        }
7310                        if (result.size() == 0 && !addEphemeral) {
7311                            // No result in current profile, but found candidate in parent user.
7312                            // And we are not going to add emphemeral app, so we can return the
7313                            // result straight away.
7314                            result.add(xpDomainInfo.resolveInfo);
7315                            return applyPostResolutionFilter(result, instantAppPkgName,
7316                                    allowDynamicSplits, filterCallingUid, userId);
7317                        }
7318                    } else if (result.size() <= 1 && !addEphemeral) {
7319                        // No result in parent user and <= 1 result in current profile, and we
7320                        // are not going to add emphemeral app, so we can return the result without
7321                        // further processing.
7322                        return applyPostResolutionFilter(result, instantAppPkgName,
7323                                allowDynamicSplits, filterCallingUid, userId);
7324                    }
7325                    // We have more than one candidate (combining results from current and parent
7326                    // profile), so we need filtering and sorting.
7327                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7328                            intent, flags, result, xpDomainInfo, userId);
7329                    sortResult = true;
7330                }
7331            } else {
7332                final PackageParser.Package pkg = mPackages.get(pkgName);
7333                result = null;
7334                if (pkg != null) {
7335                    result = filterIfNotSystemUser(
7336                            mActivities.queryIntentForPackage(
7337                                    intent, resolvedType, flags, pkg.activities, userId),
7338                            userId);
7339                }
7340                if (result == null || result.size() == 0) {
7341                    // the caller wants to resolve for a particular package; however, there
7342                    // were no installed results, so, try to find an ephemeral result
7343                    addEphemeral = !ephemeralDisabled
7344                            && isInstantAppAllowed(
7345                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7346                    if (result == null) {
7347                        result = new ArrayList<>();
7348                    }
7349                }
7350            }
7351        }
7352        if (addEphemeral) {
7353            result = maybeAddInstantAppInstaller(
7354                    result, intent, resolvedType, flags, userId, resolveForStart);
7355        }
7356        if (sortResult) {
7357            Collections.sort(result, mResolvePrioritySorter);
7358        }
7359        return applyPostResolutionFilter(
7360                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7361    }
7362
7363    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7364            String resolvedType, int flags, int userId, boolean resolveForStart) {
7365        // first, check to see if we've got an instant app already installed
7366        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7367        ResolveInfo localInstantApp = null;
7368        boolean blockResolution = false;
7369        if (!alreadyResolvedLocally) {
7370            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7371                    flags
7372                        | PackageManager.GET_RESOLVED_FILTER
7373                        | PackageManager.MATCH_INSTANT
7374                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7375                    userId);
7376            for (int i = instantApps.size() - 1; i >= 0; --i) {
7377                final ResolveInfo info = instantApps.get(i);
7378                final String packageName = info.activityInfo.packageName;
7379                final PackageSetting ps = mSettings.mPackages.get(packageName);
7380                if (ps.getInstantApp(userId)) {
7381                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7382                    final int status = (int)(packedStatus >> 32);
7383                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7384                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7385                        // there's a local instant application installed, but, the user has
7386                        // chosen to never use it; skip resolution and don't acknowledge
7387                        // an instant application is even available
7388                        if (DEBUG_EPHEMERAL) {
7389                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7390                        }
7391                        blockResolution = true;
7392                        break;
7393                    } else {
7394                        // we have a locally installed instant application; skip resolution
7395                        // but acknowledge there's an instant application available
7396                        if (DEBUG_EPHEMERAL) {
7397                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7398                        }
7399                        localInstantApp = info;
7400                        break;
7401                    }
7402                }
7403            }
7404        }
7405        // no app installed, let's see if one's available
7406        AuxiliaryResolveInfo auxiliaryResponse = null;
7407        if (!blockResolution) {
7408            if (localInstantApp == null) {
7409                // we don't have an instant app locally, resolve externally
7410                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7411                final InstantAppRequest requestObject = new InstantAppRequest(
7412                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7413                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7414                        resolveForStart);
7415                auxiliaryResponse =
7416                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7417                                mContext, mInstantAppResolverConnection, requestObject);
7418                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7419            } else {
7420                // we have an instant application locally, but, we can't admit that since
7421                // callers shouldn't be able to determine prior browsing. create a dummy
7422                // auxiliary response so the downstream code behaves as if there's an
7423                // instant application available externally. when it comes time to start
7424                // the instant application, we'll do the right thing.
7425                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7426                auxiliaryResponse = new AuxiliaryResolveInfo(
7427                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7428                        ai.versionCode, null /*failureIntent*/);
7429            }
7430        }
7431        if (auxiliaryResponse != null) {
7432            if (DEBUG_EPHEMERAL) {
7433                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7434            }
7435            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7436            final PackageSetting ps =
7437                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7438            if (ps != null) {
7439                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7440                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7441                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7442                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7443                // make sure this resolver is the default
7444                ephemeralInstaller.isDefault = true;
7445                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7446                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7447                // add a non-generic filter
7448                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7449                ephemeralInstaller.filter.addDataPath(
7450                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7451                ephemeralInstaller.isInstantAppAvailable = true;
7452                result.add(ephemeralInstaller);
7453            }
7454        }
7455        return result;
7456    }
7457
7458    private static class CrossProfileDomainInfo {
7459        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7460        ResolveInfo resolveInfo;
7461        /* Best domain verification status of the activities found in the other profile */
7462        int bestDomainVerificationStatus;
7463    }
7464
7465    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7466            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7467        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7468                sourceUserId)) {
7469            return null;
7470        }
7471        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7472                resolvedType, flags, parentUserId);
7473
7474        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7475            return null;
7476        }
7477        CrossProfileDomainInfo result = null;
7478        int size = resultTargetUser.size();
7479        for (int i = 0; i < size; i++) {
7480            ResolveInfo riTargetUser = resultTargetUser.get(i);
7481            // Intent filter verification is only for filters that specify a host. So don't return
7482            // those that handle all web uris.
7483            if (riTargetUser.handleAllWebDataURI) {
7484                continue;
7485            }
7486            String packageName = riTargetUser.activityInfo.packageName;
7487            PackageSetting ps = mSettings.mPackages.get(packageName);
7488            if (ps == null) {
7489                continue;
7490            }
7491            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7492            int status = (int)(verificationState >> 32);
7493            if (result == null) {
7494                result = new CrossProfileDomainInfo();
7495                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7496                        sourceUserId, parentUserId);
7497                result.bestDomainVerificationStatus = status;
7498            } else {
7499                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7500                        result.bestDomainVerificationStatus);
7501            }
7502        }
7503        // Don't consider matches with status NEVER across profiles.
7504        if (result != null && result.bestDomainVerificationStatus
7505                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7506            return null;
7507        }
7508        return result;
7509    }
7510
7511    /**
7512     * Verification statuses are ordered from the worse to the best, except for
7513     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7514     */
7515    private int bestDomainVerificationStatus(int status1, int status2) {
7516        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7517            return status2;
7518        }
7519        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7520            return status1;
7521        }
7522        return (int) MathUtils.max(status1, status2);
7523    }
7524
7525    private boolean isUserEnabled(int userId) {
7526        long callingId = Binder.clearCallingIdentity();
7527        try {
7528            UserInfo userInfo = sUserManager.getUserInfo(userId);
7529            return userInfo != null && userInfo.isEnabled();
7530        } finally {
7531            Binder.restoreCallingIdentity(callingId);
7532        }
7533    }
7534
7535    /**
7536     * Filter out activities with systemUserOnly flag set, when current user is not System.
7537     *
7538     * @return filtered list
7539     */
7540    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7541        if (userId == UserHandle.USER_SYSTEM) {
7542            return resolveInfos;
7543        }
7544        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7545            ResolveInfo info = resolveInfos.get(i);
7546            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7547                resolveInfos.remove(i);
7548            }
7549        }
7550        return resolveInfos;
7551    }
7552
7553    /**
7554     * Filters out ephemeral activities.
7555     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7556     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7557     *
7558     * @param resolveInfos The pre-filtered list of resolved activities
7559     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7560     *          is performed.
7561     * @return A filtered list of resolved activities.
7562     */
7563    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7564            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7565        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7566            final ResolveInfo info = resolveInfos.get(i);
7567            // allow activities that are defined in the provided package
7568            if (allowDynamicSplits
7569                    && info.activityInfo.splitName != null
7570                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7571                            info.activityInfo.splitName)) {
7572                // requested activity is defined in a split that hasn't been installed yet.
7573                // add the installer to the resolve list
7574                if (DEBUG_INSTALL) {
7575                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7576                }
7577                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7578                final ComponentName installFailureActivity = findInstallFailureActivity(
7579                        info.activityInfo.packageName,  filterCallingUid, userId);
7580                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7581                        info.activityInfo.packageName, info.activityInfo.splitName,
7582                        installFailureActivity,
7583                        info.activityInfo.applicationInfo.versionCode,
7584                        null /*failureIntent*/);
7585                // make sure this resolver is the default
7586                installerInfo.isDefault = true;
7587                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7588                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7589                // add a non-generic filter
7590                installerInfo.filter = new IntentFilter();
7591                // load resources from the correct package
7592                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7593                resolveInfos.set(i, installerInfo);
7594                continue;
7595            }
7596            // caller is a full app, don't need to apply any other filtering
7597            if (ephemeralPkgName == null) {
7598                continue;
7599            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7600                // caller is same app; don't need to apply any other filtering
7601                continue;
7602            }
7603            // allow activities that have been explicitly exposed to ephemeral apps
7604            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7605            if (!isEphemeralApp
7606                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7607                continue;
7608            }
7609            resolveInfos.remove(i);
7610        }
7611        return resolveInfos;
7612    }
7613
7614    /**
7615     * Returns the activity component that can handle install failures.
7616     * <p>By default, the instant application installer handles failures. However, an
7617     * application may want to handle failures on its own. Applications do this by
7618     * creating an activity with an intent filter that handles the action
7619     * {@link Intent#ACTION_INSTALL_FAILURE}.
7620     */
7621    private @Nullable ComponentName findInstallFailureActivity(
7622            String packageName, int filterCallingUid, int userId) {
7623        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7624        failureActivityIntent.setPackage(packageName);
7625        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7626        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7627                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7628                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7629        final int NR = result.size();
7630        if (NR > 0) {
7631            for (int i = 0; i < NR; i++) {
7632                final ResolveInfo info = result.get(i);
7633                if (info.activityInfo.splitName != null) {
7634                    continue;
7635                }
7636                return new ComponentName(packageName, info.activityInfo.name);
7637            }
7638        }
7639        return null;
7640    }
7641
7642    /**
7643     * @param resolveInfos list of resolve infos in descending priority order
7644     * @return if the list contains a resolve info with non-negative priority
7645     */
7646    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7647        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7648    }
7649
7650    private static boolean hasWebURI(Intent intent) {
7651        if (intent.getData() == null) {
7652            return false;
7653        }
7654        final String scheme = intent.getScheme();
7655        if (TextUtils.isEmpty(scheme)) {
7656            return false;
7657        }
7658        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7659    }
7660
7661    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7662            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7663            int userId) {
7664        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7665
7666        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7667            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7668                    candidates.size());
7669        }
7670
7671        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7672        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7673        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7674        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7675        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7676        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7677
7678        synchronized (mPackages) {
7679            final int count = candidates.size();
7680            // First, try to use linked apps. Partition the candidates into four lists:
7681            // one for the final results, one for the "do not use ever", one for "undefined status"
7682            // and finally one for "browser app type".
7683            for (int n=0; n<count; n++) {
7684                ResolveInfo info = candidates.get(n);
7685                String packageName = info.activityInfo.packageName;
7686                PackageSetting ps = mSettings.mPackages.get(packageName);
7687                if (ps != null) {
7688                    // Add to the special match all list (Browser use case)
7689                    if (info.handleAllWebDataURI) {
7690                        matchAllList.add(info);
7691                        continue;
7692                    }
7693                    // Try to get the status from User settings first
7694                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7695                    int status = (int)(packedStatus >> 32);
7696                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7697                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7698                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7699                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7700                                    + " : linkgen=" + linkGeneration);
7701                        }
7702                        // Use link-enabled generation as preferredOrder, i.e.
7703                        // prefer newly-enabled over earlier-enabled.
7704                        info.preferredOrder = linkGeneration;
7705                        alwaysList.add(info);
7706                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7707                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7708                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7709                        }
7710                        neverList.add(info);
7711                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7712                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7713                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7714                        }
7715                        alwaysAskList.add(info);
7716                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7717                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7718                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7719                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7720                        }
7721                        undefinedList.add(info);
7722                    }
7723                }
7724            }
7725
7726            // We'll want to include browser possibilities in a few cases
7727            boolean includeBrowser = false;
7728
7729            // First try to add the "always" resolution(s) for the current user, if any
7730            if (alwaysList.size() > 0) {
7731                result.addAll(alwaysList);
7732            } else {
7733                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7734                result.addAll(undefinedList);
7735                // Maybe add one for the other profile.
7736                if (xpDomainInfo != null && (
7737                        xpDomainInfo.bestDomainVerificationStatus
7738                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7739                    result.add(xpDomainInfo.resolveInfo);
7740                }
7741                includeBrowser = true;
7742            }
7743
7744            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7745            // If there were 'always' entries their preferred order has been set, so we also
7746            // back that off to make the alternatives equivalent
7747            if (alwaysAskList.size() > 0) {
7748                for (ResolveInfo i : result) {
7749                    i.preferredOrder = 0;
7750                }
7751                result.addAll(alwaysAskList);
7752                includeBrowser = true;
7753            }
7754
7755            if (includeBrowser) {
7756                // Also add browsers (all of them or only the default one)
7757                if (DEBUG_DOMAIN_VERIFICATION) {
7758                    Slog.v(TAG, "   ...including browsers in candidate set");
7759                }
7760                if ((matchFlags & MATCH_ALL) != 0) {
7761                    result.addAll(matchAllList);
7762                } else {
7763                    // Browser/generic handling case.  If there's a default browser, go straight
7764                    // to that (but only if there is no other higher-priority match).
7765                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7766                    int maxMatchPrio = 0;
7767                    ResolveInfo defaultBrowserMatch = null;
7768                    final int numCandidates = matchAllList.size();
7769                    for (int n = 0; n < numCandidates; n++) {
7770                        ResolveInfo info = matchAllList.get(n);
7771                        // track the highest overall match priority...
7772                        if (info.priority > maxMatchPrio) {
7773                            maxMatchPrio = info.priority;
7774                        }
7775                        // ...and the highest-priority default browser match
7776                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7777                            if (defaultBrowserMatch == null
7778                                    || (defaultBrowserMatch.priority < info.priority)) {
7779                                if (debug) {
7780                                    Slog.v(TAG, "Considering default browser match " + info);
7781                                }
7782                                defaultBrowserMatch = info;
7783                            }
7784                        }
7785                    }
7786                    if (defaultBrowserMatch != null
7787                            && defaultBrowserMatch.priority >= maxMatchPrio
7788                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7789                    {
7790                        if (debug) {
7791                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7792                        }
7793                        result.add(defaultBrowserMatch);
7794                    } else {
7795                        result.addAll(matchAllList);
7796                    }
7797                }
7798
7799                // If there is nothing selected, add all candidates and remove the ones that the user
7800                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7801                if (result.size() == 0) {
7802                    result.addAll(candidates);
7803                    result.removeAll(neverList);
7804                }
7805            }
7806        }
7807        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7808            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7809                    result.size());
7810            for (ResolveInfo info : result) {
7811                Slog.v(TAG, "  + " + info.activityInfo);
7812            }
7813        }
7814        return result;
7815    }
7816
7817    // Returns a packed value as a long:
7818    //
7819    // high 'int'-sized word: link status: undefined/ask/never/always.
7820    // low 'int'-sized word: relative priority among 'always' results.
7821    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7822        long result = ps.getDomainVerificationStatusForUser(userId);
7823        // if none available, get the master status
7824        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7825            if (ps.getIntentFilterVerificationInfo() != null) {
7826                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7827            }
7828        }
7829        return result;
7830    }
7831
7832    private ResolveInfo querySkipCurrentProfileIntents(
7833            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7834            int flags, int sourceUserId) {
7835        if (matchingFilters != null) {
7836            int size = matchingFilters.size();
7837            for (int i = 0; i < size; i ++) {
7838                CrossProfileIntentFilter filter = matchingFilters.get(i);
7839                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7840                    // Checking if there are activities in the target user that can handle the
7841                    // intent.
7842                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7843                            resolvedType, flags, sourceUserId);
7844                    if (resolveInfo != null) {
7845                        return resolveInfo;
7846                    }
7847                }
7848            }
7849        }
7850        return null;
7851    }
7852
7853    // Return matching ResolveInfo in target user if any.
7854    private ResolveInfo queryCrossProfileIntents(
7855            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7856            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7857        if (matchingFilters != null) {
7858            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7859            // match the same intent. For performance reasons, it is better not to
7860            // run queryIntent twice for the same userId
7861            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7862            int size = matchingFilters.size();
7863            for (int i = 0; i < size; i++) {
7864                CrossProfileIntentFilter filter = matchingFilters.get(i);
7865                int targetUserId = filter.getTargetUserId();
7866                boolean skipCurrentProfile =
7867                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7868                boolean skipCurrentProfileIfNoMatchFound =
7869                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7870                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7871                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7872                    // Checking if there are activities in the target user that can handle the
7873                    // intent.
7874                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7875                            resolvedType, flags, sourceUserId);
7876                    if (resolveInfo != null) return resolveInfo;
7877                    alreadyTriedUserIds.put(targetUserId, true);
7878                }
7879            }
7880        }
7881        return null;
7882    }
7883
7884    /**
7885     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7886     * will forward the intent to the filter's target user.
7887     * Otherwise, returns null.
7888     */
7889    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7890            String resolvedType, int flags, int sourceUserId) {
7891        int targetUserId = filter.getTargetUserId();
7892        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7893                resolvedType, flags, targetUserId);
7894        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7895            // If all the matches in the target profile are suspended, return null.
7896            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7897                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7898                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7899                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7900                            targetUserId);
7901                }
7902            }
7903        }
7904        return null;
7905    }
7906
7907    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7908            int sourceUserId, int targetUserId) {
7909        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7910        long ident = Binder.clearCallingIdentity();
7911        boolean targetIsProfile;
7912        try {
7913            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7914        } finally {
7915            Binder.restoreCallingIdentity(ident);
7916        }
7917        String className;
7918        if (targetIsProfile) {
7919            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7920        } else {
7921            className = FORWARD_INTENT_TO_PARENT;
7922        }
7923        ComponentName forwardingActivityComponentName = new ComponentName(
7924                mAndroidApplication.packageName, className);
7925        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7926                sourceUserId);
7927        if (!targetIsProfile) {
7928            forwardingActivityInfo.showUserIcon = targetUserId;
7929            forwardingResolveInfo.noResourceId = true;
7930        }
7931        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7932        forwardingResolveInfo.priority = 0;
7933        forwardingResolveInfo.preferredOrder = 0;
7934        forwardingResolveInfo.match = 0;
7935        forwardingResolveInfo.isDefault = true;
7936        forwardingResolveInfo.filter = filter;
7937        forwardingResolveInfo.targetUserId = targetUserId;
7938        return forwardingResolveInfo;
7939    }
7940
7941    @Override
7942    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7943            Intent[] specifics, String[] specificTypes, Intent intent,
7944            String resolvedType, int flags, int userId) {
7945        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7946                specificTypes, intent, resolvedType, flags, userId));
7947    }
7948
7949    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7950            Intent[] specifics, String[] specificTypes, Intent intent,
7951            String resolvedType, int flags, int userId) {
7952        if (!sUserManager.exists(userId)) return Collections.emptyList();
7953        final int callingUid = Binder.getCallingUid();
7954        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7955                false /*includeInstantApps*/);
7956        enforceCrossUserPermission(callingUid, userId,
7957                false /*requireFullPermission*/, false /*checkShell*/,
7958                "query intent activity options");
7959        final String resultsAction = intent.getAction();
7960
7961        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7962                | PackageManager.GET_RESOLVED_FILTER, userId);
7963
7964        if (DEBUG_INTENT_MATCHING) {
7965            Log.v(TAG, "Query " + intent + ": " + results);
7966        }
7967
7968        int specificsPos = 0;
7969        int N;
7970
7971        // todo: note that the algorithm used here is O(N^2).  This
7972        // isn't a problem in our current environment, but if we start running
7973        // into situations where we have more than 5 or 10 matches then this
7974        // should probably be changed to something smarter...
7975
7976        // First we go through and resolve each of the specific items
7977        // that were supplied, taking care of removing any corresponding
7978        // duplicate items in the generic resolve list.
7979        if (specifics != null) {
7980            for (int i=0; i<specifics.length; i++) {
7981                final Intent sintent = specifics[i];
7982                if (sintent == null) {
7983                    continue;
7984                }
7985
7986                if (DEBUG_INTENT_MATCHING) {
7987                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7988                }
7989
7990                String action = sintent.getAction();
7991                if (resultsAction != null && resultsAction.equals(action)) {
7992                    // If this action was explicitly requested, then don't
7993                    // remove things that have it.
7994                    action = null;
7995                }
7996
7997                ResolveInfo ri = null;
7998                ActivityInfo ai = null;
7999
8000                ComponentName comp = sintent.getComponent();
8001                if (comp == null) {
8002                    ri = resolveIntent(
8003                        sintent,
8004                        specificTypes != null ? specificTypes[i] : null,
8005                            flags, userId);
8006                    if (ri == null) {
8007                        continue;
8008                    }
8009                    if (ri == mResolveInfo) {
8010                        // ACK!  Must do something better with this.
8011                    }
8012                    ai = ri.activityInfo;
8013                    comp = new ComponentName(ai.applicationInfo.packageName,
8014                            ai.name);
8015                } else {
8016                    ai = getActivityInfo(comp, flags, userId);
8017                    if (ai == null) {
8018                        continue;
8019                    }
8020                }
8021
8022                // Look for any generic query activities that are duplicates
8023                // of this specific one, and remove them from the results.
8024                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8025                N = results.size();
8026                int j;
8027                for (j=specificsPos; j<N; j++) {
8028                    ResolveInfo sri = results.get(j);
8029                    if ((sri.activityInfo.name.equals(comp.getClassName())
8030                            && sri.activityInfo.applicationInfo.packageName.equals(
8031                                    comp.getPackageName()))
8032                        || (action != null && sri.filter.matchAction(action))) {
8033                        results.remove(j);
8034                        if (DEBUG_INTENT_MATCHING) Log.v(
8035                            TAG, "Removing duplicate item from " + j
8036                            + " due to specific " + specificsPos);
8037                        if (ri == null) {
8038                            ri = sri;
8039                        }
8040                        j--;
8041                        N--;
8042                    }
8043                }
8044
8045                // Add this specific item to its proper place.
8046                if (ri == null) {
8047                    ri = new ResolveInfo();
8048                    ri.activityInfo = ai;
8049                }
8050                results.add(specificsPos, ri);
8051                ri.specificIndex = i;
8052                specificsPos++;
8053            }
8054        }
8055
8056        // Now we go through the remaining generic results and remove any
8057        // duplicate actions that are found here.
8058        N = results.size();
8059        for (int i=specificsPos; i<N-1; i++) {
8060            final ResolveInfo rii = results.get(i);
8061            if (rii.filter == null) {
8062                continue;
8063            }
8064
8065            // Iterate over all of the actions of this result's intent
8066            // filter...  typically this should be just one.
8067            final Iterator<String> it = rii.filter.actionsIterator();
8068            if (it == null) {
8069                continue;
8070            }
8071            while (it.hasNext()) {
8072                final String action = it.next();
8073                if (resultsAction != null && resultsAction.equals(action)) {
8074                    // If this action was explicitly requested, then don't
8075                    // remove things that have it.
8076                    continue;
8077                }
8078                for (int j=i+1; j<N; j++) {
8079                    final ResolveInfo rij = results.get(j);
8080                    if (rij.filter != null && rij.filter.hasAction(action)) {
8081                        results.remove(j);
8082                        if (DEBUG_INTENT_MATCHING) Log.v(
8083                            TAG, "Removing duplicate item from " + j
8084                            + " due to action " + action + " at " + i);
8085                        j--;
8086                        N--;
8087                    }
8088                }
8089            }
8090
8091            // If the caller didn't request filter information, drop it now
8092            // so we don't have to marshall/unmarshall it.
8093            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8094                rii.filter = null;
8095            }
8096        }
8097
8098        // Filter out the caller activity if so requested.
8099        if (caller != null) {
8100            N = results.size();
8101            for (int i=0; i<N; i++) {
8102                ActivityInfo ainfo = results.get(i).activityInfo;
8103                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8104                        && caller.getClassName().equals(ainfo.name)) {
8105                    results.remove(i);
8106                    break;
8107                }
8108            }
8109        }
8110
8111        // If the caller didn't request filter information,
8112        // drop them now so we don't have to
8113        // marshall/unmarshall it.
8114        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8115            N = results.size();
8116            for (int i=0; i<N; i++) {
8117                results.get(i).filter = null;
8118            }
8119        }
8120
8121        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8122        return results;
8123    }
8124
8125    @Override
8126    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8127            String resolvedType, int flags, int userId) {
8128        return new ParceledListSlice<>(
8129                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8130                        false /*allowDynamicSplits*/));
8131    }
8132
8133    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8134            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8135        if (!sUserManager.exists(userId)) return Collections.emptyList();
8136        final int callingUid = Binder.getCallingUid();
8137        enforceCrossUserPermission(callingUid, userId,
8138                false /*requireFullPermission*/, false /*checkShell*/,
8139                "query intent receivers");
8140        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8141        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8142                false /*includeInstantApps*/);
8143        ComponentName comp = intent.getComponent();
8144        if (comp == null) {
8145            if (intent.getSelector() != null) {
8146                intent = intent.getSelector();
8147                comp = intent.getComponent();
8148            }
8149        }
8150        if (comp != null) {
8151            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8152            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8153            if (ai != null) {
8154                // When specifying an explicit component, we prevent the activity from being
8155                // used when either 1) the calling package is normal and the activity is within
8156                // an instant application or 2) the calling package is ephemeral and the
8157                // activity is not visible to instant applications.
8158                final boolean matchInstantApp =
8159                        (flags & PackageManager.MATCH_INSTANT) != 0;
8160                final boolean matchVisibleToInstantAppOnly =
8161                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8162                final boolean matchExplicitlyVisibleOnly =
8163                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8164                final boolean isCallerInstantApp =
8165                        instantAppPkgName != null;
8166                final boolean isTargetSameInstantApp =
8167                        comp.getPackageName().equals(instantAppPkgName);
8168                final boolean isTargetInstantApp =
8169                        (ai.applicationInfo.privateFlags
8170                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8171                final boolean isTargetVisibleToInstantApp =
8172                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8173                final boolean isTargetExplicitlyVisibleToInstantApp =
8174                        isTargetVisibleToInstantApp
8175                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8176                final boolean isTargetHiddenFromInstantApp =
8177                        !isTargetVisibleToInstantApp
8178                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8179                final boolean blockResolution =
8180                        !isTargetSameInstantApp
8181                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8182                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8183                                        && isTargetHiddenFromInstantApp));
8184                if (!blockResolution) {
8185                    ResolveInfo ri = new ResolveInfo();
8186                    ri.activityInfo = ai;
8187                    list.add(ri);
8188                }
8189            }
8190            return applyPostResolutionFilter(
8191                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8192        }
8193
8194        // reader
8195        synchronized (mPackages) {
8196            String pkgName = intent.getPackage();
8197            if (pkgName == null) {
8198                final List<ResolveInfo> result =
8199                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8200                return applyPostResolutionFilter(
8201                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8202            }
8203            final PackageParser.Package pkg = mPackages.get(pkgName);
8204            if (pkg != null) {
8205                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8206                        intent, resolvedType, flags, pkg.receivers, userId);
8207                return applyPostResolutionFilter(
8208                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8209            }
8210            return Collections.emptyList();
8211        }
8212    }
8213
8214    @Override
8215    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8216        final int callingUid = Binder.getCallingUid();
8217        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8218    }
8219
8220    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8221            int userId, int callingUid) {
8222        if (!sUserManager.exists(userId)) return null;
8223        flags = updateFlagsForResolve(
8224                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8225        List<ResolveInfo> query = queryIntentServicesInternal(
8226                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8227        if (query != null) {
8228            if (query.size() >= 1) {
8229                // If there is more than one service with the same priority,
8230                // just arbitrarily pick the first one.
8231                return query.get(0);
8232            }
8233        }
8234        return null;
8235    }
8236
8237    @Override
8238    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8239            String resolvedType, int flags, int userId) {
8240        final int callingUid = Binder.getCallingUid();
8241        return new ParceledListSlice<>(queryIntentServicesInternal(
8242                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8243    }
8244
8245    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8246            String resolvedType, int flags, int userId, int callingUid,
8247            boolean includeInstantApps) {
8248        if (!sUserManager.exists(userId)) return Collections.emptyList();
8249        enforceCrossUserPermission(callingUid, userId,
8250                false /*requireFullPermission*/, false /*checkShell*/,
8251                "query intent receivers");
8252        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8253        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8254        ComponentName comp = intent.getComponent();
8255        if (comp == null) {
8256            if (intent.getSelector() != null) {
8257                intent = intent.getSelector();
8258                comp = intent.getComponent();
8259            }
8260        }
8261        if (comp != null) {
8262            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8263            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8264            if (si != null) {
8265                // When specifying an explicit component, we prevent the service from being
8266                // used when either 1) the service is in an instant application and the
8267                // caller is not the same instant application or 2) the calling package is
8268                // ephemeral and the activity is not visible to ephemeral applications.
8269                final boolean matchInstantApp =
8270                        (flags & PackageManager.MATCH_INSTANT) != 0;
8271                final boolean matchVisibleToInstantAppOnly =
8272                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8273                final boolean isCallerInstantApp =
8274                        instantAppPkgName != null;
8275                final boolean isTargetSameInstantApp =
8276                        comp.getPackageName().equals(instantAppPkgName);
8277                final boolean isTargetInstantApp =
8278                        (si.applicationInfo.privateFlags
8279                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8280                final boolean isTargetHiddenFromInstantApp =
8281                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8282                final boolean blockResolution =
8283                        !isTargetSameInstantApp
8284                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8285                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8286                                        && isTargetHiddenFromInstantApp));
8287                if (!blockResolution) {
8288                    final ResolveInfo ri = new ResolveInfo();
8289                    ri.serviceInfo = si;
8290                    list.add(ri);
8291                }
8292            }
8293            return list;
8294        }
8295
8296        // reader
8297        synchronized (mPackages) {
8298            String pkgName = intent.getPackage();
8299            if (pkgName == null) {
8300                return applyPostServiceResolutionFilter(
8301                        mServices.queryIntent(intent, resolvedType, flags, userId),
8302                        instantAppPkgName);
8303            }
8304            final PackageParser.Package pkg = mPackages.get(pkgName);
8305            if (pkg != null) {
8306                return applyPostServiceResolutionFilter(
8307                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8308                                userId),
8309                        instantAppPkgName);
8310            }
8311            return Collections.emptyList();
8312        }
8313    }
8314
8315    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8316            String instantAppPkgName) {
8317        if (instantAppPkgName == null) {
8318            return resolveInfos;
8319        }
8320        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8321            final ResolveInfo info = resolveInfos.get(i);
8322            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8323            // allow services that are defined in the provided package
8324            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8325                if (info.serviceInfo.splitName != null
8326                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8327                                info.serviceInfo.splitName)) {
8328                    // requested service is defined in a split that hasn't been installed yet.
8329                    // add the installer to the resolve list
8330                    if (DEBUG_EPHEMERAL) {
8331                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8332                    }
8333                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8334                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8335                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8336                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8337                            null /*failureIntent*/);
8338                    // make sure this resolver is the default
8339                    installerInfo.isDefault = true;
8340                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8341                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8342                    // add a non-generic filter
8343                    installerInfo.filter = new IntentFilter();
8344                    // load resources from the correct package
8345                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8346                    resolveInfos.set(i, installerInfo);
8347                }
8348                continue;
8349            }
8350            // allow services that have been explicitly exposed to ephemeral apps
8351            if (!isEphemeralApp
8352                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8353                continue;
8354            }
8355            resolveInfos.remove(i);
8356        }
8357        return resolveInfos;
8358    }
8359
8360    @Override
8361    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8362            String resolvedType, int flags, int userId) {
8363        return new ParceledListSlice<>(
8364                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8365    }
8366
8367    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8368            Intent intent, String resolvedType, int flags, int userId) {
8369        if (!sUserManager.exists(userId)) return Collections.emptyList();
8370        final int callingUid = Binder.getCallingUid();
8371        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8372        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8373                false /*includeInstantApps*/);
8374        ComponentName comp = intent.getComponent();
8375        if (comp == null) {
8376            if (intent.getSelector() != null) {
8377                intent = intent.getSelector();
8378                comp = intent.getComponent();
8379            }
8380        }
8381        if (comp != null) {
8382            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8383            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8384            if (pi != null) {
8385                // When specifying an explicit component, we prevent the provider from being
8386                // used when either 1) the provider is in an instant application and the
8387                // caller is not the same instant application or 2) the calling package is an
8388                // instant application and the provider is not visible to instant applications.
8389                final boolean matchInstantApp =
8390                        (flags & PackageManager.MATCH_INSTANT) != 0;
8391                final boolean matchVisibleToInstantAppOnly =
8392                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8393                final boolean isCallerInstantApp =
8394                        instantAppPkgName != null;
8395                final boolean isTargetSameInstantApp =
8396                        comp.getPackageName().equals(instantAppPkgName);
8397                final boolean isTargetInstantApp =
8398                        (pi.applicationInfo.privateFlags
8399                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8400                final boolean isTargetHiddenFromInstantApp =
8401                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8402                final boolean blockResolution =
8403                        !isTargetSameInstantApp
8404                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8405                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8406                                        && isTargetHiddenFromInstantApp));
8407                if (!blockResolution) {
8408                    final ResolveInfo ri = new ResolveInfo();
8409                    ri.providerInfo = pi;
8410                    list.add(ri);
8411                }
8412            }
8413            return list;
8414        }
8415
8416        // reader
8417        synchronized (mPackages) {
8418            String pkgName = intent.getPackage();
8419            if (pkgName == null) {
8420                return applyPostContentProviderResolutionFilter(
8421                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8422                        instantAppPkgName);
8423            }
8424            final PackageParser.Package pkg = mPackages.get(pkgName);
8425            if (pkg != null) {
8426                return applyPostContentProviderResolutionFilter(
8427                        mProviders.queryIntentForPackage(
8428                        intent, resolvedType, flags, pkg.providers, userId),
8429                        instantAppPkgName);
8430            }
8431            return Collections.emptyList();
8432        }
8433    }
8434
8435    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8436            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8437        if (instantAppPkgName == null) {
8438            return resolveInfos;
8439        }
8440        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8441            final ResolveInfo info = resolveInfos.get(i);
8442            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8443            // allow providers that are defined in the provided package
8444            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8445                if (info.providerInfo.splitName != null
8446                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8447                                info.providerInfo.splitName)) {
8448                    // requested provider is defined in a split that hasn't been installed yet.
8449                    // add the installer to the resolve list
8450                    if (DEBUG_EPHEMERAL) {
8451                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8452                    }
8453                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8454                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8455                            info.providerInfo.packageName, info.providerInfo.splitName,
8456                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8457                            null /*failureIntent*/);
8458                    // make sure this resolver is the default
8459                    installerInfo.isDefault = true;
8460                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8461                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8462                    // add a non-generic filter
8463                    installerInfo.filter = new IntentFilter();
8464                    // load resources from the correct package
8465                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8466                    resolveInfos.set(i, installerInfo);
8467                }
8468                continue;
8469            }
8470            // allow providers that have been explicitly exposed to instant applications
8471            if (!isEphemeralApp
8472                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8473                continue;
8474            }
8475            resolveInfos.remove(i);
8476        }
8477        return resolveInfos;
8478    }
8479
8480    @Override
8481    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8482        final int callingUid = Binder.getCallingUid();
8483        if (getInstantAppPackageName(callingUid) != null) {
8484            return ParceledListSlice.emptyList();
8485        }
8486        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8487        flags = updateFlagsForPackage(flags, userId, null);
8488        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8489        enforceCrossUserPermission(callingUid, userId,
8490                true /* requireFullPermission */, false /* checkShell */,
8491                "get installed packages");
8492
8493        // writer
8494        synchronized (mPackages) {
8495            ArrayList<PackageInfo> list;
8496            if (listUninstalled) {
8497                list = new ArrayList<>(mSettings.mPackages.size());
8498                for (PackageSetting ps : mSettings.mPackages.values()) {
8499                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8500                        continue;
8501                    }
8502                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8503                        continue;
8504                    }
8505                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8506                    if (pi != null) {
8507                        list.add(pi);
8508                    }
8509                }
8510            } else {
8511                list = new ArrayList<>(mPackages.size());
8512                for (PackageParser.Package p : mPackages.values()) {
8513                    final PackageSetting ps = (PackageSetting) p.mExtras;
8514                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8515                        continue;
8516                    }
8517                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8518                        continue;
8519                    }
8520                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8521                            p.mExtras, flags, userId);
8522                    if (pi != null) {
8523                        list.add(pi);
8524                    }
8525                }
8526            }
8527
8528            return new ParceledListSlice<>(list);
8529        }
8530    }
8531
8532    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8533            String[] permissions, boolean[] tmp, int flags, int userId) {
8534        int numMatch = 0;
8535        final PermissionsState permissionsState = ps.getPermissionsState();
8536        for (int i=0; i<permissions.length; i++) {
8537            final String permission = permissions[i];
8538            if (permissionsState.hasPermission(permission, userId)) {
8539                tmp[i] = true;
8540                numMatch++;
8541            } else {
8542                tmp[i] = false;
8543            }
8544        }
8545        if (numMatch == 0) {
8546            return;
8547        }
8548        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8549
8550        // The above might return null in cases of uninstalled apps or install-state
8551        // skew across users/profiles.
8552        if (pi != null) {
8553            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8554                if (numMatch == permissions.length) {
8555                    pi.requestedPermissions = permissions;
8556                } else {
8557                    pi.requestedPermissions = new String[numMatch];
8558                    numMatch = 0;
8559                    for (int i=0; i<permissions.length; i++) {
8560                        if (tmp[i]) {
8561                            pi.requestedPermissions[numMatch] = permissions[i];
8562                            numMatch++;
8563                        }
8564                    }
8565                }
8566            }
8567            list.add(pi);
8568        }
8569    }
8570
8571    @Override
8572    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8573            String[] permissions, int flags, int userId) {
8574        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8575        flags = updateFlagsForPackage(flags, userId, permissions);
8576        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8577                true /* requireFullPermission */, false /* checkShell */,
8578                "get packages holding permissions");
8579        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8580
8581        // writer
8582        synchronized (mPackages) {
8583            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8584            boolean[] tmpBools = new boolean[permissions.length];
8585            if (listUninstalled) {
8586                for (PackageSetting ps : mSettings.mPackages.values()) {
8587                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8588                            userId);
8589                }
8590            } else {
8591                for (PackageParser.Package pkg : mPackages.values()) {
8592                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8593                    if (ps != null) {
8594                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8595                                userId);
8596                    }
8597                }
8598            }
8599
8600            return new ParceledListSlice<PackageInfo>(list);
8601        }
8602    }
8603
8604    @Override
8605    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8606        final int callingUid = Binder.getCallingUid();
8607        if (getInstantAppPackageName(callingUid) != null) {
8608            return ParceledListSlice.emptyList();
8609        }
8610        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8611        flags = updateFlagsForApplication(flags, userId, null);
8612        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8613
8614        // writer
8615        synchronized (mPackages) {
8616            ArrayList<ApplicationInfo> list;
8617            if (listUninstalled) {
8618                list = new ArrayList<>(mSettings.mPackages.size());
8619                for (PackageSetting ps : mSettings.mPackages.values()) {
8620                    ApplicationInfo ai;
8621                    int effectiveFlags = flags;
8622                    if (ps.isSystem()) {
8623                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8624                    }
8625                    if (ps.pkg != null) {
8626                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8627                            continue;
8628                        }
8629                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8630                            continue;
8631                        }
8632                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8633                                ps.readUserState(userId), userId);
8634                        if (ai != null) {
8635                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8636                        }
8637                    } else {
8638                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8639                        // and already converts to externally visible package name
8640                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8641                                callingUid, effectiveFlags, userId);
8642                    }
8643                    if (ai != null) {
8644                        list.add(ai);
8645                    }
8646                }
8647            } else {
8648                list = new ArrayList<>(mPackages.size());
8649                for (PackageParser.Package p : mPackages.values()) {
8650                    if (p.mExtras != null) {
8651                        PackageSetting ps = (PackageSetting) p.mExtras;
8652                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8653                            continue;
8654                        }
8655                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8656                            continue;
8657                        }
8658                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8659                                ps.readUserState(userId), userId);
8660                        if (ai != null) {
8661                            ai.packageName = resolveExternalPackageNameLPr(p);
8662                            list.add(ai);
8663                        }
8664                    }
8665                }
8666            }
8667
8668            return new ParceledListSlice<>(list);
8669        }
8670    }
8671
8672    @Override
8673    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8674        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8675            return null;
8676        }
8677        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8678            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8679                    "getEphemeralApplications");
8680        }
8681        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8682                true /* requireFullPermission */, false /* checkShell */,
8683                "getEphemeralApplications");
8684        synchronized (mPackages) {
8685            List<InstantAppInfo> instantApps = mInstantAppRegistry
8686                    .getInstantAppsLPr(userId);
8687            if (instantApps != null) {
8688                return new ParceledListSlice<>(instantApps);
8689            }
8690        }
8691        return null;
8692    }
8693
8694    @Override
8695    public boolean isInstantApp(String packageName, int userId) {
8696        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8697                true /* requireFullPermission */, false /* checkShell */,
8698                "isInstantApp");
8699        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8700            return false;
8701        }
8702
8703        synchronized (mPackages) {
8704            int callingUid = Binder.getCallingUid();
8705            if (Process.isIsolated(callingUid)) {
8706                callingUid = mIsolatedOwners.get(callingUid);
8707            }
8708            final PackageSetting ps = mSettings.mPackages.get(packageName);
8709            PackageParser.Package pkg = mPackages.get(packageName);
8710            final boolean returnAllowed =
8711                    ps != null
8712                    && (isCallerSameApp(packageName, callingUid)
8713                            || canViewInstantApps(callingUid, userId)
8714                            || mInstantAppRegistry.isInstantAccessGranted(
8715                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8716            if (returnAllowed) {
8717                return ps.getInstantApp(userId);
8718            }
8719        }
8720        return false;
8721    }
8722
8723    @Override
8724    public byte[] getInstantAppCookie(String packageName, int userId) {
8725        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8726            return null;
8727        }
8728
8729        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8730                true /* requireFullPermission */, false /* checkShell */,
8731                "getInstantAppCookie");
8732        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8733            return null;
8734        }
8735        synchronized (mPackages) {
8736            return mInstantAppRegistry.getInstantAppCookieLPw(
8737                    packageName, userId);
8738        }
8739    }
8740
8741    @Override
8742    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8743        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8744            return true;
8745        }
8746
8747        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8748                true /* requireFullPermission */, true /* checkShell */,
8749                "setInstantAppCookie");
8750        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8751            return false;
8752        }
8753        synchronized (mPackages) {
8754            return mInstantAppRegistry.setInstantAppCookieLPw(
8755                    packageName, cookie, userId);
8756        }
8757    }
8758
8759    @Override
8760    public Bitmap getInstantAppIcon(String packageName, int userId) {
8761        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8762            return null;
8763        }
8764
8765        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8766            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8767                    "getInstantAppIcon");
8768        }
8769        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8770                true /* requireFullPermission */, false /* checkShell */,
8771                "getInstantAppIcon");
8772
8773        synchronized (mPackages) {
8774            return mInstantAppRegistry.getInstantAppIconLPw(
8775                    packageName, userId);
8776        }
8777    }
8778
8779    private boolean isCallerSameApp(String packageName, int uid) {
8780        PackageParser.Package pkg = mPackages.get(packageName);
8781        return pkg != null
8782                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8783    }
8784
8785    @Override
8786    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8787        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8788            return ParceledListSlice.emptyList();
8789        }
8790        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8791    }
8792
8793    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8794        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8795
8796        // reader
8797        synchronized (mPackages) {
8798            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8799            final int userId = UserHandle.getCallingUserId();
8800            while (i.hasNext()) {
8801                final PackageParser.Package p = i.next();
8802                if (p.applicationInfo == null) continue;
8803
8804                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8805                        && !p.applicationInfo.isDirectBootAware();
8806                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8807                        && p.applicationInfo.isDirectBootAware();
8808
8809                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8810                        && (!mSafeMode || isSystemApp(p))
8811                        && (matchesUnaware || matchesAware)) {
8812                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8813                    if (ps != null) {
8814                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8815                                ps.readUserState(userId), userId);
8816                        if (ai != null) {
8817                            finalList.add(ai);
8818                        }
8819                    }
8820                }
8821            }
8822        }
8823
8824        return finalList;
8825    }
8826
8827    @Override
8828    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8829        if (!sUserManager.exists(userId)) return null;
8830        flags = updateFlagsForComponent(flags, userId, name);
8831        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8832        // reader
8833        synchronized (mPackages) {
8834            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8835            PackageSetting ps = provider != null
8836                    ? mSettings.mPackages.get(provider.owner.packageName)
8837                    : null;
8838            if (ps != null) {
8839                final boolean isInstantApp = ps.getInstantApp(userId);
8840                // normal application; filter out instant application provider
8841                if (instantAppPkgName == null && isInstantApp) {
8842                    return null;
8843                }
8844                // instant application; filter out other instant applications
8845                if (instantAppPkgName != null
8846                        && isInstantApp
8847                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8848                    return null;
8849                }
8850                // instant application; filter out non-exposed provider
8851                if (instantAppPkgName != null
8852                        && !isInstantApp
8853                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8854                    return null;
8855                }
8856                // provider not enabled
8857                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8858                    return null;
8859                }
8860                return PackageParser.generateProviderInfo(
8861                        provider, flags, ps.readUserState(userId), userId);
8862            }
8863            return null;
8864        }
8865    }
8866
8867    /**
8868     * @deprecated
8869     */
8870    @Deprecated
8871    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8872        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8873            return;
8874        }
8875        // reader
8876        synchronized (mPackages) {
8877            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8878                    .entrySet().iterator();
8879            final int userId = UserHandle.getCallingUserId();
8880            while (i.hasNext()) {
8881                Map.Entry<String, PackageParser.Provider> entry = i.next();
8882                PackageParser.Provider p = entry.getValue();
8883                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8884
8885                if (ps != null && p.syncable
8886                        && (!mSafeMode || (p.info.applicationInfo.flags
8887                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8888                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8889                            ps.readUserState(userId), userId);
8890                    if (info != null) {
8891                        outNames.add(entry.getKey());
8892                        outInfo.add(info);
8893                    }
8894                }
8895            }
8896        }
8897    }
8898
8899    @Override
8900    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8901            int uid, int flags, String metaDataKey) {
8902        final int callingUid = Binder.getCallingUid();
8903        final int userId = processName != null ? UserHandle.getUserId(uid)
8904                : UserHandle.getCallingUserId();
8905        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8906        flags = updateFlagsForComponent(flags, userId, processName);
8907        ArrayList<ProviderInfo> finalList = null;
8908        // reader
8909        synchronized (mPackages) {
8910            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8911            while (i.hasNext()) {
8912                final PackageParser.Provider p = i.next();
8913                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8914                if (ps != null && p.info.authority != null
8915                        && (processName == null
8916                                || (p.info.processName.equals(processName)
8917                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8918                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8919
8920                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8921                    // parameter.
8922                    if (metaDataKey != null
8923                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8924                        continue;
8925                    }
8926                    final ComponentName component =
8927                            new ComponentName(p.info.packageName, p.info.name);
8928                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8929                        continue;
8930                    }
8931                    if (finalList == null) {
8932                        finalList = new ArrayList<ProviderInfo>(3);
8933                    }
8934                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8935                            ps.readUserState(userId), userId);
8936                    if (info != null) {
8937                        finalList.add(info);
8938                    }
8939                }
8940            }
8941        }
8942
8943        if (finalList != null) {
8944            Collections.sort(finalList, mProviderInitOrderSorter);
8945            return new ParceledListSlice<ProviderInfo>(finalList);
8946        }
8947
8948        return ParceledListSlice.emptyList();
8949    }
8950
8951    @Override
8952    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8953        // reader
8954        synchronized (mPackages) {
8955            final int callingUid = Binder.getCallingUid();
8956            final int callingUserId = UserHandle.getUserId(callingUid);
8957            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8958            if (ps == null) return null;
8959            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8960                return null;
8961            }
8962            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8963            return PackageParser.generateInstrumentationInfo(i, flags);
8964        }
8965    }
8966
8967    @Override
8968    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8969            String targetPackage, int flags) {
8970        final int callingUid = Binder.getCallingUid();
8971        final int callingUserId = UserHandle.getUserId(callingUid);
8972        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8973        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8974            return ParceledListSlice.emptyList();
8975        }
8976        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8977    }
8978
8979    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8980            int flags) {
8981        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8982
8983        // reader
8984        synchronized (mPackages) {
8985            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8986            while (i.hasNext()) {
8987                final PackageParser.Instrumentation p = i.next();
8988                if (targetPackage == null
8989                        || targetPackage.equals(p.info.targetPackage)) {
8990                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8991                            flags);
8992                    if (ii != null) {
8993                        finalList.add(ii);
8994                    }
8995                }
8996            }
8997        }
8998
8999        return finalList;
9000    }
9001
9002    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9003        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9004        try {
9005            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9006        } finally {
9007            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9008        }
9009    }
9010
9011    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9012        final File[] files = dir.listFiles();
9013        if (ArrayUtils.isEmpty(files)) {
9014            Log.d(TAG, "No files in app dir " + dir);
9015            return;
9016        }
9017
9018        if (DEBUG_PACKAGE_SCANNING) {
9019            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9020                    + " flags=0x" + Integer.toHexString(parseFlags));
9021        }
9022        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9023                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9024                mParallelPackageParserCallback);
9025
9026        // Submit files for parsing in parallel
9027        int fileCount = 0;
9028        for (File file : files) {
9029            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9030                    && !PackageInstallerService.isStageName(file.getName());
9031            if (!isPackage) {
9032                // Ignore entries which are not packages
9033                continue;
9034            }
9035            parallelPackageParser.submit(file, parseFlags);
9036            fileCount++;
9037        }
9038
9039        // Process results one by one
9040        for (; fileCount > 0; fileCount--) {
9041            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9042            Throwable throwable = parseResult.throwable;
9043            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9044
9045            if (throwable == null) {
9046                // Static shared libraries have synthetic package names
9047                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9048                    renameStaticSharedLibraryPackage(parseResult.pkg);
9049                }
9050                try {
9051                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9052                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9053                                currentTime, null);
9054                    }
9055                } catch (PackageManagerException e) {
9056                    errorCode = e.error;
9057                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9058                }
9059            } else if (throwable instanceof PackageParser.PackageParserException) {
9060                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9061                        throwable;
9062                errorCode = e.error;
9063                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9064            } else {
9065                throw new IllegalStateException("Unexpected exception occurred while parsing "
9066                        + parseResult.scanFile, throwable);
9067            }
9068
9069            // Delete invalid userdata apps
9070            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9071                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9072                logCriticalInfo(Log.WARN,
9073                        "Deleting invalid package at " + parseResult.scanFile);
9074                removeCodePathLI(parseResult.scanFile);
9075            }
9076        }
9077        parallelPackageParser.close();
9078    }
9079
9080    private static File getSettingsProblemFile() {
9081        File dataDir = Environment.getDataDirectory();
9082        File systemDir = new File(dataDir, "system");
9083        File fname = new File(systemDir, "uiderrors.txt");
9084        return fname;
9085    }
9086
9087    static void reportSettingsProblem(int priority, String msg) {
9088        logCriticalInfo(priority, msg);
9089    }
9090
9091    public static void logCriticalInfo(int priority, String msg) {
9092        Slog.println(priority, TAG, msg);
9093        EventLogTags.writePmCriticalInfo(msg);
9094        try {
9095            File fname = getSettingsProblemFile();
9096            FileOutputStream out = new FileOutputStream(fname, true);
9097            PrintWriter pw = new FastPrintWriter(out);
9098            SimpleDateFormat formatter = new SimpleDateFormat();
9099            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9100            pw.println(dateString + ": " + msg);
9101            pw.close();
9102            FileUtils.setPermissions(
9103                    fname.toString(),
9104                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9105                    -1, -1);
9106        } catch (java.io.IOException e) {
9107        }
9108    }
9109
9110    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9111        if (srcFile.isDirectory()) {
9112            final File baseFile = new File(pkg.baseCodePath);
9113            long maxModifiedTime = baseFile.lastModified();
9114            if (pkg.splitCodePaths != null) {
9115                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9116                    final File splitFile = new File(pkg.splitCodePaths[i]);
9117                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9118                }
9119            }
9120            return maxModifiedTime;
9121        }
9122        return srcFile.lastModified();
9123    }
9124
9125    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9126            final int policyFlags) throws PackageManagerException {
9127        // When upgrading from pre-N MR1, verify the package time stamp using the package
9128        // directory and not the APK file.
9129        final long lastModifiedTime = mIsPreNMR1Upgrade
9130                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9131        if (ps != null
9132                && ps.codePath.equals(srcFile)
9133                && ps.timeStamp == lastModifiedTime
9134                && !isCompatSignatureUpdateNeeded(pkg)
9135                && !isRecoverSignatureUpdateNeeded(pkg)) {
9136            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9137            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9138            ArraySet<PublicKey> signingKs;
9139            synchronized (mPackages) {
9140                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9141            }
9142            if (ps.signatures.mSignatures != null
9143                    && ps.signatures.mSignatures.length != 0
9144                    && signingKs != null) {
9145                // Optimization: reuse the existing cached certificates
9146                // if the package appears to be unchanged.
9147                pkg.mSignatures = ps.signatures.mSignatures;
9148                pkg.mSigningKeys = signingKs;
9149                return;
9150            }
9151
9152            Slog.w(TAG, "PackageSetting for " + ps.name
9153                    + " is missing signatures.  Collecting certs again to recover them.");
9154        } else {
9155            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9156        }
9157
9158        try {
9159            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9160            PackageParser.collectCertificates(pkg, policyFlags);
9161        } catch (PackageParserException e) {
9162            throw PackageManagerException.from(e);
9163        } finally {
9164            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9165        }
9166    }
9167
9168    /**
9169     *  Traces a package scan.
9170     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9171     */
9172    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9173            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9174        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9175        try {
9176            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9177        } finally {
9178            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9179        }
9180    }
9181
9182    /**
9183     *  Scans a package and returns the newly parsed package.
9184     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9185     */
9186    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9187            long currentTime, UserHandle user) throws PackageManagerException {
9188        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9189        PackageParser pp = new PackageParser();
9190        pp.setSeparateProcesses(mSeparateProcesses);
9191        pp.setOnlyCoreApps(mOnlyCore);
9192        pp.setDisplayMetrics(mMetrics);
9193        pp.setCallback(mPackageParserCallback);
9194
9195        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9196            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9197        }
9198
9199        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9200        final PackageParser.Package pkg;
9201        try {
9202            pkg = pp.parsePackage(scanFile, parseFlags);
9203        } catch (PackageParserException e) {
9204            throw PackageManagerException.from(e);
9205        } finally {
9206            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9207        }
9208
9209        // Static shared libraries have synthetic package names
9210        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9211            renameStaticSharedLibraryPackage(pkg);
9212        }
9213
9214        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9215    }
9216
9217    /**
9218     *  Scans a package and returns the newly parsed package.
9219     *  @throws PackageManagerException on a parse error.
9220     */
9221    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9222            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9223            throws PackageManagerException {
9224        // If the package has children and this is the first dive in the function
9225        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9226        // packages (parent and children) would be successfully scanned before the
9227        // actual scan since scanning mutates internal state and we want to atomically
9228        // install the package and its children.
9229        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9230            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9231                scanFlags |= SCAN_CHECK_ONLY;
9232            }
9233        } else {
9234            scanFlags &= ~SCAN_CHECK_ONLY;
9235        }
9236
9237        // Scan the parent
9238        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9239                scanFlags, currentTime, user);
9240
9241        // Scan the children
9242        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9243        for (int i = 0; i < childCount; i++) {
9244            PackageParser.Package childPackage = pkg.childPackages.get(i);
9245            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9246                    currentTime, user);
9247        }
9248
9249
9250        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9251            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9252        }
9253
9254        return scannedPkg;
9255    }
9256
9257    /**
9258     *  Scans a package and returns the newly parsed package.
9259     *  @throws PackageManagerException on a parse error.
9260     */
9261    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9262            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9263            throws PackageManagerException {
9264        PackageSetting ps = null;
9265        PackageSetting updatedPkg;
9266        // reader
9267        synchronized (mPackages) {
9268            // Look to see if we already know about this package.
9269            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9270            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9271                // This package has been renamed to its original name.  Let's
9272                // use that.
9273                ps = mSettings.getPackageLPr(oldName);
9274            }
9275            // If there was no original package, see one for the real package name.
9276            if (ps == null) {
9277                ps = mSettings.getPackageLPr(pkg.packageName);
9278            }
9279            // Check to see if this package could be hiding/updating a system
9280            // package.  Must look for it either under the original or real
9281            // package name depending on our state.
9282            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9283            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9284
9285            // If this is a package we don't know about on the system partition, we
9286            // may need to remove disabled child packages on the system partition
9287            // or may need to not add child packages if the parent apk is updated
9288            // on the data partition and no longer defines this child package.
9289            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9290                // If this is a parent package for an updated system app and this system
9291                // app got an OTA update which no longer defines some of the child packages
9292                // we have to prune them from the disabled system packages.
9293                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9294                if (disabledPs != null) {
9295                    final int scannedChildCount = (pkg.childPackages != null)
9296                            ? pkg.childPackages.size() : 0;
9297                    final int disabledChildCount = disabledPs.childPackageNames != null
9298                            ? disabledPs.childPackageNames.size() : 0;
9299                    for (int i = 0; i < disabledChildCount; i++) {
9300                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9301                        boolean disabledPackageAvailable = false;
9302                        for (int j = 0; j < scannedChildCount; j++) {
9303                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9304                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9305                                disabledPackageAvailable = true;
9306                                break;
9307                            }
9308                         }
9309                         if (!disabledPackageAvailable) {
9310                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9311                         }
9312                    }
9313                }
9314            }
9315        }
9316
9317        final boolean isUpdatedPkg = updatedPkg != null;
9318        final boolean isUpdatedSystemPkg = isUpdatedPkg
9319                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9320        boolean isUpdatedPkgBetter = false;
9321        // First check if this is a system package that may involve an update
9322        if (isUpdatedSystemPkg) {
9323            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9324            // it needs to drop FLAG_PRIVILEGED.
9325            if (locationIsPrivileged(scanFile)) {
9326                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9327            } else {
9328                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9329            }
9330            // If new package is not located in "/oem" (e.g. due to an OTA),
9331            // it needs to drop FLAG_OEM.
9332            if (locationIsOem(scanFile)) {
9333                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
9334            } else {
9335                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
9336            }
9337
9338            if (ps != null && !ps.codePath.equals(scanFile)) {
9339                // The path has changed from what was last scanned...  check the
9340                // version of the new path against what we have stored to determine
9341                // what to do.
9342                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9343                if (pkg.mVersionCode <= ps.versionCode) {
9344                    // The system package has been updated and the code path does not match
9345                    // Ignore entry. Skip it.
9346                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9347                            + " ignored: updated version " + ps.versionCode
9348                            + " better than this " + pkg.mVersionCode);
9349                    if (!updatedPkg.codePath.equals(scanFile)) {
9350                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9351                                + ps.name + " changing from " + updatedPkg.codePathString
9352                                + " to " + scanFile);
9353                        updatedPkg.codePath = scanFile;
9354                        updatedPkg.codePathString = scanFile.toString();
9355                        updatedPkg.resourcePath = scanFile;
9356                        updatedPkg.resourcePathString = scanFile.toString();
9357                    }
9358                    updatedPkg.pkg = pkg;
9359                    updatedPkg.versionCode = pkg.mVersionCode;
9360
9361                    // Update the disabled system child packages to point to the package too.
9362                    final int childCount = updatedPkg.childPackageNames != null
9363                            ? updatedPkg.childPackageNames.size() : 0;
9364                    for (int i = 0; i < childCount; i++) {
9365                        String childPackageName = updatedPkg.childPackageNames.get(i);
9366                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9367                                childPackageName);
9368                        if (updatedChildPkg != null) {
9369                            updatedChildPkg.pkg = pkg;
9370                            updatedChildPkg.versionCode = pkg.mVersionCode;
9371                        }
9372                    }
9373                } else {
9374                    // The current app on the system partition is better than
9375                    // what we have updated to on the data partition; switch
9376                    // back to the system partition version.
9377                    // At this point, its safely assumed that package installation for
9378                    // apps in system partition will go through. If not there won't be a working
9379                    // version of the app
9380                    // writer
9381                    synchronized (mPackages) {
9382                        // Just remove the loaded entries from package lists.
9383                        mPackages.remove(ps.name);
9384                    }
9385
9386                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9387                            + " reverting from " + ps.codePathString
9388                            + ": new version " + pkg.mVersionCode
9389                            + " better than installed " + ps.versionCode);
9390
9391                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9392                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9393                    synchronized (mInstallLock) {
9394                        args.cleanUpResourcesLI();
9395                    }
9396                    synchronized (mPackages) {
9397                        mSettings.enableSystemPackageLPw(ps.name);
9398                    }
9399                    isUpdatedPkgBetter = true;
9400                }
9401            }
9402        }
9403
9404        String resourcePath = null;
9405        String baseResourcePath = null;
9406        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9407            if (ps != null && ps.resourcePathString != null) {
9408                resourcePath = ps.resourcePathString;
9409                baseResourcePath = ps.resourcePathString;
9410            } else {
9411                // Should not happen at all. Just log an error.
9412                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9413            }
9414        } else {
9415            resourcePath = pkg.codePath;
9416            baseResourcePath = pkg.baseCodePath;
9417        }
9418
9419        // Set application objects path explicitly.
9420        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9421        pkg.setApplicationInfoCodePath(pkg.codePath);
9422        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9423        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9424        pkg.setApplicationInfoResourcePath(resourcePath);
9425        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9426        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9427
9428        // throw an exception if we have an update to a system application, but, it's not more
9429        // recent than the package we've already scanned
9430        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9431            // Set CPU Abis to application info.
9432            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9433                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9434                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9435            } else {
9436                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9437                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9438            }
9439
9440            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9441                    + scanFile + " ignored: updated version " + ps.versionCode
9442                    + " better than this " + pkg.mVersionCode);
9443        }
9444
9445        if (isUpdatedPkg) {
9446            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9447            // initially
9448            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9449
9450            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9451            // flag set initially
9452            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9453                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9454            }
9455
9456            // An updated OEM app will not have the PARSE_IS_OEM
9457            // flag set initially
9458            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9459                policyFlags |= PackageParser.PARSE_IS_OEM;
9460            }
9461        }
9462
9463        // Verify certificates against what was last scanned
9464        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9465
9466        /*
9467         * A new system app appeared, but we already had a non-system one of the
9468         * same name installed earlier.
9469         */
9470        boolean shouldHideSystemApp = false;
9471        if (!isUpdatedPkg && ps != null
9472                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9473            /*
9474             * Check to make sure the signatures match first. If they don't,
9475             * wipe the installed application and its data.
9476             */
9477            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9478                    != PackageManager.SIGNATURE_MATCH) {
9479                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9480                        + " signatures don't match existing userdata copy; removing");
9481                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9482                        "scanPackageInternalLI")) {
9483                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9484                }
9485                ps = null;
9486            } else {
9487                /*
9488                 * If the newly-added system app is an older version than the
9489                 * already installed version, hide it. It will be scanned later
9490                 * and re-added like an update.
9491                 */
9492                if (pkg.mVersionCode <= ps.versionCode) {
9493                    shouldHideSystemApp = true;
9494                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9495                            + " but new version " + pkg.mVersionCode + " better than installed "
9496                            + ps.versionCode + "; hiding system");
9497                } else {
9498                    /*
9499                     * The newly found system app is a newer version that the
9500                     * one previously installed. Simply remove the
9501                     * already-installed application and replace it with our own
9502                     * while keeping the application data.
9503                     */
9504                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9505                            + " reverting from " + ps.codePathString + ": new version "
9506                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9507                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9508                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9509                    synchronized (mInstallLock) {
9510                        args.cleanUpResourcesLI();
9511                    }
9512                }
9513            }
9514        }
9515
9516        // The apk is forward locked (not public) if its code and resources
9517        // are kept in different files. (except for app in either system or
9518        // vendor path).
9519        // TODO grab this value from PackageSettings
9520        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9521            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9522                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9523            }
9524        }
9525
9526        final int userId = ((user == null) ? 0 : user.getIdentifier());
9527        if (ps != null && ps.getInstantApp(userId)) {
9528            scanFlags |= SCAN_AS_INSTANT_APP;
9529        }
9530        if (ps != null && ps.getVirtulalPreload(userId)) {
9531            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9532        }
9533
9534        // Note that we invoke the following method only if we are about to unpack an application
9535        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9536                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9537
9538        /*
9539         * If the system app should be overridden by a previously installed
9540         * data, hide the system app now and let the /data/app scan pick it up
9541         * again.
9542         */
9543        if (shouldHideSystemApp) {
9544            synchronized (mPackages) {
9545                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9546            }
9547        }
9548
9549        return scannedPkg;
9550    }
9551
9552    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9553        // Derive the new package synthetic package name
9554        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9555                + pkg.staticSharedLibVersion);
9556    }
9557
9558    private static String fixProcessName(String defProcessName,
9559            String processName) {
9560        if (processName == null) {
9561            return defProcessName;
9562        }
9563        return processName;
9564    }
9565
9566    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9567            throws PackageManagerException {
9568        if (pkgSetting.signatures.mSignatures != null) {
9569            // Already existing package. Make sure signatures match
9570            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9571                    == PackageManager.SIGNATURE_MATCH;
9572            if (!match) {
9573                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9574                        == PackageManager.SIGNATURE_MATCH;
9575            }
9576            if (!match) {
9577                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9578                        == PackageManager.SIGNATURE_MATCH;
9579            }
9580            if (!match) {
9581                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9582                        + pkg.packageName + " signatures do not match the "
9583                        + "previously installed version; ignoring!");
9584            }
9585        }
9586
9587        // Check for shared user signatures
9588        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9589            // Already existing package. Make sure signatures match
9590            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9591                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9592            if (!match) {
9593                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9594                        == PackageManager.SIGNATURE_MATCH;
9595            }
9596            if (!match) {
9597                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9598                        == PackageManager.SIGNATURE_MATCH;
9599            }
9600            if (!match) {
9601                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9602                        "Package " + pkg.packageName
9603                        + " has no signatures that match those in shared user "
9604                        + pkgSetting.sharedUser.name + "; ignoring!");
9605            }
9606        }
9607    }
9608
9609    /**
9610     * Enforces that only the system UID or root's UID can call a method exposed
9611     * via Binder.
9612     *
9613     * @param message used as message if SecurityException is thrown
9614     * @throws SecurityException if the caller is not system or root
9615     */
9616    private static final void enforceSystemOrRoot(String message) {
9617        final int uid = Binder.getCallingUid();
9618        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9619            throw new SecurityException(message);
9620        }
9621    }
9622
9623    @Override
9624    public void performFstrimIfNeeded() {
9625        enforceSystemOrRoot("Only the system can request fstrim");
9626
9627        // Before everything else, see whether we need to fstrim.
9628        try {
9629            IStorageManager sm = PackageHelper.getStorageManager();
9630            if (sm != null) {
9631                boolean doTrim = false;
9632                final long interval = android.provider.Settings.Global.getLong(
9633                        mContext.getContentResolver(),
9634                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9635                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9636                if (interval > 0) {
9637                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9638                    if (timeSinceLast > interval) {
9639                        doTrim = true;
9640                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9641                                + "; running immediately");
9642                    }
9643                }
9644                if (doTrim) {
9645                    final boolean dexOptDialogShown;
9646                    synchronized (mPackages) {
9647                        dexOptDialogShown = mDexOptDialogShown;
9648                    }
9649                    if (!isFirstBoot() && dexOptDialogShown) {
9650                        try {
9651                            ActivityManager.getService().showBootMessage(
9652                                    mContext.getResources().getString(
9653                                            R.string.android_upgrading_fstrim), true);
9654                        } catch (RemoteException e) {
9655                        }
9656                    }
9657                    sm.runMaintenance();
9658                }
9659            } else {
9660                Slog.e(TAG, "storageManager service unavailable!");
9661            }
9662        } catch (RemoteException e) {
9663            // Can't happen; StorageManagerService is local
9664        }
9665    }
9666
9667    @Override
9668    public void updatePackagesIfNeeded() {
9669        enforceSystemOrRoot("Only the system can request package update");
9670
9671        // We need to re-extract after an OTA.
9672        boolean causeUpgrade = isUpgrade();
9673
9674        // First boot or factory reset.
9675        // Note: we also handle devices that are upgrading to N right now as if it is their
9676        //       first boot, as they do not have profile data.
9677        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9678
9679        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9680        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9681
9682        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9683            return;
9684        }
9685
9686        List<PackageParser.Package> pkgs;
9687        synchronized (mPackages) {
9688            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9689        }
9690
9691        final long startTime = System.nanoTime();
9692        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9693                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9694                    false /* bootComplete */);
9695
9696        final int elapsedTimeSeconds =
9697                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9698
9699        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9700        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9701        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9702        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9703        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9704    }
9705
9706    /*
9707     * Return the prebuilt profile path given a package base code path.
9708     */
9709    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9710        return pkg.baseCodePath + ".prof";
9711    }
9712
9713    /**
9714     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9715     * containing statistics about the invocation. The array consists of three elements,
9716     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9717     * and {@code numberOfPackagesFailed}.
9718     */
9719    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9720            final String compilerFilter, boolean bootComplete) {
9721
9722        int numberOfPackagesVisited = 0;
9723        int numberOfPackagesOptimized = 0;
9724        int numberOfPackagesSkipped = 0;
9725        int numberOfPackagesFailed = 0;
9726        final int numberOfPackagesToDexopt = pkgs.size();
9727
9728        for (PackageParser.Package pkg : pkgs) {
9729            numberOfPackagesVisited++;
9730
9731            boolean useProfileForDexopt = false;
9732
9733            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9734                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9735                // that are already compiled.
9736                File profileFile = new File(getPrebuildProfilePath(pkg));
9737                // Copy profile if it exists.
9738                if (profileFile.exists()) {
9739                    try {
9740                        // We could also do this lazily before calling dexopt in
9741                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9742                        // is that we don't have a good way to say "do this only once".
9743                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9744                                pkg.applicationInfo.uid, pkg.packageName)) {
9745                            Log.e(TAG, "Installer failed to copy system profile!");
9746                        } else {
9747                            // Disabled as this causes speed-profile compilation during first boot
9748                            // even if things are already compiled.
9749                            // useProfileForDexopt = true;
9750                        }
9751                    } catch (Exception e) {
9752                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9753                                e);
9754                    }
9755                } else {
9756                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9757                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9758                    // minimize the number off apps being speed-profile compiled during first boot.
9759                    // The other paths will not change the filter.
9760                    if (disabledPs != null && disabledPs.pkg.isStub) {
9761                        // The package is the stub one, remove the stub suffix to get the normal
9762                        // package and APK names.
9763                        String systemProfilePath =
9764                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9765                        File systemProfile = new File(systemProfilePath);
9766                        // Use the profile for compilation if there exists one for the same package
9767                        // in the system partition.
9768                        useProfileForDexopt = systemProfile.exists();
9769                    }
9770                }
9771            }
9772
9773            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9774                if (DEBUG_DEXOPT) {
9775                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9776                }
9777                numberOfPackagesSkipped++;
9778                continue;
9779            }
9780
9781            if (DEBUG_DEXOPT) {
9782                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9783                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9784            }
9785
9786            if (showDialog) {
9787                try {
9788                    ActivityManager.getService().showBootMessage(
9789                            mContext.getResources().getString(R.string.android_upgrading_apk,
9790                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9791                } catch (RemoteException e) {
9792                }
9793                synchronized (mPackages) {
9794                    mDexOptDialogShown = true;
9795                }
9796            }
9797
9798            String pkgCompilerFilter = compilerFilter;
9799            if (useProfileForDexopt) {
9800                // Use background dexopt mode to try and use the profile. Note that this does not
9801                // guarantee usage of the profile.
9802                pkgCompilerFilter =
9803                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9804                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9805            }
9806
9807            // checkProfiles is false to avoid merging profiles during boot which
9808            // might interfere with background compilation (b/28612421).
9809            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9810            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9811            // trade-off worth doing to save boot time work.
9812            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9813            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9814                    pkg.packageName,
9815                    pkgCompilerFilter,
9816                    dexoptFlags));
9817
9818            switch (primaryDexOptStaus) {
9819                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9820                    numberOfPackagesOptimized++;
9821                    break;
9822                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9823                    numberOfPackagesSkipped++;
9824                    break;
9825                case PackageDexOptimizer.DEX_OPT_FAILED:
9826                    numberOfPackagesFailed++;
9827                    break;
9828                default:
9829                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9830                    break;
9831            }
9832        }
9833
9834        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9835                numberOfPackagesFailed };
9836    }
9837
9838    @Override
9839    public void notifyPackageUse(String packageName, int reason) {
9840        synchronized (mPackages) {
9841            final int callingUid = Binder.getCallingUid();
9842            final int callingUserId = UserHandle.getUserId(callingUid);
9843            if (getInstantAppPackageName(callingUid) != null) {
9844                if (!isCallerSameApp(packageName, callingUid)) {
9845                    return;
9846                }
9847            } else {
9848                if (isInstantApp(packageName, callingUserId)) {
9849                    return;
9850                }
9851            }
9852            notifyPackageUseLocked(packageName, reason);
9853        }
9854    }
9855
9856    private void notifyPackageUseLocked(String packageName, int reason) {
9857        final PackageParser.Package p = mPackages.get(packageName);
9858        if (p == null) {
9859            return;
9860        }
9861        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9862    }
9863
9864    @Override
9865    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9866            List<String> classPaths, String loaderIsa) {
9867        int userId = UserHandle.getCallingUserId();
9868        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9869        if (ai == null) {
9870            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9871                + loadingPackageName + ", user=" + userId);
9872            return;
9873        }
9874        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9875    }
9876
9877    @Override
9878    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9879            IDexModuleRegisterCallback callback) {
9880        int userId = UserHandle.getCallingUserId();
9881        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9882        DexManager.RegisterDexModuleResult result;
9883        if (ai == null) {
9884            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9885                     " calling user. package=" + packageName + ", user=" + userId);
9886            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9887        } else {
9888            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9889        }
9890
9891        if (callback != null) {
9892            mHandler.post(() -> {
9893                try {
9894                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9895                } catch (RemoteException e) {
9896                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9897                }
9898            });
9899        }
9900    }
9901
9902    /**
9903     * Ask the package manager to perform a dex-opt with the given compiler filter.
9904     *
9905     * Note: exposed only for the shell command to allow moving packages explicitly to a
9906     *       definite state.
9907     */
9908    @Override
9909    public boolean performDexOptMode(String packageName,
9910            boolean checkProfiles, String targetCompilerFilter, boolean force,
9911            boolean bootComplete, String splitName) {
9912        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9913                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9914                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9915        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9916                splitName, flags));
9917    }
9918
9919    /**
9920     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9921     * secondary dex files belonging to the given package.
9922     *
9923     * Note: exposed only for the shell command to allow moving packages explicitly to a
9924     *       definite state.
9925     */
9926    @Override
9927    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9928            boolean force) {
9929        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9930                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9931                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9932                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9933        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9934    }
9935
9936    /*package*/ boolean performDexOpt(DexoptOptions options) {
9937        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9938            return false;
9939        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9940            return false;
9941        }
9942
9943        if (options.isDexoptOnlySecondaryDex()) {
9944            return mDexManager.dexoptSecondaryDex(options);
9945        } else {
9946            int dexoptStatus = performDexOptWithStatus(options);
9947            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9948        }
9949    }
9950
9951    /**
9952     * Perform dexopt on the given package and return one of following result:
9953     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9954     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9955     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9956     */
9957    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9958        return performDexOptTraced(options);
9959    }
9960
9961    private int performDexOptTraced(DexoptOptions options) {
9962        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9963        try {
9964            return performDexOptInternal(options);
9965        } finally {
9966            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9967        }
9968    }
9969
9970    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9971    // if the package can now be considered up to date for the given filter.
9972    private int performDexOptInternal(DexoptOptions options) {
9973        PackageParser.Package p;
9974        synchronized (mPackages) {
9975            p = mPackages.get(options.getPackageName());
9976            if (p == null) {
9977                // Package could not be found. Report failure.
9978                return PackageDexOptimizer.DEX_OPT_FAILED;
9979            }
9980            mPackageUsage.maybeWriteAsync(mPackages);
9981            mCompilerStats.maybeWriteAsync();
9982        }
9983        long callingId = Binder.clearCallingIdentity();
9984        try {
9985            synchronized (mInstallLock) {
9986                return performDexOptInternalWithDependenciesLI(p, options);
9987            }
9988        } finally {
9989            Binder.restoreCallingIdentity(callingId);
9990        }
9991    }
9992
9993    public ArraySet<String> getOptimizablePackages() {
9994        ArraySet<String> pkgs = new ArraySet<String>();
9995        synchronized (mPackages) {
9996            for (PackageParser.Package p : mPackages.values()) {
9997                if (PackageDexOptimizer.canOptimizePackage(p)) {
9998                    pkgs.add(p.packageName);
9999                }
10000            }
10001        }
10002        return pkgs;
10003    }
10004
10005    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10006            DexoptOptions options) {
10007        // Select the dex optimizer based on the force parameter.
10008        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10009        //       allocate an object here.
10010        PackageDexOptimizer pdo = options.isForce()
10011                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10012                : mPackageDexOptimizer;
10013
10014        // Dexopt all dependencies first. Note: we ignore the return value and march on
10015        // on errors.
10016        // Note that we are going to call performDexOpt on those libraries as many times as
10017        // they are referenced in packages. When we do a batch of performDexOpt (for example
10018        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10019        // and the first package that uses the library will dexopt it. The
10020        // others will see that the compiled code for the library is up to date.
10021        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10022        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10023        if (!deps.isEmpty()) {
10024            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10025                    options.getCompilerFilter(), options.getSplitName(),
10026                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10027            for (PackageParser.Package depPackage : deps) {
10028                // TODO: Analyze and investigate if we (should) profile libraries.
10029                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10030                        getOrCreateCompilerPackageStats(depPackage),
10031                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10032            }
10033        }
10034        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10035                getOrCreateCompilerPackageStats(p),
10036                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10037    }
10038
10039    /**
10040     * Reconcile the information we have about the secondary dex files belonging to
10041     * {@code packagName} and the actual dex files. For all dex files that were
10042     * deleted, update the internal records and delete the generated oat files.
10043     */
10044    @Override
10045    public void reconcileSecondaryDexFiles(String packageName) {
10046        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10047            return;
10048        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10049            return;
10050        }
10051        mDexManager.reconcileSecondaryDexFiles(packageName);
10052    }
10053
10054    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10055    // a reference there.
10056    /*package*/ DexManager getDexManager() {
10057        return mDexManager;
10058    }
10059
10060    /**
10061     * Execute the background dexopt job immediately.
10062     */
10063    @Override
10064    public boolean runBackgroundDexoptJob() {
10065        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10066            return false;
10067        }
10068        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10069    }
10070
10071    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10072        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10073                || p.usesStaticLibraries != null) {
10074            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10075            Set<String> collectedNames = new HashSet<>();
10076            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10077
10078            retValue.remove(p);
10079
10080            return retValue;
10081        } else {
10082            return Collections.emptyList();
10083        }
10084    }
10085
10086    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10087            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10088        if (!collectedNames.contains(p.packageName)) {
10089            collectedNames.add(p.packageName);
10090            collected.add(p);
10091
10092            if (p.usesLibraries != null) {
10093                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10094                        null, collected, collectedNames);
10095            }
10096            if (p.usesOptionalLibraries != null) {
10097                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10098                        null, collected, collectedNames);
10099            }
10100            if (p.usesStaticLibraries != null) {
10101                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10102                        p.usesStaticLibrariesVersions, collected, collectedNames);
10103            }
10104        }
10105    }
10106
10107    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10108            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10109        final int libNameCount = libs.size();
10110        for (int i = 0; i < libNameCount; i++) {
10111            String libName = libs.get(i);
10112            int version = (versions != null && versions.length == libNameCount)
10113                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10114            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10115            if (libPkg != null) {
10116                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10117            }
10118        }
10119    }
10120
10121    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10122        synchronized (mPackages) {
10123            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10124            if (libEntry != null) {
10125                return mPackages.get(libEntry.apk);
10126            }
10127            return null;
10128        }
10129    }
10130
10131    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10132        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10133        if (versionedLib == null) {
10134            return null;
10135        }
10136        return versionedLib.get(version);
10137    }
10138
10139    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10140        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10141                pkg.staticSharedLibName);
10142        if (versionedLib == null) {
10143            return null;
10144        }
10145        int previousLibVersion = -1;
10146        final int versionCount = versionedLib.size();
10147        for (int i = 0; i < versionCount; i++) {
10148            final int libVersion = versionedLib.keyAt(i);
10149            if (libVersion < pkg.staticSharedLibVersion) {
10150                previousLibVersion = Math.max(previousLibVersion, libVersion);
10151            }
10152        }
10153        if (previousLibVersion >= 0) {
10154            return versionedLib.get(previousLibVersion);
10155        }
10156        return null;
10157    }
10158
10159    public void shutdown() {
10160        mPackageUsage.writeNow(mPackages);
10161        mCompilerStats.writeNow();
10162        mDexManager.writePackageDexUsageNow();
10163    }
10164
10165    @Override
10166    public void dumpProfiles(String packageName) {
10167        PackageParser.Package pkg;
10168        synchronized (mPackages) {
10169            pkg = mPackages.get(packageName);
10170            if (pkg == null) {
10171                throw new IllegalArgumentException("Unknown package: " + packageName);
10172            }
10173        }
10174        /* Only the shell, root, or the app user should be able to dump profiles. */
10175        int callingUid = Binder.getCallingUid();
10176        if (callingUid != Process.SHELL_UID &&
10177            callingUid != Process.ROOT_UID &&
10178            callingUid != pkg.applicationInfo.uid) {
10179            throw new SecurityException("dumpProfiles");
10180        }
10181
10182        synchronized (mInstallLock) {
10183            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10184            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10185            try {
10186                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10187                String codePaths = TextUtils.join(";", allCodePaths);
10188                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10189            } catch (InstallerException e) {
10190                Slog.w(TAG, "Failed to dump profiles", e);
10191            }
10192            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10193        }
10194    }
10195
10196    @Override
10197    public void forceDexOpt(String packageName) {
10198        enforceSystemOrRoot("forceDexOpt");
10199
10200        PackageParser.Package pkg;
10201        synchronized (mPackages) {
10202            pkg = mPackages.get(packageName);
10203            if (pkg == null) {
10204                throw new IllegalArgumentException("Unknown package: " + packageName);
10205            }
10206        }
10207
10208        synchronized (mInstallLock) {
10209            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10210
10211            // Whoever is calling forceDexOpt wants a compiled package.
10212            // Don't use profiles since that may cause compilation to be skipped.
10213            final int res = performDexOptInternalWithDependenciesLI(
10214                    pkg,
10215                    new DexoptOptions(packageName,
10216                            getDefaultCompilerFilter(),
10217                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10218
10219            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10220            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10221                throw new IllegalStateException("Failed to dexopt: " + res);
10222            }
10223        }
10224    }
10225
10226    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10227        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10228            Slog.w(TAG, "Unable to update from " + oldPkg.name
10229                    + " to " + newPkg.packageName
10230                    + ": old package not in system partition");
10231            return false;
10232        } else if (mPackages.get(oldPkg.name) != null) {
10233            Slog.w(TAG, "Unable to update from " + oldPkg.name
10234                    + " to " + newPkg.packageName
10235                    + ": old package still exists");
10236            return false;
10237        }
10238        return true;
10239    }
10240
10241    void removeCodePathLI(File codePath) {
10242        if (codePath.isDirectory()) {
10243            try {
10244                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10245            } catch (InstallerException e) {
10246                Slog.w(TAG, "Failed to remove code path", e);
10247            }
10248        } else {
10249            codePath.delete();
10250        }
10251    }
10252
10253    private int[] resolveUserIds(int userId) {
10254        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10255    }
10256
10257    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10258        if (pkg == null) {
10259            Slog.wtf(TAG, "Package was null!", new Throwable());
10260            return;
10261        }
10262        clearAppDataLeafLIF(pkg, userId, flags);
10263        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10264        for (int i = 0; i < childCount; i++) {
10265            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10266        }
10267    }
10268
10269    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10270        final PackageSetting ps;
10271        synchronized (mPackages) {
10272            ps = mSettings.mPackages.get(pkg.packageName);
10273        }
10274        for (int realUserId : resolveUserIds(userId)) {
10275            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10276            try {
10277                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10278                        ceDataInode);
10279            } catch (InstallerException e) {
10280                Slog.w(TAG, String.valueOf(e));
10281            }
10282        }
10283    }
10284
10285    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10286        if (pkg == null) {
10287            Slog.wtf(TAG, "Package was null!", new Throwable());
10288            return;
10289        }
10290        destroyAppDataLeafLIF(pkg, userId, flags);
10291        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10292        for (int i = 0; i < childCount; i++) {
10293            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10294        }
10295    }
10296
10297    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10298        final PackageSetting ps;
10299        synchronized (mPackages) {
10300            ps = mSettings.mPackages.get(pkg.packageName);
10301        }
10302        for (int realUserId : resolveUserIds(userId)) {
10303            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10304            try {
10305                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10306                        ceDataInode);
10307            } catch (InstallerException e) {
10308                Slog.w(TAG, String.valueOf(e));
10309            }
10310            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10311        }
10312    }
10313
10314    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10315        if (pkg == null) {
10316            Slog.wtf(TAG, "Package was null!", new Throwable());
10317            return;
10318        }
10319        destroyAppProfilesLeafLIF(pkg);
10320        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10321        for (int i = 0; i < childCount; i++) {
10322            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10323        }
10324    }
10325
10326    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10327        try {
10328            mInstaller.destroyAppProfiles(pkg.packageName);
10329        } catch (InstallerException e) {
10330            Slog.w(TAG, String.valueOf(e));
10331        }
10332    }
10333
10334    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10335        if (pkg == null) {
10336            Slog.wtf(TAG, "Package was null!", new Throwable());
10337            return;
10338        }
10339        clearAppProfilesLeafLIF(pkg);
10340        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10341        for (int i = 0; i < childCount; i++) {
10342            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10343        }
10344    }
10345
10346    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10347        try {
10348            mInstaller.clearAppProfiles(pkg.packageName);
10349        } catch (InstallerException e) {
10350            Slog.w(TAG, String.valueOf(e));
10351        }
10352    }
10353
10354    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10355            long lastUpdateTime) {
10356        // Set parent install/update time
10357        PackageSetting ps = (PackageSetting) pkg.mExtras;
10358        if (ps != null) {
10359            ps.firstInstallTime = firstInstallTime;
10360            ps.lastUpdateTime = lastUpdateTime;
10361        }
10362        // Set children install/update time
10363        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10364        for (int i = 0; i < childCount; i++) {
10365            PackageParser.Package childPkg = pkg.childPackages.get(i);
10366            ps = (PackageSetting) childPkg.mExtras;
10367            if (ps != null) {
10368                ps.firstInstallTime = firstInstallTime;
10369                ps.lastUpdateTime = lastUpdateTime;
10370            }
10371        }
10372    }
10373
10374    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10375            PackageParser.Package changingLib) {
10376        if (file.path != null) {
10377            usesLibraryFiles.add(file.path);
10378            return;
10379        }
10380        PackageParser.Package p = mPackages.get(file.apk);
10381        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10382            // If we are doing this while in the middle of updating a library apk,
10383            // then we need to make sure to use that new apk for determining the
10384            // dependencies here.  (We haven't yet finished committing the new apk
10385            // to the package manager state.)
10386            if (p == null || p.packageName.equals(changingLib.packageName)) {
10387                p = changingLib;
10388            }
10389        }
10390        if (p != null) {
10391            usesLibraryFiles.addAll(p.getAllCodePaths());
10392            if (p.usesLibraryFiles != null) {
10393                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10394            }
10395        }
10396    }
10397
10398    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10399            PackageParser.Package changingLib) throws PackageManagerException {
10400        if (pkg == null) {
10401            return;
10402        }
10403        ArraySet<String> usesLibraryFiles = null;
10404        if (pkg.usesLibraries != null) {
10405            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10406                    null, null, pkg.packageName, changingLib, true,
10407                    pkg.applicationInfo.targetSdkVersion, null);
10408        }
10409        if (pkg.usesStaticLibraries != null) {
10410            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10411                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10412                    pkg.packageName, changingLib, true,
10413                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10414        }
10415        if (pkg.usesOptionalLibraries != null) {
10416            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10417                    null, null, pkg.packageName, changingLib, false,
10418                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10419        }
10420        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10421            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10422        } else {
10423            pkg.usesLibraryFiles = null;
10424        }
10425    }
10426
10427    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10428            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10429            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10430            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10431            throws PackageManagerException {
10432        final int libCount = requestedLibraries.size();
10433        for (int i = 0; i < libCount; i++) {
10434            final String libName = requestedLibraries.get(i);
10435            final int libVersion = requiredVersions != null ? requiredVersions[i]
10436                    : SharedLibraryInfo.VERSION_UNDEFINED;
10437            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10438            if (libEntry == null) {
10439                if (required) {
10440                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10441                            "Package " + packageName + " requires unavailable shared library "
10442                                    + libName + "; failing!");
10443                } else if (DEBUG_SHARED_LIBRARIES) {
10444                    Slog.i(TAG, "Package " + packageName
10445                            + " desires unavailable shared library "
10446                            + libName + "; ignoring!");
10447                }
10448            } else {
10449                if (requiredVersions != null && requiredCertDigests != null) {
10450                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10451                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10452                            "Package " + packageName + " requires unavailable static shared"
10453                                    + " library " + libName + " version "
10454                                    + libEntry.info.getVersion() + "; failing!");
10455                    }
10456
10457                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10458                    if (libPkg == null) {
10459                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10460                                "Package " + packageName + " requires unavailable static shared"
10461                                        + " library; failing!");
10462                    }
10463
10464                    final String[] expectedCertDigests = requiredCertDigests[i];
10465                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10466                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10467                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10468                            : PackageUtils.computeSignaturesSha256Digests(
10469                                    new Signature[]{libPkg.mSignatures[0]});
10470
10471                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10472                    // target O we don't parse the "additional-certificate" tags similarly
10473                    // how we only consider all certs only for apps targeting O (see above).
10474                    // Therefore, the size check is safe to make.
10475                    if (expectedCertDigests.length != libCertDigests.length) {
10476                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10477                                "Package " + packageName + " requires differently signed" +
10478                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10479                    }
10480
10481                    // Use a predictable order as signature order may vary
10482                    Arrays.sort(libCertDigests);
10483                    Arrays.sort(expectedCertDigests);
10484
10485                    final int certCount = libCertDigests.length;
10486                    for (int j = 0; j < certCount; j++) {
10487                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10488                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10489                                    "Package " + packageName + " requires differently signed" +
10490                                            " static shared library; failing!");
10491                        }
10492                    }
10493                }
10494
10495                if (outUsedLibraries == null) {
10496                    outUsedLibraries = new ArraySet<>();
10497                }
10498                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10499            }
10500        }
10501        return outUsedLibraries;
10502    }
10503
10504    private static boolean hasString(List<String> list, List<String> which) {
10505        if (list == null) {
10506            return false;
10507        }
10508        for (int i=list.size()-1; i>=0; i--) {
10509            for (int j=which.size()-1; j>=0; j--) {
10510                if (which.get(j).equals(list.get(i))) {
10511                    return true;
10512                }
10513            }
10514        }
10515        return false;
10516    }
10517
10518    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10519            PackageParser.Package changingPkg) {
10520        ArrayList<PackageParser.Package> res = null;
10521        for (PackageParser.Package pkg : mPackages.values()) {
10522            if (changingPkg != null
10523                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10524                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10525                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10526                            changingPkg.staticSharedLibName)) {
10527                return null;
10528            }
10529            if (res == null) {
10530                res = new ArrayList<>();
10531            }
10532            res.add(pkg);
10533            try {
10534                updateSharedLibrariesLPr(pkg, changingPkg);
10535            } catch (PackageManagerException e) {
10536                // If a system app update or an app and a required lib missing we
10537                // delete the package and for updated system apps keep the data as
10538                // it is better for the user to reinstall than to be in an limbo
10539                // state. Also libs disappearing under an app should never happen
10540                // - just in case.
10541                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10542                    final int flags = pkg.isUpdatedSystemApp()
10543                            ? PackageManager.DELETE_KEEP_DATA : 0;
10544                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10545                            flags , null, true, null);
10546                }
10547                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10548            }
10549        }
10550        return res;
10551    }
10552
10553    /**
10554     * Derive the value of the {@code cpuAbiOverride} based on the provided
10555     * value and an optional stored value from the package settings.
10556     */
10557    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10558        String cpuAbiOverride = null;
10559
10560        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10561            cpuAbiOverride = null;
10562        } else if (abiOverride != null) {
10563            cpuAbiOverride = abiOverride;
10564        } else if (settings != null) {
10565            cpuAbiOverride = settings.cpuAbiOverrideString;
10566        }
10567
10568        return cpuAbiOverride;
10569    }
10570
10571    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10572            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10573                    throws PackageManagerException {
10574        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10575        // If the package has children and this is the first dive in the function
10576        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10577        // whether all packages (parent and children) would be successfully scanned
10578        // before the actual scan since scanning mutates internal state and we want
10579        // to atomically install the package and its children.
10580        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10581            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10582                scanFlags |= SCAN_CHECK_ONLY;
10583            }
10584        } else {
10585            scanFlags &= ~SCAN_CHECK_ONLY;
10586        }
10587
10588        final PackageParser.Package scannedPkg;
10589        try {
10590            // Scan the parent
10591            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10592            // Scan the children
10593            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10594            for (int i = 0; i < childCount; i++) {
10595                PackageParser.Package childPkg = pkg.childPackages.get(i);
10596                scanPackageLI(childPkg, policyFlags,
10597                        scanFlags, currentTime, user);
10598            }
10599        } finally {
10600            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10601        }
10602
10603        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10604            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10605        }
10606
10607        return scannedPkg;
10608    }
10609
10610    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10611            int scanFlags, long currentTime, @Nullable UserHandle user)
10612                    throws PackageManagerException {
10613        boolean success = false;
10614        try {
10615            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10616                    currentTime, user);
10617            success = true;
10618            return res;
10619        } finally {
10620            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10621                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10622                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10623                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10624                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10625            }
10626        }
10627    }
10628
10629    /**
10630     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10631     */
10632    private static boolean apkHasCode(String fileName) {
10633        StrictJarFile jarFile = null;
10634        try {
10635            jarFile = new StrictJarFile(fileName,
10636                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10637            return jarFile.findEntry("classes.dex") != null;
10638        } catch (IOException ignore) {
10639        } finally {
10640            try {
10641                if (jarFile != null) {
10642                    jarFile.close();
10643                }
10644            } catch (IOException ignore) {}
10645        }
10646        return false;
10647    }
10648
10649    /**
10650     * Enforces code policy for the package. This ensures that if an APK has
10651     * declared hasCode="true" in its manifest that the APK actually contains
10652     * code.
10653     *
10654     * @throws PackageManagerException If bytecode could not be found when it should exist
10655     */
10656    private static void assertCodePolicy(PackageParser.Package pkg)
10657            throws PackageManagerException {
10658        final boolean shouldHaveCode =
10659                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10660        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10661            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10662                    "Package " + pkg.baseCodePath + " code is missing");
10663        }
10664
10665        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10666            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10667                final boolean splitShouldHaveCode =
10668                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10669                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10670                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10671                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10672                }
10673            }
10674        }
10675    }
10676
10677    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10678            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10679                    throws PackageManagerException {
10680        if (DEBUG_PACKAGE_SCANNING) {
10681            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10682                Log.d(TAG, "Scanning package " + pkg.packageName);
10683        }
10684
10685        applyPolicy(pkg, policyFlags);
10686
10687        assertPackageIsValid(pkg, policyFlags, scanFlags);
10688
10689        if (Build.IS_DEBUGGABLE &&
10690                pkg.isPrivilegedApp() &&
10691                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10692            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10693        }
10694
10695        // Initialize package source and resource directories
10696        final File scanFile = new File(pkg.codePath);
10697        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10698        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10699
10700        SharedUserSetting suid = null;
10701        PackageSetting pkgSetting = null;
10702
10703        // Getting the package setting may have a side-effect, so if we
10704        // are only checking if scan would succeed, stash a copy of the
10705        // old setting to restore at the end.
10706        PackageSetting nonMutatedPs = null;
10707
10708        // We keep references to the derived CPU Abis from settings in oder to reuse
10709        // them in the case where we're not upgrading or booting for the first time.
10710        String primaryCpuAbiFromSettings = null;
10711        String secondaryCpuAbiFromSettings = null;
10712
10713        // writer
10714        synchronized (mPackages) {
10715            if (pkg.mSharedUserId != null) {
10716                // SIDE EFFECTS; may potentially allocate a new shared user
10717                suid = mSettings.getSharedUserLPw(
10718                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10719                if (DEBUG_PACKAGE_SCANNING) {
10720                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10721                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10722                                + "): packages=" + suid.packages);
10723                }
10724            }
10725
10726            // Check if we are renaming from an original package name.
10727            PackageSetting origPackage = null;
10728            String realName = null;
10729            if (pkg.mOriginalPackages != null) {
10730                // This package may need to be renamed to a previously
10731                // installed name.  Let's check on that...
10732                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10733                if (pkg.mOriginalPackages.contains(renamed)) {
10734                    // This package had originally been installed as the
10735                    // original name, and we have already taken care of
10736                    // transitioning to the new one.  Just update the new
10737                    // one to continue using the old name.
10738                    realName = pkg.mRealPackage;
10739                    if (!pkg.packageName.equals(renamed)) {
10740                        // Callers into this function may have already taken
10741                        // care of renaming the package; only do it here if
10742                        // it is not already done.
10743                        pkg.setPackageName(renamed);
10744                    }
10745                } else {
10746                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10747                        if ((origPackage = mSettings.getPackageLPr(
10748                                pkg.mOriginalPackages.get(i))) != null) {
10749                            // We do have the package already installed under its
10750                            // original name...  should we use it?
10751                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10752                                // New package is not compatible with original.
10753                                origPackage = null;
10754                                continue;
10755                            } else if (origPackage.sharedUser != null) {
10756                                // Make sure uid is compatible between packages.
10757                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10758                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10759                                            + " to " + pkg.packageName + ": old uid "
10760                                            + origPackage.sharedUser.name
10761                                            + " differs from " + pkg.mSharedUserId);
10762                                    origPackage = null;
10763                                    continue;
10764                                }
10765                                // TODO: Add case when shared user id is added [b/28144775]
10766                            } else {
10767                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10768                                        + pkg.packageName + " to old name " + origPackage.name);
10769                            }
10770                            break;
10771                        }
10772                    }
10773                }
10774            }
10775
10776            if (mTransferedPackages.contains(pkg.packageName)) {
10777                Slog.w(TAG, "Package " + pkg.packageName
10778                        + " was transferred to another, but its .apk remains");
10779            }
10780
10781            // See comments in nonMutatedPs declaration
10782            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10783                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10784                if (foundPs != null) {
10785                    nonMutatedPs = new PackageSetting(foundPs);
10786                }
10787            }
10788
10789            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10790                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10791                if (foundPs != null) {
10792                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10793                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10794                }
10795            }
10796
10797            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10798            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10799                PackageManagerService.reportSettingsProblem(Log.WARN,
10800                        "Package " + pkg.packageName + " shared user changed from "
10801                                + (pkgSetting.sharedUser != null
10802                                        ? pkgSetting.sharedUser.name : "<nothing>")
10803                                + " to "
10804                                + (suid != null ? suid.name : "<nothing>")
10805                                + "; replacing with new");
10806                pkgSetting = null;
10807            }
10808            final PackageSetting oldPkgSetting =
10809                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10810            final PackageSetting disabledPkgSetting =
10811                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10812
10813            String[] usesStaticLibraries = null;
10814            if (pkg.usesStaticLibraries != null) {
10815                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10816                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10817            }
10818
10819            if (pkgSetting == null) {
10820                final String parentPackageName = (pkg.parentPackage != null)
10821                        ? pkg.parentPackage.packageName : null;
10822                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10823                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10824                // REMOVE SharedUserSetting from method; update in a separate call
10825                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10826                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10827                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10828                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10829                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10830                        true /*allowInstall*/, instantApp, virtualPreload,
10831                        parentPackageName, pkg.getChildPackageNames(),
10832                        UserManagerService.getInstance(), usesStaticLibraries,
10833                        pkg.usesStaticLibrariesVersions);
10834                // SIDE EFFECTS; updates system state; move elsewhere
10835                if (origPackage != null) {
10836                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10837                }
10838                mSettings.addUserToSettingLPw(pkgSetting);
10839            } else {
10840                // REMOVE SharedUserSetting from method; update in a separate call.
10841                //
10842                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10843                // secondaryCpuAbi are not known at this point so we always update them
10844                // to null here, only to reset them at a later point.
10845                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10846                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10847                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10848                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10849                        UserManagerService.getInstance(), usesStaticLibraries,
10850                        pkg.usesStaticLibrariesVersions);
10851            }
10852            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10853            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10854
10855            // SIDE EFFECTS; modifies system state; move elsewhere
10856            if (pkgSetting.origPackage != null) {
10857                // If we are first transitioning from an original package,
10858                // fix up the new package's name now.  We need to do this after
10859                // looking up the package under its new name, so getPackageLP
10860                // can take care of fiddling things correctly.
10861                pkg.setPackageName(origPackage.name);
10862
10863                // File a report about this.
10864                String msg = "New package " + pkgSetting.realName
10865                        + " renamed to replace old package " + pkgSetting.name;
10866                reportSettingsProblem(Log.WARN, msg);
10867
10868                // Make a note of it.
10869                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10870                    mTransferedPackages.add(origPackage.name);
10871                }
10872
10873                // No longer need to retain this.
10874                pkgSetting.origPackage = null;
10875            }
10876
10877            // SIDE EFFECTS; modifies system state; move elsewhere
10878            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10879                // Make a note of it.
10880                mTransferedPackages.add(pkg.packageName);
10881            }
10882
10883            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10884                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10885            }
10886
10887            if ((scanFlags & SCAN_BOOTING) == 0
10888                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10889                // Check all shared libraries and map to their actual file path.
10890                // We only do this here for apps not on a system dir, because those
10891                // are the only ones that can fail an install due to this.  We
10892                // will take care of the system apps by updating all of their
10893                // library paths after the scan is done. Also during the initial
10894                // scan don't update any libs as we do this wholesale after all
10895                // apps are scanned to avoid dependency based scanning.
10896                updateSharedLibrariesLPr(pkg, null);
10897            }
10898
10899            if (mFoundPolicyFile) {
10900                SELinuxMMAC.assignSeInfoValue(pkg);
10901            }
10902            pkg.applicationInfo.uid = pkgSetting.appId;
10903            pkg.mExtras = pkgSetting;
10904
10905
10906            // Static shared libs have same package with different versions where
10907            // we internally use a synthetic package name to allow multiple versions
10908            // of the same package, therefore we need to compare signatures against
10909            // the package setting for the latest library version.
10910            PackageSetting signatureCheckPs = pkgSetting;
10911            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10912                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10913                if (libraryEntry != null) {
10914                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10915                }
10916            }
10917
10918            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10919                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10920                    // We just determined the app is signed correctly, so bring
10921                    // over the latest parsed certs.
10922                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10923                } else {
10924                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10925                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10926                                "Package " + pkg.packageName + " upgrade keys do not match the "
10927                                + "previously installed version");
10928                    } else {
10929                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10930                        String msg = "System package " + pkg.packageName
10931                                + " signature changed; retaining data.";
10932                        reportSettingsProblem(Log.WARN, msg);
10933                    }
10934                }
10935            } else {
10936                try {
10937                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10938                    verifySignaturesLP(signatureCheckPs, pkg);
10939                    // We just determined the app is signed correctly, so bring
10940                    // over the latest parsed certs.
10941                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10942                } catch (PackageManagerException e) {
10943                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10944                        throw e;
10945                    }
10946                    // The signature has changed, but this package is in the system
10947                    // image...  let's recover!
10948                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10949                    // However...  if this package is part of a shared user, but it
10950                    // doesn't match the signature of the shared user, let's fail.
10951                    // What this means is that you can't change the signatures
10952                    // associated with an overall shared user, which doesn't seem all
10953                    // that unreasonable.
10954                    if (signatureCheckPs.sharedUser != null) {
10955                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10956                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10957                            throw new PackageManagerException(
10958                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10959                                    "Signature mismatch for shared user: "
10960                                            + pkgSetting.sharedUser);
10961                        }
10962                    }
10963                    // File a report about this.
10964                    String msg = "System package " + pkg.packageName
10965                            + " signature changed; retaining data.";
10966                    reportSettingsProblem(Log.WARN, msg);
10967                }
10968            }
10969
10970            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10971                // This package wants to adopt ownership of permissions from
10972                // another package.
10973                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10974                    final String origName = pkg.mAdoptPermissions.get(i);
10975                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10976                    if (orig != null) {
10977                        if (verifyPackageUpdateLPr(orig, pkg)) {
10978                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10979                                    + pkg.packageName);
10980                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10981                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10982                        }
10983                    }
10984                }
10985            }
10986        }
10987
10988        pkg.applicationInfo.processName = fixProcessName(
10989                pkg.applicationInfo.packageName,
10990                pkg.applicationInfo.processName);
10991
10992        if (pkg != mPlatformPackage) {
10993            // Get all of our default paths setup
10994            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10995        }
10996
10997        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10998
10999        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
11000            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
11001                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
11002                final boolean extractNativeLibs = !pkg.isLibrary();
11003                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
11004                        mAppLib32InstallDir);
11005                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11006
11007                // Some system apps still use directory structure for native libraries
11008                // in which case we might end up not detecting abi solely based on apk
11009                // structure. Try to detect abi based on directory structure.
11010                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11011                        pkg.applicationInfo.primaryCpuAbi == null) {
11012                    setBundledAppAbisAndRoots(pkg, pkgSetting);
11013                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11014                }
11015            } else {
11016                // This is not a first boot or an upgrade, don't bother deriving the
11017                // ABI during the scan. Instead, trust the value that was stored in the
11018                // package setting.
11019                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11020                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11021
11022                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11023
11024                if (DEBUG_ABI_SELECTION) {
11025                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11026                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11027                        pkg.applicationInfo.secondaryCpuAbi);
11028                }
11029            }
11030        } else {
11031            if ((scanFlags & SCAN_MOVE) != 0) {
11032                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11033                // but we already have this packages package info in the PackageSetting. We just
11034                // use that and derive the native library path based on the new codepath.
11035                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11036                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11037            }
11038
11039            // Set native library paths again. For moves, the path will be updated based on the
11040            // ABIs we've determined above. For non-moves, the path will be updated based on the
11041            // ABIs we determined during compilation, but the path will depend on the final
11042            // package path (after the rename away from the stage path).
11043            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11044        }
11045
11046        // This is a special case for the "system" package, where the ABI is
11047        // dictated by the zygote configuration (and init.rc). We should keep track
11048        // of this ABI so that we can deal with "normal" applications that run under
11049        // the same UID correctly.
11050        if (mPlatformPackage == pkg) {
11051            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11052                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11053        }
11054
11055        // If there's a mismatch between the abi-override in the package setting
11056        // and the abiOverride specified for the install. Warn about this because we
11057        // would've already compiled the app without taking the package setting into
11058        // account.
11059        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11060            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11061                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11062                        " for package " + pkg.packageName);
11063            }
11064        }
11065
11066        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11067        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11068        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11069
11070        // Copy the derived override back to the parsed package, so that we can
11071        // update the package settings accordingly.
11072        pkg.cpuAbiOverride = cpuAbiOverride;
11073
11074        if (DEBUG_ABI_SELECTION) {
11075            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11076                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11077                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11078        }
11079
11080        // Push the derived path down into PackageSettings so we know what to
11081        // clean up at uninstall time.
11082        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11083
11084        if (DEBUG_ABI_SELECTION) {
11085            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11086                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11087                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11088        }
11089
11090        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11091        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11092            // We don't do this here during boot because we can do it all
11093            // at once after scanning all existing packages.
11094            //
11095            // We also do this *before* we perform dexopt on this package, so that
11096            // we can avoid redundant dexopts, and also to make sure we've got the
11097            // code and package path correct.
11098            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11099        }
11100
11101        if (mFactoryTest && pkg.requestedPermissions.contains(
11102                android.Manifest.permission.FACTORY_TEST)) {
11103            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11104        }
11105
11106        if (isSystemApp(pkg)) {
11107            pkgSetting.isOrphaned = true;
11108        }
11109
11110        // Take care of first install / last update times.
11111        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11112        if (currentTime != 0) {
11113            if (pkgSetting.firstInstallTime == 0) {
11114                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11115            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11116                pkgSetting.lastUpdateTime = currentTime;
11117            }
11118        } else if (pkgSetting.firstInstallTime == 0) {
11119            // We need *something*.  Take time time stamp of the file.
11120            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11121        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11122            if (scanFileTime != pkgSetting.timeStamp) {
11123                // A package on the system image has changed; consider this
11124                // to be an update.
11125                pkgSetting.lastUpdateTime = scanFileTime;
11126            }
11127        }
11128        pkgSetting.setTimeStamp(scanFileTime);
11129
11130        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11131            if (nonMutatedPs != null) {
11132                synchronized (mPackages) {
11133                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11134                }
11135            }
11136        } else {
11137            final int userId = user == null ? 0 : user.getIdentifier();
11138            // Modify state for the given package setting
11139            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11140                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11141            if (pkgSetting.getInstantApp(userId)) {
11142                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11143            }
11144        }
11145        return pkg;
11146    }
11147
11148    /**
11149     * Applies policy to the parsed package based upon the given policy flags.
11150     * Ensures the package is in a good state.
11151     * <p>
11152     * Implementation detail: This method must NOT have any side effect. It would
11153     * ideally be static, but, it requires locks to read system state.
11154     */
11155    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11156        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11157            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11158            if (pkg.applicationInfo.isDirectBootAware()) {
11159                // we're direct boot aware; set for all components
11160                for (PackageParser.Service s : pkg.services) {
11161                    s.info.encryptionAware = s.info.directBootAware = true;
11162                }
11163                for (PackageParser.Provider p : pkg.providers) {
11164                    p.info.encryptionAware = p.info.directBootAware = true;
11165                }
11166                for (PackageParser.Activity a : pkg.activities) {
11167                    a.info.encryptionAware = a.info.directBootAware = true;
11168                }
11169                for (PackageParser.Activity r : pkg.receivers) {
11170                    r.info.encryptionAware = r.info.directBootAware = true;
11171                }
11172            }
11173            if (compressedFileExists(pkg.codePath)) {
11174                pkg.isStub = true;
11175            }
11176        } else {
11177            // Only allow system apps to be flagged as core apps.
11178            pkg.coreApp = false;
11179            // clear flags not applicable to regular apps
11180            pkg.applicationInfo.privateFlags &=
11181                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11182            pkg.applicationInfo.privateFlags &=
11183                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11184        }
11185        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11186
11187        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11188            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11189        }
11190
11191        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
11192            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
11193        }
11194
11195        if (!isSystemApp(pkg)) {
11196            // Only system apps can use these features.
11197            pkg.mOriginalPackages = null;
11198            pkg.mRealPackage = null;
11199            pkg.mAdoptPermissions = null;
11200        }
11201    }
11202
11203    /**
11204     * Asserts the parsed package is valid according to the given policy. If the
11205     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11206     * <p>
11207     * Implementation detail: This method must NOT have any side effects. It would
11208     * ideally be static, but, it requires locks to read system state.
11209     *
11210     * @throws PackageManagerException If the package fails any of the validation checks
11211     */
11212    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11213            throws PackageManagerException {
11214        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11215            assertCodePolicy(pkg);
11216        }
11217
11218        if (pkg.applicationInfo.getCodePath() == null ||
11219                pkg.applicationInfo.getResourcePath() == null) {
11220            // Bail out. The resource and code paths haven't been set.
11221            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11222                    "Code and resource paths haven't been set correctly");
11223        }
11224
11225        // Make sure we're not adding any bogus keyset info
11226        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11227        ksms.assertScannedPackageValid(pkg);
11228
11229        synchronized (mPackages) {
11230            // The special "android" package can only be defined once
11231            if (pkg.packageName.equals("android")) {
11232                if (mAndroidApplication != null) {
11233                    Slog.w(TAG, "*************************************************");
11234                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11235                    Slog.w(TAG, " codePath=" + pkg.codePath);
11236                    Slog.w(TAG, "*************************************************");
11237                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11238                            "Core android package being redefined.  Skipping.");
11239                }
11240            }
11241
11242            // A package name must be unique; don't allow duplicates
11243            if (mPackages.containsKey(pkg.packageName)) {
11244                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11245                        "Application package " + pkg.packageName
11246                        + " already installed.  Skipping duplicate.");
11247            }
11248
11249            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11250                // Static libs have a synthetic package name containing the version
11251                // but we still want the base name to be unique.
11252                if (mPackages.containsKey(pkg.manifestPackageName)) {
11253                    throw new PackageManagerException(
11254                            "Duplicate static shared lib provider package");
11255                }
11256
11257                // Static shared libraries should have at least O target SDK
11258                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11259                    throw new PackageManagerException(
11260                            "Packages declaring static-shared libs must target O SDK or higher");
11261                }
11262
11263                // Package declaring static a shared lib cannot be instant apps
11264                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11265                    throw new PackageManagerException(
11266                            "Packages declaring static-shared libs cannot be instant apps");
11267                }
11268
11269                // Package declaring static a shared lib cannot be renamed since the package
11270                // name is synthetic and apps can't code around package manager internals.
11271                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11272                    throw new PackageManagerException(
11273                            "Packages declaring static-shared libs cannot be renamed");
11274                }
11275
11276                // Package declaring static a shared lib cannot declare child packages
11277                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11278                    throw new PackageManagerException(
11279                            "Packages declaring static-shared libs cannot have child packages");
11280                }
11281
11282                // Package declaring static a shared lib cannot declare dynamic libs
11283                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11284                    throw new PackageManagerException(
11285                            "Packages declaring static-shared libs cannot declare dynamic libs");
11286                }
11287
11288                // Package declaring static a shared lib cannot declare shared users
11289                if (pkg.mSharedUserId != null) {
11290                    throw new PackageManagerException(
11291                            "Packages declaring static-shared libs cannot declare shared users");
11292                }
11293
11294                // Static shared libs cannot declare activities
11295                if (!pkg.activities.isEmpty()) {
11296                    throw new PackageManagerException(
11297                            "Static shared libs cannot declare activities");
11298                }
11299
11300                // Static shared libs cannot declare services
11301                if (!pkg.services.isEmpty()) {
11302                    throw new PackageManagerException(
11303                            "Static shared libs cannot declare services");
11304                }
11305
11306                // Static shared libs cannot declare providers
11307                if (!pkg.providers.isEmpty()) {
11308                    throw new PackageManagerException(
11309                            "Static shared libs cannot declare content providers");
11310                }
11311
11312                // Static shared libs cannot declare receivers
11313                if (!pkg.receivers.isEmpty()) {
11314                    throw new PackageManagerException(
11315                            "Static shared libs cannot declare broadcast receivers");
11316                }
11317
11318                // Static shared libs cannot declare permission groups
11319                if (!pkg.permissionGroups.isEmpty()) {
11320                    throw new PackageManagerException(
11321                            "Static shared libs cannot declare permission groups");
11322                }
11323
11324                // Static shared libs cannot declare permissions
11325                if (!pkg.permissions.isEmpty()) {
11326                    throw new PackageManagerException(
11327                            "Static shared libs cannot declare permissions");
11328                }
11329
11330                // Static shared libs cannot declare protected broadcasts
11331                if (pkg.protectedBroadcasts != null) {
11332                    throw new PackageManagerException(
11333                            "Static shared libs cannot declare protected broadcasts");
11334                }
11335
11336                // Static shared libs cannot be overlay targets
11337                if (pkg.mOverlayTarget != null) {
11338                    throw new PackageManagerException(
11339                            "Static shared libs cannot be overlay targets");
11340                }
11341
11342                // The version codes must be ordered as lib versions
11343                int minVersionCode = Integer.MIN_VALUE;
11344                int maxVersionCode = Integer.MAX_VALUE;
11345
11346                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11347                        pkg.staticSharedLibName);
11348                if (versionedLib != null) {
11349                    final int versionCount = versionedLib.size();
11350                    for (int i = 0; i < versionCount; i++) {
11351                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11352                        final int libVersionCode = libInfo.getDeclaringPackage()
11353                                .getVersionCode();
11354                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11355                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11356                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11357                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11358                        } else {
11359                            minVersionCode = maxVersionCode = libVersionCode;
11360                            break;
11361                        }
11362                    }
11363                }
11364                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11365                    throw new PackageManagerException("Static shared"
11366                            + " lib version codes must be ordered as lib versions");
11367                }
11368            }
11369
11370            // Only privileged apps and updated privileged apps can add child packages.
11371            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11372                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11373                    throw new PackageManagerException("Only privileged apps can add child "
11374                            + "packages. Ignoring package " + pkg.packageName);
11375                }
11376                final int childCount = pkg.childPackages.size();
11377                for (int i = 0; i < childCount; i++) {
11378                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11379                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11380                            childPkg.packageName)) {
11381                        throw new PackageManagerException("Can't override child of "
11382                                + "another disabled app. Ignoring package " + pkg.packageName);
11383                    }
11384                }
11385            }
11386
11387            // If we're only installing presumed-existing packages, require that the
11388            // scanned APK is both already known and at the path previously established
11389            // for it.  Previously unknown packages we pick up normally, but if we have an
11390            // a priori expectation about this package's install presence, enforce it.
11391            // With a singular exception for new system packages. When an OTA contains
11392            // a new system package, we allow the codepath to change from a system location
11393            // to the user-installed location. If we don't allow this change, any newer,
11394            // user-installed version of the application will be ignored.
11395            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11396                if (mExpectingBetter.containsKey(pkg.packageName)) {
11397                    logCriticalInfo(Log.WARN,
11398                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11399                } else {
11400                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11401                    if (known != null) {
11402                        if (DEBUG_PACKAGE_SCANNING) {
11403                            Log.d(TAG, "Examining " + pkg.codePath
11404                                    + " and requiring known paths " + known.codePathString
11405                                    + " & " + known.resourcePathString);
11406                        }
11407                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11408                                || !pkg.applicationInfo.getResourcePath().equals(
11409                                        known.resourcePathString)) {
11410                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11411                                    "Application package " + pkg.packageName
11412                                    + " found at " + pkg.applicationInfo.getCodePath()
11413                                    + " but expected at " + known.codePathString
11414                                    + "; ignoring.");
11415                        }
11416                    } else {
11417                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11418                                "Application package " + pkg.packageName
11419                                + " not found; ignoring.");
11420                    }
11421                }
11422            }
11423
11424            // Verify that this new package doesn't have any content providers
11425            // that conflict with existing packages.  Only do this if the
11426            // package isn't already installed, since we don't want to break
11427            // things that are installed.
11428            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11429                final int N = pkg.providers.size();
11430                int i;
11431                for (i=0; i<N; i++) {
11432                    PackageParser.Provider p = pkg.providers.get(i);
11433                    if (p.info.authority != null) {
11434                        String names[] = p.info.authority.split(";");
11435                        for (int j = 0; j < names.length; j++) {
11436                            if (mProvidersByAuthority.containsKey(names[j])) {
11437                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11438                                final String otherPackageName =
11439                                        ((other != null && other.getComponentName() != null) ?
11440                                                other.getComponentName().getPackageName() : "?");
11441                                throw new PackageManagerException(
11442                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11443                                        "Can't install because provider name " + names[j]
11444                                                + " (in package " + pkg.applicationInfo.packageName
11445                                                + ") is already used by " + otherPackageName);
11446                            }
11447                        }
11448                    }
11449                }
11450            }
11451        }
11452    }
11453
11454    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11455            int type, String declaringPackageName, int declaringVersionCode) {
11456        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11457        if (versionedLib == null) {
11458            versionedLib = new SparseArray<>();
11459            mSharedLibraries.put(name, versionedLib);
11460            if (type == SharedLibraryInfo.TYPE_STATIC) {
11461                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11462            }
11463        } else if (versionedLib.indexOfKey(version) >= 0) {
11464            return false;
11465        }
11466        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11467                version, type, declaringPackageName, declaringVersionCode);
11468        versionedLib.put(version, libEntry);
11469        return true;
11470    }
11471
11472    private boolean removeSharedLibraryLPw(String name, int version) {
11473        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11474        if (versionedLib == null) {
11475            return false;
11476        }
11477        final int libIdx = versionedLib.indexOfKey(version);
11478        if (libIdx < 0) {
11479            return false;
11480        }
11481        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11482        versionedLib.remove(version);
11483        if (versionedLib.size() <= 0) {
11484            mSharedLibraries.remove(name);
11485            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11486                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11487                        .getPackageName());
11488            }
11489        }
11490        return true;
11491    }
11492
11493    /**
11494     * Adds a scanned package to the system. When this method is finished, the package will
11495     * be available for query, resolution, etc...
11496     */
11497    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11498            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11499        final String pkgName = pkg.packageName;
11500        if (mCustomResolverComponentName != null &&
11501                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11502            setUpCustomResolverActivity(pkg);
11503        }
11504
11505        if (pkg.packageName.equals("android")) {
11506            synchronized (mPackages) {
11507                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11508                    // Set up information for our fall-back user intent resolution activity.
11509                    mPlatformPackage = pkg;
11510                    pkg.mVersionCode = mSdkVersion;
11511                    mAndroidApplication = pkg.applicationInfo;
11512                    if (!mResolverReplaced) {
11513                        mResolveActivity.applicationInfo = mAndroidApplication;
11514                        mResolveActivity.name = ResolverActivity.class.getName();
11515                        mResolveActivity.packageName = mAndroidApplication.packageName;
11516                        mResolveActivity.processName = "system:ui";
11517                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11518                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11519                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11520                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11521                        mResolveActivity.exported = true;
11522                        mResolveActivity.enabled = true;
11523                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11524                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11525                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11526                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11527                                | ActivityInfo.CONFIG_ORIENTATION
11528                                | ActivityInfo.CONFIG_KEYBOARD
11529                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11530                        mResolveInfo.activityInfo = mResolveActivity;
11531                        mResolveInfo.priority = 0;
11532                        mResolveInfo.preferredOrder = 0;
11533                        mResolveInfo.match = 0;
11534                        mResolveComponentName = new ComponentName(
11535                                mAndroidApplication.packageName, mResolveActivity.name);
11536                    }
11537                }
11538            }
11539        }
11540
11541        ArrayList<PackageParser.Package> clientLibPkgs = null;
11542        // writer
11543        synchronized (mPackages) {
11544            boolean hasStaticSharedLibs = false;
11545
11546            // Any app can add new static shared libraries
11547            if (pkg.staticSharedLibName != null) {
11548                // Static shared libs don't allow renaming as they have synthetic package
11549                // names to allow install of multiple versions, so use name from manifest.
11550                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11551                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11552                        pkg.manifestPackageName, pkg.mVersionCode)) {
11553                    hasStaticSharedLibs = true;
11554                } else {
11555                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11556                                + pkg.staticSharedLibName + " already exists; skipping");
11557                }
11558                // Static shared libs cannot be updated once installed since they
11559                // use synthetic package name which includes the version code, so
11560                // not need to update other packages's shared lib dependencies.
11561            }
11562
11563            if (!hasStaticSharedLibs
11564                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11565                // Only system apps can add new dynamic shared libraries.
11566                if (pkg.libraryNames != null) {
11567                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11568                        String name = pkg.libraryNames.get(i);
11569                        boolean allowed = false;
11570                        if (pkg.isUpdatedSystemApp()) {
11571                            // New library entries can only be added through the
11572                            // system image.  This is important to get rid of a lot
11573                            // of nasty edge cases: for example if we allowed a non-
11574                            // system update of the app to add a library, then uninstalling
11575                            // the update would make the library go away, and assumptions
11576                            // we made such as through app install filtering would now
11577                            // have allowed apps on the device which aren't compatible
11578                            // with it.  Better to just have the restriction here, be
11579                            // conservative, and create many fewer cases that can negatively
11580                            // impact the user experience.
11581                            final PackageSetting sysPs = mSettings
11582                                    .getDisabledSystemPkgLPr(pkg.packageName);
11583                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11584                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11585                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11586                                        allowed = true;
11587                                        break;
11588                                    }
11589                                }
11590                            }
11591                        } else {
11592                            allowed = true;
11593                        }
11594                        if (allowed) {
11595                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11596                                    SharedLibraryInfo.VERSION_UNDEFINED,
11597                                    SharedLibraryInfo.TYPE_DYNAMIC,
11598                                    pkg.packageName, pkg.mVersionCode)) {
11599                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11600                                        + name + " already exists; skipping");
11601                            }
11602                        } else {
11603                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11604                                    + name + " that is not declared on system image; skipping");
11605                        }
11606                    }
11607
11608                    if ((scanFlags & SCAN_BOOTING) == 0) {
11609                        // If we are not booting, we need to update any applications
11610                        // that are clients of our shared library.  If we are booting,
11611                        // this will all be done once the scan is complete.
11612                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11613                    }
11614                }
11615            }
11616        }
11617
11618        if ((scanFlags & SCAN_BOOTING) != 0) {
11619            // No apps can run during boot scan, so they don't need to be frozen
11620        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11621            // Caller asked to not kill app, so it's probably not frozen
11622        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11623            // Caller asked us to ignore frozen check for some reason; they
11624            // probably didn't know the package name
11625        } else {
11626            // We're doing major surgery on this package, so it better be frozen
11627            // right now to keep it from launching
11628            checkPackageFrozen(pkgName);
11629        }
11630
11631        // Also need to kill any apps that are dependent on the library.
11632        if (clientLibPkgs != null) {
11633            for (int i=0; i<clientLibPkgs.size(); i++) {
11634                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11635                killApplication(clientPkg.applicationInfo.packageName,
11636                        clientPkg.applicationInfo.uid, "update lib");
11637            }
11638        }
11639
11640        // writer
11641        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11642
11643        synchronized (mPackages) {
11644            // We don't expect installation to fail beyond this point
11645
11646            // Add the new setting to mSettings
11647            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11648            // Add the new setting to mPackages
11649            mPackages.put(pkg.applicationInfo.packageName, pkg);
11650            // Make sure we don't accidentally delete its data.
11651            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11652            while (iter.hasNext()) {
11653                PackageCleanItem item = iter.next();
11654                if (pkgName.equals(item.packageName)) {
11655                    iter.remove();
11656                }
11657            }
11658
11659            // Add the package's KeySets to the global KeySetManagerService
11660            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11661            ksms.addScannedPackageLPw(pkg);
11662
11663            int N = pkg.providers.size();
11664            StringBuilder r = null;
11665            int i;
11666            for (i=0; i<N; i++) {
11667                PackageParser.Provider p = pkg.providers.get(i);
11668                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11669                        p.info.processName);
11670                mProviders.addProvider(p);
11671                p.syncable = p.info.isSyncable;
11672                if (p.info.authority != null) {
11673                    String names[] = p.info.authority.split(";");
11674                    p.info.authority = null;
11675                    for (int j = 0; j < names.length; j++) {
11676                        if (j == 1 && p.syncable) {
11677                            // We only want the first authority for a provider to possibly be
11678                            // syncable, so if we already added this provider using a different
11679                            // authority clear the syncable flag. We copy the provider before
11680                            // changing it because the mProviders object contains a reference
11681                            // to a provider that we don't want to change.
11682                            // Only do this for the second authority since the resulting provider
11683                            // object can be the same for all future authorities for this provider.
11684                            p = new PackageParser.Provider(p);
11685                            p.syncable = false;
11686                        }
11687                        if (!mProvidersByAuthority.containsKey(names[j])) {
11688                            mProvidersByAuthority.put(names[j], p);
11689                            if (p.info.authority == null) {
11690                                p.info.authority = names[j];
11691                            } else {
11692                                p.info.authority = p.info.authority + ";" + names[j];
11693                            }
11694                            if (DEBUG_PACKAGE_SCANNING) {
11695                                if (chatty)
11696                                    Log.d(TAG, "Registered content provider: " + names[j]
11697                                            + ", className = " + p.info.name + ", isSyncable = "
11698                                            + p.info.isSyncable);
11699                            }
11700                        } else {
11701                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11702                            Slog.w(TAG, "Skipping provider name " + names[j] +
11703                                    " (in package " + pkg.applicationInfo.packageName +
11704                                    "): name already used by "
11705                                    + ((other != null && other.getComponentName() != null)
11706                                            ? other.getComponentName().getPackageName() : "?"));
11707                        }
11708                    }
11709                }
11710                if (chatty) {
11711                    if (r == null) {
11712                        r = new StringBuilder(256);
11713                    } else {
11714                        r.append(' ');
11715                    }
11716                    r.append(p.info.name);
11717                }
11718            }
11719            if (r != null) {
11720                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11721            }
11722
11723            N = pkg.services.size();
11724            r = null;
11725            for (i=0; i<N; i++) {
11726                PackageParser.Service s = pkg.services.get(i);
11727                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11728                        s.info.processName);
11729                mServices.addService(s);
11730                if (chatty) {
11731                    if (r == null) {
11732                        r = new StringBuilder(256);
11733                    } else {
11734                        r.append(' ');
11735                    }
11736                    r.append(s.info.name);
11737                }
11738            }
11739            if (r != null) {
11740                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11741            }
11742
11743            N = pkg.receivers.size();
11744            r = null;
11745            for (i=0; i<N; i++) {
11746                PackageParser.Activity a = pkg.receivers.get(i);
11747                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11748                        a.info.processName);
11749                mReceivers.addActivity(a, "receiver");
11750                if (chatty) {
11751                    if (r == null) {
11752                        r = new StringBuilder(256);
11753                    } else {
11754                        r.append(' ');
11755                    }
11756                    r.append(a.info.name);
11757                }
11758            }
11759            if (r != null) {
11760                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11761            }
11762
11763            N = pkg.activities.size();
11764            r = null;
11765            for (i=0; i<N; i++) {
11766                PackageParser.Activity a = pkg.activities.get(i);
11767                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11768                        a.info.processName);
11769                mActivities.addActivity(a, "activity");
11770                if (chatty) {
11771                    if (r == null) {
11772                        r = new StringBuilder(256);
11773                    } else {
11774                        r.append(' ');
11775                    }
11776                    r.append(a.info.name);
11777                }
11778            }
11779            if (r != null) {
11780                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11781            }
11782
11783            N = pkg.permissionGroups.size();
11784            r = null;
11785            for (i=0; i<N; i++) {
11786                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11787                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11788                final String curPackageName = cur == null ? null : cur.info.packageName;
11789                // Dont allow ephemeral apps to define new permission groups.
11790                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11791                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11792                            + pg.info.packageName
11793                            + " ignored: instant apps cannot define new permission groups.");
11794                    continue;
11795                }
11796                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11797                if (cur == null || isPackageUpdate) {
11798                    mPermissionGroups.put(pg.info.name, pg);
11799                    if (chatty) {
11800                        if (r == null) {
11801                            r = new StringBuilder(256);
11802                        } else {
11803                            r.append(' ');
11804                        }
11805                        if (isPackageUpdate) {
11806                            r.append("UPD:");
11807                        }
11808                        r.append(pg.info.name);
11809                    }
11810                } else {
11811                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11812                            + pg.info.packageName + " ignored: original from "
11813                            + cur.info.packageName);
11814                    if (chatty) {
11815                        if (r == null) {
11816                            r = new StringBuilder(256);
11817                        } else {
11818                            r.append(' ');
11819                        }
11820                        r.append("DUP:");
11821                        r.append(pg.info.name);
11822                    }
11823                }
11824            }
11825            if (r != null) {
11826                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11827            }
11828
11829            N = pkg.permissions.size();
11830            r = null;
11831            for (i=0; i<N; i++) {
11832                PackageParser.Permission p = pkg.permissions.get(i);
11833
11834                // Dont allow ephemeral apps to define new permissions.
11835                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11836                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11837                            + p.info.packageName
11838                            + " ignored: instant apps cannot define new permissions.");
11839                    continue;
11840                }
11841
11842                // Assume by default that we did not install this permission into the system.
11843                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11844
11845                // Now that permission groups have a special meaning, we ignore permission
11846                // groups for legacy apps to prevent unexpected behavior. In particular,
11847                // permissions for one app being granted to someone just because they happen
11848                // to be in a group defined by another app (before this had no implications).
11849                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11850                    p.group = mPermissionGroups.get(p.info.group);
11851                    // Warn for a permission in an unknown group.
11852                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11853                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11854                                + p.info.packageName + " in an unknown group " + p.info.group);
11855                    }
11856                }
11857
11858                ArrayMap<String, BasePermission> permissionMap =
11859                        p.tree ? mSettings.mPermissionTrees
11860                                : mSettings.mPermissions;
11861                BasePermission bp = permissionMap.get(p.info.name);
11862
11863                // Allow system apps to redefine non-system permissions
11864                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11865                    final boolean currentOwnerIsSystem = (bp.perm != null
11866                            && isSystemApp(bp.perm.owner));
11867                    if (isSystemApp(p.owner)) {
11868                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11869                            // It's a built-in permission and no owner, take ownership now
11870                            bp.packageSetting = pkgSetting;
11871                            bp.perm = p;
11872                            bp.uid = pkg.applicationInfo.uid;
11873                            bp.sourcePackage = p.info.packageName;
11874                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11875                        } else if (!currentOwnerIsSystem) {
11876                            String msg = "New decl " + p.owner + " of permission  "
11877                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11878                            reportSettingsProblem(Log.WARN, msg);
11879                            bp = null;
11880                        }
11881                    }
11882                }
11883
11884                if (bp == null) {
11885                    bp = new BasePermission(p.info.name, p.info.packageName,
11886                            BasePermission.TYPE_NORMAL);
11887                    permissionMap.put(p.info.name, bp);
11888                }
11889
11890                if (bp.perm == null) {
11891                    if (bp.sourcePackage == null
11892                            || bp.sourcePackage.equals(p.info.packageName)) {
11893                        BasePermission tree = findPermissionTreeLP(p.info.name);
11894                        if (tree == null
11895                                || tree.sourcePackage.equals(p.info.packageName)) {
11896                            bp.packageSetting = pkgSetting;
11897                            bp.perm = p;
11898                            bp.uid = pkg.applicationInfo.uid;
11899                            bp.sourcePackage = p.info.packageName;
11900                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11901                            if (chatty) {
11902                                if (r == null) {
11903                                    r = new StringBuilder(256);
11904                                } else {
11905                                    r.append(' ');
11906                                }
11907                                r.append(p.info.name);
11908                            }
11909                        } else {
11910                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11911                                    + p.info.packageName + " ignored: base tree "
11912                                    + tree.name + " is from package "
11913                                    + tree.sourcePackage);
11914                        }
11915                    } else {
11916                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11917                                + p.info.packageName + " ignored: original from "
11918                                + bp.sourcePackage);
11919                    }
11920                } else if (chatty) {
11921                    if (r == null) {
11922                        r = new StringBuilder(256);
11923                    } else {
11924                        r.append(' ');
11925                    }
11926                    r.append("DUP:");
11927                    r.append(p.info.name);
11928                }
11929                if (bp.perm == p) {
11930                    bp.protectionLevel = p.info.protectionLevel;
11931                }
11932            }
11933
11934            if (r != null) {
11935                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11936            }
11937
11938            N = pkg.instrumentation.size();
11939            r = null;
11940            for (i=0; i<N; i++) {
11941                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11942                a.info.packageName = pkg.applicationInfo.packageName;
11943                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11944                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11945                a.info.splitNames = pkg.splitNames;
11946                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11947                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11948                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11949                a.info.dataDir = pkg.applicationInfo.dataDir;
11950                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11951                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11952                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11953                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11954                mInstrumentation.put(a.getComponentName(), a);
11955                if (chatty) {
11956                    if (r == null) {
11957                        r = new StringBuilder(256);
11958                    } else {
11959                        r.append(' ');
11960                    }
11961                    r.append(a.info.name);
11962                }
11963            }
11964            if (r != null) {
11965                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11966            }
11967
11968            if (pkg.protectedBroadcasts != null) {
11969                N = pkg.protectedBroadcasts.size();
11970                synchronized (mProtectedBroadcasts) {
11971                    for (i = 0; i < N; i++) {
11972                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11973                    }
11974                }
11975            }
11976        }
11977
11978        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11979    }
11980
11981    /**
11982     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11983     * is derived purely on the basis of the contents of {@code scanFile} and
11984     * {@code cpuAbiOverride}.
11985     *
11986     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11987     */
11988    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11989                                 String cpuAbiOverride, boolean extractLibs,
11990                                 File appLib32InstallDir)
11991            throws PackageManagerException {
11992        // Give ourselves some initial paths; we'll come back for another
11993        // pass once we've determined ABI below.
11994        setNativeLibraryPaths(pkg, appLib32InstallDir);
11995
11996        // We would never need to extract libs for forward-locked and external packages,
11997        // since the container service will do it for us. We shouldn't attempt to
11998        // extract libs from system app when it was not updated.
11999        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
12000                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
12001            extractLibs = false;
12002        }
12003
12004        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
12005        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
12006
12007        NativeLibraryHelper.Handle handle = null;
12008        try {
12009            handle = NativeLibraryHelper.Handle.create(pkg);
12010            // TODO(multiArch): This can be null for apps that didn't go through the
12011            // usual installation process. We can calculate it again, like we
12012            // do during install time.
12013            //
12014            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12015            // unnecessary.
12016            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12017
12018            // Null out the abis so that they can be recalculated.
12019            pkg.applicationInfo.primaryCpuAbi = null;
12020            pkg.applicationInfo.secondaryCpuAbi = null;
12021            if (isMultiArch(pkg.applicationInfo)) {
12022                // Warn if we've set an abiOverride for multi-lib packages..
12023                // By definition, we need to copy both 32 and 64 bit libraries for
12024                // such packages.
12025                if (pkg.cpuAbiOverride != null
12026                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12027                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12028                }
12029
12030                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12031                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12032                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12033                    if (extractLibs) {
12034                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12035                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12036                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12037                                useIsaSpecificSubdirs);
12038                    } else {
12039                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12040                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12041                    }
12042                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12043                }
12044
12045                // Shared library native code should be in the APK zip aligned
12046                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12047                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12048                            "Shared library native lib extraction not supported");
12049                }
12050
12051                maybeThrowExceptionForMultiArchCopy(
12052                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12053
12054                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12055                    if (extractLibs) {
12056                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12057                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12058                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12059                                useIsaSpecificSubdirs);
12060                    } else {
12061                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12062                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12063                    }
12064                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12065                }
12066
12067                maybeThrowExceptionForMultiArchCopy(
12068                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12069
12070                if (abi64 >= 0) {
12071                    // Shared library native libs should be in the APK zip aligned
12072                    if (extractLibs && pkg.isLibrary()) {
12073                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12074                                "Shared library native lib extraction not supported");
12075                    }
12076                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12077                }
12078
12079                if (abi32 >= 0) {
12080                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12081                    if (abi64 >= 0) {
12082                        if (pkg.use32bitAbi) {
12083                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12084                            pkg.applicationInfo.primaryCpuAbi = abi;
12085                        } else {
12086                            pkg.applicationInfo.secondaryCpuAbi = abi;
12087                        }
12088                    } else {
12089                        pkg.applicationInfo.primaryCpuAbi = abi;
12090                    }
12091                }
12092            } else {
12093                String[] abiList = (cpuAbiOverride != null) ?
12094                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12095
12096                // Enable gross and lame hacks for apps that are built with old
12097                // SDK tools. We must scan their APKs for renderscript bitcode and
12098                // not launch them if it's present. Don't bother checking on devices
12099                // that don't have 64 bit support.
12100                boolean needsRenderScriptOverride = false;
12101                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12102                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12103                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12104                    needsRenderScriptOverride = true;
12105                }
12106
12107                final int copyRet;
12108                if (extractLibs) {
12109                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12110                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12111                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12112                } else {
12113                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12114                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12115                }
12116                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12117
12118                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12119                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12120                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12121                }
12122
12123                if (copyRet >= 0) {
12124                    // Shared libraries that have native libs must be multi-architecture
12125                    if (pkg.isLibrary()) {
12126                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12127                                "Shared library with native libs must be multiarch");
12128                    }
12129                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12130                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12131                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12132                } else if (needsRenderScriptOverride) {
12133                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12134                }
12135            }
12136        } catch (IOException ioe) {
12137            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12138        } finally {
12139            IoUtils.closeQuietly(handle);
12140        }
12141
12142        // Now that we've calculated the ABIs and determined if it's an internal app,
12143        // we will go ahead and populate the nativeLibraryPath.
12144        setNativeLibraryPaths(pkg, appLib32InstallDir);
12145    }
12146
12147    /**
12148     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12149     * i.e, so that all packages can be run inside a single process if required.
12150     *
12151     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12152     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12153     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12154     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12155     * updating a package that belongs to a shared user.
12156     *
12157     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12158     * adds unnecessary complexity.
12159     */
12160    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12161            PackageParser.Package scannedPackage) {
12162        String requiredInstructionSet = null;
12163        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12164            requiredInstructionSet = VMRuntime.getInstructionSet(
12165                     scannedPackage.applicationInfo.primaryCpuAbi);
12166        }
12167
12168        PackageSetting requirer = null;
12169        for (PackageSetting ps : packagesForUser) {
12170            // If packagesForUser contains scannedPackage, we skip it. This will happen
12171            // when scannedPackage is an update of an existing package. Without this check,
12172            // we will never be able to change the ABI of any package belonging to a shared
12173            // user, even if it's compatible with other packages.
12174            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12175                if (ps.primaryCpuAbiString == null) {
12176                    continue;
12177                }
12178
12179                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12180                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12181                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12182                    // this but there's not much we can do.
12183                    String errorMessage = "Instruction set mismatch, "
12184                            + ((requirer == null) ? "[caller]" : requirer)
12185                            + " requires " + requiredInstructionSet + " whereas " + ps
12186                            + " requires " + instructionSet;
12187                    Slog.w(TAG, errorMessage);
12188                }
12189
12190                if (requiredInstructionSet == null) {
12191                    requiredInstructionSet = instructionSet;
12192                    requirer = ps;
12193                }
12194            }
12195        }
12196
12197        if (requiredInstructionSet != null) {
12198            String adjustedAbi;
12199            if (requirer != null) {
12200                // requirer != null implies that either scannedPackage was null or that scannedPackage
12201                // did not require an ABI, in which case we have to adjust scannedPackage to match
12202                // the ABI of the set (which is the same as requirer's ABI)
12203                adjustedAbi = requirer.primaryCpuAbiString;
12204                if (scannedPackage != null) {
12205                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12206                }
12207            } else {
12208                // requirer == null implies that we're updating all ABIs in the set to
12209                // match scannedPackage.
12210                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12211            }
12212
12213            for (PackageSetting ps : packagesForUser) {
12214                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12215                    if (ps.primaryCpuAbiString != null) {
12216                        continue;
12217                    }
12218
12219                    ps.primaryCpuAbiString = adjustedAbi;
12220                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12221                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12222                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12223                        if (DEBUG_ABI_SELECTION) {
12224                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12225                                    + " (requirer="
12226                                    + (requirer != null ? requirer.pkg : "null")
12227                                    + ", scannedPackage="
12228                                    + (scannedPackage != null ? scannedPackage : "null")
12229                                    + ")");
12230                        }
12231                        try {
12232                            mInstaller.rmdex(ps.codePathString,
12233                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12234                        } catch (InstallerException ignored) {
12235                        }
12236                    }
12237                }
12238            }
12239        }
12240    }
12241
12242    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12243        synchronized (mPackages) {
12244            mResolverReplaced = true;
12245            // Set up information for custom user intent resolution activity.
12246            mResolveActivity.applicationInfo = pkg.applicationInfo;
12247            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12248            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12249            mResolveActivity.processName = pkg.applicationInfo.packageName;
12250            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12251            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12252                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12253            mResolveActivity.theme = 0;
12254            mResolveActivity.exported = true;
12255            mResolveActivity.enabled = true;
12256            mResolveInfo.activityInfo = mResolveActivity;
12257            mResolveInfo.priority = 0;
12258            mResolveInfo.preferredOrder = 0;
12259            mResolveInfo.match = 0;
12260            mResolveComponentName = mCustomResolverComponentName;
12261            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12262                    mResolveComponentName);
12263        }
12264    }
12265
12266    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12267        if (installerActivity == null) {
12268            if (DEBUG_EPHEMERAL) {
12269                Slog.d(TAG, "Clear ephemeral installer activity");
12270            }
12271            mInstantAppInstallerActivity = null;
12272            return;
12273        }
12274
12275        if (DEBUG_EPHEMERAL) {
12276            Slog.d(TAG, "Set ephemeral installer activity: "
12277                    + installerActivity.getComponentName());
12278        }
12279        // Set up information for ephemeral installer activity
12280        mInstantAppInstallerActivity = installerActivity;
12281        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12282                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12283        mInstantAppInstallerActivity.exported = true;
12284        mInstantAppInstallerActivity.enabled = true;
12285        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12286        mInstantAppInstallerInfo.priority = 0;
12287        mInstantAppInstallerInfo.preferredOrder = 1;
12288        mInstantAppInstallerInfo.isDefault = true;
12289        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12290                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12291    }
12292
12293    private static String calculateBundledApkRoot(final String codePathString) {
12294        final File codePath = new File(codePathString);
12295        final File codeRoot;
12296        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12297            codeRoot = Environment.getRootDirectory();
12298        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12299            codeRoot = Environment.getOemDirectory();
12300        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12301            codeRoot = Environment.getVendorDirectory();
12302        } else {
12303            // Unrecognized code path; take its top real segment as the apk root:
12304            // e.g. /something/app/blah.apk => /something
12305            try {
12306                File f = codePath.getCanonicalFile();
12307                File parent = f.getParentFile();    // non-null because codePath is a file
12308                File tmp;
12309                while ((tmp = parent.getParentFile()) != null) {
12310                    f = parent;
12311                    parent = tmp;
12312                }
12313                codeRoot = f;
12314                Slog.w(TAG, "Unrecognized code path "
12315                        + codePath + " - using " + codeRoot);
12316            } catch (IOException e) {
12317                // Can't canonicalize the code path -- shenanigans?
12318                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12319                return Environment.getRootDirectory().getPath();
12320            }
12321        }
12322        return codeRoot.getPath();
12323    }
12324
12325    /**
12326     * Derive and set the location of native libraries for the given package,
12327     * which varies depending on where and how the package was installed.
12328     */
12329    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12330        final ApplicationInfo info = pkg.applicationInfo;
12331        final String codePath = pkg.codePath;
12332        final File codeFile = new File(codePath);
12333        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12334        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12335
12336        info.nativeLibraryRootDir = null;
12337        info.nativeLibraryRootRequiresIsa = false;
12338        info.nativeLibraryDir = null;
12339        info.secondaryNativeLibraryDir = null;
12340
12341        if (isApkFile(codeFile)) {
12342            // Monolithic install
12343            if (bundledApp) {
12344                // If "/system/lib64/apkname" exists, assume that is the per-package
12345                // native library directory to use; otherwise use "/system/lib/apkname".
12346                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12347                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12348                        getPrimaryInstructionSet(info));
12349
12350                // This is a bundled system app so choose the path based on the ABI.
12351                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12352                // is just the default path.
12353                final String apkName = deriveCodePathName(codePath);
12354                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12355                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12356                        apkName).getAbsolutePath();
12357
12358                if (info.secondaryCpuAbi != null) {
12359                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12360                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12361                            secondaryLibDir, apkName).getAbsolutePath();
12362                }
12363            } else if (asecApp) {
12364                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12365                        .getAbsolutePath();
12366            } else {
12367                final String apkName = deriveCodePathName(codePath);
12368                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12369                        .getAbsolutePath();
12370            }
12371
12372            info.nativeLibraryRootRequiresIsa = false;
12373            info.nativeLibraryDir = info.nativeLibraryRootDir;
12374        } else {
12375            // Cluster install
12376            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12377            info.nativeLibraryRootRequiresIsa = true;
12378
12379            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12380                    getPrimaryInstructionSet(info)).getAbsolutePath();
12381
12382            if (info.secondaryCpuAbi != null) {
12383                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12384                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12385            }
12386        }
12387    }
12388
12389    /**
12390     * Calculate the abis and roots for a bundled app. These can uniquely
12391     * be determined from the contents of the system partition, i.e whether
12392     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12393     * of this information, and instead assume that the system was built
12394     * sensibly.
12395     */
12396    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12397                                           PackageSetting pkgSetting) {
12398        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12399
12400        // If "/system/lib64/apkname" exists, assume that is the per-package
12401        // native library directory to use; otherwise use "/system/lib/apkname".
12402        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12403        setBundledAppAbi(pkg, apkRoot, apkName);
12404        // pkgSetting might be null during rescan following uninstall of updates
12405        // to a bundled app, so accommodate that possibility.  The settings in
12406        // that case will be established later from the parsed package.
12407        //
12408        // If the settings aren't null, sync them up with what we've just derived.
12409        // note that apkRoot isn't stored in the package settings.
12410        if (pkgSetting != null) {
12411            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12412            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12413        }
12414    }
12415
12416    /**
12417     * Deduces the ABI of a bundled app and sets the relevant fields on the
12418     * parsed pkg object.
12419     *
12420     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12421     *        under which system libraries are installed.
12422     * @param apkName the name of the installed package.
12423     */
12424    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12425        final File codeFile = new File(pkg.codePath);
12426
12427        final boolean has64BitLibs;
12428        final boolean has32BitLibs;
12429        if (isApkFile(codeFile)) {
12430            // Monolithic install
12431            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12432            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12433        } else {
12434            // Cluster install
12435            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12436            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12437                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12438                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12439                has64BitLibs = (new File(rootDir, isa)).exists();
12440            } else {
12441                has64BitLibs = false;
12442            }
12443            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12444                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12445                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12446                has32BitLibs = (new File(rootDir, isa)).exists();
12447            } else {
12448                has32BitLibs = false;
12449            }
12450        }
12451
12452        if (has64BitLibs && !has32BitLibs) {
12453            // The package has 64 bit libs, but not 32 bit libs. Its primary
12454            // ABI should be 64 bit. We can safely assume here that the bundled
12455            // native libraries correspond to the most preferred ABI in the list.
12456
12457            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12458            pkg.applicationInfo.secondaryCpuAbi = null;
12459        } else if (has32BitLibs && !has64BitLibs) {
12460            // The package has 32 bit libs but not 64 bit libs. Its primary
12461            // ABI should be 32 bit.
12462
12463            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12464            pkg.applicationInfo.secondaryCpuAbi = null;
12465        } else if (has32BitLibs && has64BitLibs) {
12466            // The application has both 64 and 32 bit bundled libraries. We check
12467            // here that the app declares multiArch support, and warn if it doesn't.
12468            //
12469            // We will be lenient here and record both ABIs. The primary will be the
12470            // ABI that's higher on the list, i.e, a device that's configured to prefer
12471            // 64 bit apps will see a 64 bit primary ABI,
12472
12473            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12474                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12475            }
12476
12477            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12478                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12479                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12480            } else {
12481                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12482                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12483            }
12484        } else {
12485            pkg.applicationInfo.primaryCpuAbi = null;
12486            pkg.applicationInfo.secondaryCpuAbi = null;
12487        }
12488    }
12489
12490    private void killApplication(String pkgName, int appId, String reason) {
12491        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12492    }
12493
12494    private void killApplication(String pkgName, int appId, int userId, String reason) {
12495        // Request the ActivityManager to kill the process(only for existing packages)
12496        // so that we do not end up in a confused state while the user is still using the older
12497        // version of the application while the new one gets installed.
12498        final long token = Binder.clearCallingIdentity();
12499        try {
12500            IActivityManager am = ActivityManager.getService();
12501            if (am != null) {
12502                try {
12503                    am.killApplication(pkgName, appId, userId, reason);
12504                } catch (RemoteException e) {
12505                }
12506            }
12507        } finally {
12508            Binder.restoreCallingIdentity(token);
12509        }
12510    }
12511
12512    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12513        // Remove the parent package setting
12514        PackageSetting ps = (PackageSetting) pkg.mExtras;
12515        if (ps != null) {
12516            removePackageLI(ps, chatty);
12517        }
12518        // Remove the child package setting
12519        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12520        for (int i = 0; i < childCount; i++) {
12521            PackageParser.Package childPkg = pkg.childPackages.get(i);
12522            ps = (PackageSetting) childPkg.mExtras;
12523            if (ps != null) {
12524                removePackageLI(ps, chatty);
12525            }
12526        }
12527    }
12528
12529    void removePackageLI(PackageSetting ps, boolean chatty) {
12530        if (DEBUG_INSTALL) {
12531            if (chatty)
12532                Log.d(TAG, "Removing package " + ps.name);
12533        }
12534
12535        // writer
12536        synchronized (mPackages) {
12537            mPackages.remove(ps.name);
12538            final PackageParser.Package pkg = ps.pkg;
12539            if (pkg != null) {
12540                cleanPackageDataStructuresLILPw(pkg, chatty);
12541            }
12542        }
12543    }
12544
12545    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12546        if (DEBUG_INSTALL) {
12547            if (chatty)
12548                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12549        }
12550
12551        // writer
12552        synchronized (mPackages) {
12553            // Remove the parent package
12554            mPackages.remove(pkg.applicationInfo.packageName);
12555            cleanPackageDataStructuresLILPw(pkg, chatty);
12556
12557            // Remove the child packages
12558            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12559            for (int i = 0; i < childCount; i++) {
12560                PackageParser.Package childPkg = pkg.childPackages.get(i);
12561                mPackages.remove(childPkg.applicationInfo.packageName);
12562                cleanPackageDataStructuresLILPw(childPkg, chatty);
12563            }
12564        }
12565    }
12566
12567    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12568        int N = pkg.providers.size();
12569        StringBuilder r = null;
12570        int i;
12571        for (i=0; i<N; i++) {
12572            PackageParser.Provider p = pkg.providers.get(i);
12573            mProviders.removeProvider(p);
12574            if (p.info.authority == null) {
12575
12576                /* There was another ContentProvider with this authority when
12577                 * this app was installed so this authority is null,
12578                 * Ignore it as we don't have to unregister the provider.
12579                 */
12580                continue;
12581            }
12582            String names[] = p.info.authority.split(";");
12583            for (int j = 0; j < names.length; j++) {
12584                if (mProvidersByAuthority.get(names[j]) == p) {
12585                    mProvidersByAuthority.remove(names[j]);
12586                    if (DEBUG_REMOVE) {
12587                        if (chatty)
12588                            Log.d(TAG, "Unregistered content provider: " + names[j]
12589                                    + ", className = " + p.info.name + ", isSyncable = "
12590                                    + p.info.isSyncable);
12591                    }
12592                }
12593            }
12594            if (DEBUG_REMOVE && chatty) {
12595                if (r == null) {
12596                    r = new StringBuilder(256);
12597                } else {
12598                    r.append(' ');
12599                }
12600                r.append(p.info.name);
12601            }
12602        }
12603        if (r != null) {
12604            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12605        }
12606
12607        N = pkg.services.size();
12608        r = null;
12609        for (i=0; i<N; i++) {
12610            PackageParser.Service s = pkg.services.get(i);
12611            mServices.removeService(s);
12612            if (chatty) {
12613                if (r == null) {
12614                    r = new StringBuilder(256);
12615                } else {
12616                    r.append(' ');
12617                }
12618                r.append(s.info.name);
12619            }
12620        }
12621        if (r != null) {
12622            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12623        }
12624
12625        N = pkg.receivers.size();
12626        r = null;
12627        for (i=0; i<N; i++) {
12628            PackageParser.Activity a = pkg.receivers.get(i);
12629            mReceivers.removeActivity(a, "receiver");
12630            if (DEBUG_REMOVE && chatty) {
12631                if (r == null) {
12632                    r = new StringBuilder(256);
12633                } else {
12634                    r.append(' ');
12635                }
12636                r.append(a.info.name);
12637            }
12638        }
12639        if (r != null) {
12640            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12641        }
12642
12643        N = pkg.activities.size();
12644        r = null;
12645        for (i=0; i<N; i++) {
12646            PackageParser.Activity a = pkg.activities.get(i);
12647            mActivities.removeActivity(a, "activity");
12648            if (DEBUG_REMOVE && chatty) {
12649                if (r == null) {
12650                    r = new StringBuilder(256);
12651                } else {
12652                    r.append(' ');
12653                }
12654                r.append(a.info.name);
12655            }
12656        }
12657        if (r != null) {
12658            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12659        }
12660
12661        N = pkg.permissions.size();
12662        r = null;
12663        for (i=0; i<N; i++) {
12664            PackageParser.Permission p = pkg.permissions.get(i);
12665            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12666            if (bp == null) {
12667                bp = mSettings.mPermissionTrees.get(p.info.name);
12668            }
12669            if (bp != null && bp.perm == p) {
12670                bp.perm = null;
12671                if (DEBUG_REMOVE && chatty) {
12672                    if (r == null) {
12673                        r = new StringBuilder(256);
12674                    } else {
12675                        r.append(' ');
12676                    }
12677                    r.append(p.info.name);
12678                }
12679            }
12680            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12681                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12682                if (appOpPkgs != null) {
12683                    appOpPkgs.remove(pkg.packageName);
12684                }
12685            }
12686        }
12687        if (r != null) {
12688            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12689        }
12690
12691        N = pkg.requestedPermissions.size();
12692        r = null;
12693        for (i=0; i<N; i++) {
12694            String perm = pkg.requestedPermissions.get(i);
12695            BasePermission bp = mSettings.mPermissions.get(perm);
12696            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12697                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12698                if (appOpPkgs != null) {
12699                    appOpPkgs.remove(pkg.packageName);
12700                    if (appOpPkgs.isEmpty()) {
12701                        mAppOpPermissionPackages.remove(perm);
12702                    }
12703                }
12704            }
12705        }
12706        if (r != null) {
12707            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12708        }
12709
12710        N = pkg.instrumentation.size();
12711        r = null;
12712        for (i=0; i<N; i++) {
12713            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12714            mInstrumentation.remove(a.getComponentName());
12715            if (DEBUG_REMOVE && chatty) {
12716                if (r == null) {
12717                    r = new StringBuilder(256);
12718                } else {
12719                    r.append(' ');
12720                }
12721                r.append(a.info.name);
12722            }
12723        }
12724        if (r != null) {
12725            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12726        }
12727
12728        r = null;
12729        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12730            // Only system apps can hold shared libraries.
12731            if (pkg.libraryNames != null) {
12732                for (i = 0; i < pkg.libraryNames.size(); i++) {
12733                    String name = pkg.libraryNames.get(i);
12734                    if (removeSharedLibraryLPw(name, 0)) {
12735                        if (DEBUG_REMOVE && chatty) {
12736                            if (r == null) {
12737                                r = new StringBuilder(256);
12738                            } else {
12739                                r.append(' ');
12740                            }
12741                            r.append(name);
12742                        }
12743                    }
12744                }
12745            }
12746        }
12747
12748        r = null;
12749
12750        // Any package can hold static shared libraries.
12751        if (pkg.staticSharedLibName != null) {
12752            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12753                if (DEBUG_REMOVE && chatty) {
12754                    if (r == null) {
12755                        r = new StringBuilder(256);
12756                    } else {
12757                        r.append(' ');
12758                    }
12759                    r.append(pkg.staticSharedLibName);
12760                }
12761            }
12762        }
12763
12764        if (r != null) {
12765            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12766        }
12767    }
12768
12769    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12770        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12771            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12772                return true;
12773            }
12774        }
12775        return false;
12776    }
12777
12778    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12779    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12780    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12781
12782    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12783        // Update the parent permissions
12784        updatePermissionsLPw(pkg.packageName, pkg, flags);
12785        // Update the child permissions
12786        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12787        for (int i = 0; i < childCount; i++) {
12788            PackageParser.Package childPkg = pkg.childPackages.get(i);
12789            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12790        }
12791    }
12792
12793    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12794            int flags) {
12795        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12796        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12797    }
12798
12799    private void updatePermissionsLPw(String changingPkg,
12800            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12801        // Make sure there are no dangling permission trees.
12802        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12803        while (it.hasNext()) {
12804            final BasePermission bp = it.next();
12805            if (bp.packageSetting == null) {
12806                // We may not yet have parsed the package, so just see if
12807                // we still know about its settings.
12808                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12809            }
12810            if (bp.packageSetting == null) {
12811                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12812                        + " from package " + bp.sourcePackage);
12813                it.remove();
12814            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12815                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12816                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12817                            + " from package " + bp.sourcePackage);
12818                    flags |= UPDATE_PERMISSIONS_ALL;
12819                    it.remove();
12820                }
12821            }
12822        }
12823
12824        // Make sure all dynamic permissions have been assigned to a package,
12825        // and make sure there are no dangling permissions.
12826        it = mSettings.mPermissions.values().iterator();
12827        while (it.hasNext()) {
12828            final BasePermission bp = it.next();
12829            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12830                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12831                        + bp.name + " pkg=" + bp.sourcePackage
12832                        + " info=" + bp.pendingInfo);
12833                if (bp.packageSetting == null && bp.pendingInfo != null) {
12834                    final BasePermission tree = findPermissionTreeLP(bp.name);
12835                    if (tree != null && tree.perm != null) {
12836                        bp.packageSetting = tree.packageSetting;
12837                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12838                                new PermissionInfo(bp.pendingInfo));
12839                        bp.perm.info.packageName = tree.perm.info.packageName;
12840                        bp.perm.info.name = bp.name;
12841                        bp.uid = tree.uid;
12842                    }
12843                }
12844            }
12845            if (bp.packageSetting == null) {
12846                // We may not yet have parsed the package, so just see if
12847                // we still know about its settings.
12848                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12849            }
12850            if (bp.packageSetting == null) {
12851                Slog.w(TAG, "Removing dangling permission: " + bp.name
12852                        + " from package " + bp.sourcePackage);
12853                it.remove();
12854            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12855                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12856                    Slog.i(TAG, "Removing old permission: " + bp.name
12857                            + " from package " + bp.sourcePackage);
12858                    flags |= UPDATE_PERMISSIONS_ALL;
12859                    it.remove();
12860                }
12861            }
12862        }
12863
12864        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12865        // Now update the permissions for all packages, in particular
12866        // replace the granted permissions of the system packages.
12867        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12868            for (PackageParser.Package pkg : mPackages.values()) {
12869                if (pkg != pkgInfo) {
12870                    // Only replace for packages on requested volume
12871                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12872                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12873                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12874                    grantPermissionsLPw(pkg, replace, changingPkg);
12875                }
12876            }
12877        }
12878
12879        if (pkgInfo != null) {
12880            // Only replace for packages on requested volume
12881            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12882            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12883                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12884            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12885        }
12886        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12887    }
12888
12889    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12890            String packageOfInterest) {
12891        // IMPORTANT: There are two types of permissions: install and runtime.
12892        // Install time permissions are granted when the app is installed to
12893        // all device users and users added in the future. Runtime permissions
12894        // are granted at runtime explicitly to specific users. Normal and signature
12895        // protected permissions are install time permissions. Dangerous permissions
12896        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12897        // otherwise they are runtime permissions. This function does not manage
12898        // runtime permissions except for the case an app targeting Lollipop MR1
12899        // being upgraded to target a newer SDK, in which case dangerous permissions
12900        // are transformed from install time to runtime ones.
12901
12902        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12903        if (ps == null) {
12904            return;
12905        }
12906
12907        PermissionsState permissionsState = ps.getPermissionsState();
12908        PermissionsState origPermissions = permissionsState;
12909
12910        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12911
12912        boolean runtimePermissionsRevoked = false;
12913        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12914
12915        boolean changedInstallPermission = false;
12916
12917        if (replace) {
12918            ps.installPermissionsFixed = false;
12919            if (!ps.isSharedUser()) {
12920                origPermissions = new PermissionsState(permissionsState);
12921                permissionsState.reset();
12922            } else {
12923                // We need to know only about runtime permission changes since the
12924                // calling code always writes the install permissions state but
12925                // the runtime ones are written only if changed. The only cases of
12926                // changed runtime permissions here are promotion of an install to
12927                // runtime and revocation of a runtime from a shared user.
12928                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12929                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12930                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12931                    runtimePermissionsRevoked = true;
12932                }
12933            }
12934        }
12935
12936        permissionsState.setGlobalGids(mGlobalGids);
12937
12938        final int N = pkg.requestedPermissions.size();
12939        for (int i=0; i<N; i++) {
12940            final String name = pkg.requestedPermissions.get(i);
12941            final BasePermission bp = mSettings.mPermissions.get(name);
12942            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12943                    >= Build.VERSION_CODES.M;
12944
12945            if (DEBUG_INSTALL) {
12946                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12947            }
12948
12949            if (bp == null || bp.packageSetting == null) {
12950                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12951                    if (DEBUG_PERMISSIONS) {
12952                        Slog.i(TAG, "Unknown permission " + name
12953                                + " in package " + pkg.packageName);
12954                    }
12955                }
12956                continue;
12957            }
12958
12959
12960            // Limit ephemeral apps to ephemeral allowed permissions.
12961            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12962                if (DEBUG_PERMISSIONS) {
12963                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12964                            + pkg.packageName);
12965                }
12966                continue;
12967            }
12968
12969            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12970                if (DEBUG_PERMISSIONS) {
12971                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12972                            + pkg.packageName);
12973                }
12974                continue;
12975            }
12976
12977            final String perm = bp.name;
12978            boolean allowedSig = false;
12979            int grant = GRANT_DENIED;
12980
12981            // Keep track of app op permissions.
12982            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12983                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12984                if (pkgs == null) {
12985                    pkgs = new ArraySet<>();
12986                    mAppOpPermissionPackages.put(bp.name, pkgs);
12987                }
12988                pkgs.add(pkg.packageName);
12989            }
12990
12991            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12992            switch (level) {
12993                case PermissionInfo.PROTECTION_NORMAL: {
12994                    // For all apps normal permissions are install time ones.
12995                    grant = GRANT_INSTALL;
12996                } break;
12997
12998                case PermissionInfo.PROTECTION_DANGEROUS: {
12999                    // If a permission review is required for legacy apps we represent
13000                    // their permissions as always granted runtime ones since we need
13001                    // to keep the review required permission flag per user while an
13002                    // install permission's state is shared across all users.
13003                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
13004                        // For legacy apps dangerous permissions are install time ones.
13005                        grant = GRANT_INSTALL;
13006                    } else if (origPermissions.hasInstallPermission(bp.name)) {
13007                        // For legacy apps that became modern, install becomes runtime.
13008                        grant = GRANT_UPGRADE;
13009                    } else if (mPromoteSystemApps
13010                            && isSystemApp(ps)
13011                            && mExistingSystemPackages.contains(ps.name)) {
13012                        // For legacy system apps, install becomes runtime.
13013                        // We cannot check hasInstallPermission() for system apps since those
13014                        // permissions were granted implicitly and not persisted pre-M.
13015                        grant = GRANT_UPGRADE;
13016                    } else {
13017                        // For modern apps keep runtime permissions unchanged.
13018                        grant = GRANT_RUNTIME;
13019                    }
13020                } break;
13021
13022                case PermissionInfo.PROTECTION_SIGNATURE: {
13023                    // For all apps signature permissions are install time ones.
13024                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13025                    if (allowedSig) {
13026                        grant = GRANT_INSTALL;
13027                    }
13028                } break;
13029            }
13030
13031            if (DEBUG_PERMISSIONS) {
13032                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13033            }
13034
13035            if (grant != GRANT_DENIED) {
13036                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13037                    // If this is an existing, non-system package, then
13038                    // we can't add any new permissions to it.
13039                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13040                        // Except...  if this is a permission that was added
13041                        // to the platform (note: need to only do this when
13042                        // updating the platform).
13043                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13044                            grant = GRANT_DENIED;
13045                        }
13046                    }
13047                }
13048
13049                switch (grant) {
13050                    case GRANT_INSTALL: {
13051                        // Revoke this as runtime permission to handle the case of
13052                        // a runtime permission being downgraded to an install one.
13053                        // Also in permission review mode we keep dangerous permissions
13054                        // for legacy apps
13055                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13056                            if (origPermissions.getRuntimePermissionState(
13057                                    bp.name, userId) != null) {
13058                                // Revoke the runtime permission and clear the flags.
13059                                origPermissions.revokeRuntimePermission(bp, userId);
13060                                origPermissions.updatePermissionFlags(bp, userId,
13061                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13062                                // If we revoked a permission permission, we have to write.
13063                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13064                                        changedRuntimePermissionUserIds, userId);
13065                            }
13066                        }
13067                        // Grant an install permission.
13068                        if (permissionsState.grantInstallPermission(bp) !=
13069                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13070                            changedInstallPermission = true;
13071                        }
13072                    } break;
13073
13074                    case GRANT_RUNTIME: {
13075                        // Grant previously granted runtime permissions.
13076                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13077                            PermissionState permissionState = origPermissions
13078                                    .getRuntimePermissionState(bp.name, userId);
13079                            int flags = permissionState != null
13080                                    ? permissionState.getFlags() : 0;
13081                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13082                                // Don't propagate the permission in a permission review mode if
13083                                // the former was revoked, i.e. marked to not propagate on upgrade.
13084                                // Note that in a permission review mode install permissions are
13085                                // represented as constantly granted runtime ones since we need to
13086                                // keep a per user state associated with the permission. Also the
13087                                // revoke on upgrade flag is no longer applicable and is reset.
13088                                final boolean revokeOnUpgrade = (flags & PackageManager
13089                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13090                                if (revokeOnUpgrade) {
13091                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13092                                    // Since we changed the flags, we have to write.
13093                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13094                                            changedRuntimePermissionUserIds, userId);
13095                                }
13096                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13097                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13098                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13099                                        // If we cannot put the permission as it was,
13100                                        // we have to write.
13101                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13102                                                changedRuntimePermissionUserIds, userId);
13103                                    }
13104                                }
13105
13106                                // If the app supports runtime permissions no need for a review.
13107                                if (mPermissionReviewRequired
13108                                        && appSupportsRuntimePermissions
13109                                        && (flags & PackageManager
13110                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13111                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13112                                    // Since we changed the flags, we have to write.
13113                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13114                                            changedRuntimePermissionUserIds, userId);
13115                                }
13116                            } else if (mPermissionReviewRequired
13117                                    && !appSupportsRuntimePermissions) {
13118                                // For legacy apps that need a permission review, every new
13119                                // runtime permission is granted but it is pending a review.
13120                                // We also need to review only platform defined runtime
13121                                // permissions as these are the only ones the platform knows
13122                                // how to disable the API to simulate revocation as legacy
13123                                // apps don't expect to run with revoked permissions.
13124                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13125                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13126                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13127                                        // We changed the flags, hence have to write.
13128                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13129                                                changedRuntimePermissionUserIds, userId);
13130                                    }
13131                                }
13132                                if (permissionsState.grantRuntimePermission(bp, userId)
13133                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13134                                    // We changed the permission, hence have to write.
13135                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13136                                            changedRuntimePermissionUserIds, userId);
13137                                }
13138                            }
13139                            // Propagate the permission flags.
13140                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13141                        }
13142                    } break;
13143
13144                    case GRANT_UPGRADE: {
13145                        // Grant runtime permissions for a previously held install permission.
13146                        PermissionState permissionState = origPermissions
13147                                .getInstallPermissionState(bp.name);
13148                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13149
13150                        if (origPermissions.revokeInstallPermission(bp)
13151                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13152                            // We will be transferring the permission flags, so clear them.
13153                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13154                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13155                            changedInstallPermission = true;
13156                        }
13157
13158                        // If the permission is not to be promoted to runtime we ignore it and
13159                        // also its other flags as they are not applicable to install permissions.
13160                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13161                            for (int userId : currentUserIds) {
13162                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13163                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13164                                    // Transfer the permission flags.
13165                                    permissionsState.updatePermissionFlags(bp, userId,
13166                                            flags, flags);
13167                                    // If we granted the permission, we have to write.
13168                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13169                                            changedRuntimePermissionUserIds, userId);
13170                                }
13171                            }
13172                        }
13173                    } break;
13174
13175                    default: {
13176                        if (packageOfInterest == null
13177                                || packageOfInterest.equals(pkg.packageName)) {
13178                            if (DEBUG_PERMISSIONS) {
13179                                Slog.i(TAG, "Not granting permission " + perm
13180                                        + " to package " + pkg.packageName
13181                                        + " because it was previously installed without");
13182                            }
13183                        }
13184                    } break;
13185                }
13186            } else {
13187                if (permissionsState.revokeInstallPermission(bp) !=
13188                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13189                    // Also drop the permission flags.
13190                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13191                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13192                    changedInstallPermission = true;
13193                    Slog.i(TAG, "Un-granting permission " + perm
13194                            + " from package " + pkg.packageName
13195                            + " (protectionLevel=" + bp.protectionLevel
13196                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13197                            + ")");
13198                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13199                    // Don't print warning for app op permissions, since it is fine for them
13200                    // not to be granted, there is a UI for the user to decide.
13201                    if (DEBUG_PERMISSIONS
13202                            && (packageOfInterest == null
13203                                    || packageOfInterest.equals(pkg.packageName))) {
13204                        Slog.i(TAG, "Not granting permission " + perm
13205                                + " to package " + pkg.packageName
13206                                + " (protectionLevel=" + bp.protectionLevel
13207                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13208                                + ")");
13209                    }
13210                }
13211            }
13212        }
13213
13214        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13215                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13216            // This is the first that we have heard about this package, so the
13217            // permissions we have now selected are fixed until explicitly
13218            // changed.
13219            ps.installPermissionsFixed = true;
13220        }
13221
13222        // Persist the runtime permissions state for users with changes. If permissions
13223        // were revoked because no app in the shared user declares them we have to
13224        // write synchronously to avoid losing runtime permissions state.
13225        for (int userId : changedRuntimePermissionUserIds) {
13226            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13227        }
13228    }
13229
13230    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13231        boolean allowed = false;
13232        final int NP = PackageParser.NEW_PERMISSIONS.length;
13233        for (int ip=0; ip<NP; ip++) {
13234            final PackageParser.NewPermissionInfo npi
13235                    = PackageParser.NEW_PERMISSIONS[ip];
13236            if (npi.name.equals(perm)
13237                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13238                allowed = true;
13239                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13240                        + pkg.packageName);
13241                break;
13242            }
13243        }
13244        return allowed;
13245    }
13246
13247    /**
13248     * Determines whether a package is whitelisted for a particular privapp permission.
13249     *
13250     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
13251     *
13252     * <p>This handles parent/child apps.
13253     */
13254    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
13255        ArraySet<String> wlPermissions = SystemConfig.getInstance()
13256                .getPrivAppPermissions(pkg.packageName);
13257        // Let's check if this package is whitelisted...
13258        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13259        // If it's not, we'll also tail-recurse to the parent.
13260        return whitelisted ||
13261                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
13262    }
13263
13264    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13265            BasePermission bp, PermissionsState origPermissions) {
13266        boolean oemPermission = (bp.protectionLevel
13267                & PermissionInfo.PROTECTION_FLAG_OEM) != 0;
13268        boolean privilegedPermission = (bp.protectionLevel
13269                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13270        boolean privappPermissionsDisable =
13271                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13272        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13273        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13274        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13275                && !platformPackage && platformPermission) {
13276            if (!hasPrivappWhitelistEntry(perm, pkg)) {
13277                Slog.w(TAG, "Privileged permission " + perm + " for package "
13278                        + pkg.packageName + " - not in privapp-permissions whitelist");
13279                // Only report violations for apps on system image
13280                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13281                    // it's only a reportable violation if the permission isn't explicitly denied
13282                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13283                            .getPrivAppDenyPermissions(pkg.packageName);
13284                    final boolean permissionViolation =
13285                            deniedPermissions == null || !deniedPermissions.contains(perm);
13286                    if (permissionViolation) {
13287                        if (mPrivappPermissionsViolations == null) {
13288                            mPrivappPermissionsViolations = new ArraySet<>();
13289                        }
13290                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13291                    } else {
13292                        return false;
13293                    }
13294                }
13295                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13296                    return false;
13297                }
13298            }
13299        }
13300        boolean allowed = (compareSignatures(
13301                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13302                        == PackageManager.SIGNATURE_MATCH)
13303                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13304                        == PackageManager.SIGNATURE_MATCH);
13305        if (!allowed && (privilegedPermission || oemPermission)) {
13306            if (isSystemApp(pkg)) {
13307                // For updated system applications, a privileged/oem permission
13308                // is granted only if it had been defined by the original application.
13309                if (pkg.isUpdatedSystemApp()) {
13310                    final PackageSetting sysPs = mSettings
13311                            .getDisabledSystemPkgLPr(pkg.packageName);
13312                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13313                        // If the original was granted this permission, we take
13314                        // that grant decision as read and propagate it to the
13315                        // update.
13316                        if ((privilegedPermission && sysPs.isPrivileged())
13317                                || (oemPermission && sysPs.isOem()
13318                                        && canGrantOemPermission(sysPs, perm))) {
13319                            allowed = true;
13320                        }
13321                    } else {
13322                        // The system apk may have been updated with an older
13323                        // version of the one on the data partition, but which
13324                        // granted a new system permission that it didn't have
13325                        // before.  In this case we do want to allow the app to
13326                        // now get the new permission if the ancestral apk is
13327                        // privileged to get it.
13328                        if (sysPs != null && sysPs.pkg != null
13329                                && isPackageRequestingPermission(sysPs.pkg, perm)
13330                                && ((privilegedPermission && sysPs.isPrivileged())
13331                                        || (oemPermission && sysPs.isOem()
13332                                                && canGrantOemPermission(sysPs, perm)))) {
13333                            allowed = true;
13334                        }
13335                        // Also if a privileged parent package on the system image or any of
13336                        // its children requested a privileged/oem permission, the updated child
13337                        // packages can also get the permission.
13338                        if (pkg.parentPackage != null) {
13339                            final PackageSetting disabledSysParentPs = mSettings
13340                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13341                            final PackageParser.Package disabledSysParentPkg =
13342                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
13343                                    ? null : disabledSysParentPs.pkg;
13344                            if (disabledSysParentPkg != null
13345                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
13346                                            || (oemPermission && disabledSysParentPs.isOem()))) {
13347                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
13348                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
13349                                    allowed = true;
13350                                } else if (disabledSysParentPkg.childPackages != null) {
13351                                    final int count = disabledSysParentPkg.childPackages.size();
13352                                    for (int i = 0; i < count; i++) {
13353                                        final PackageParser.Package disabledSysChildPkg =
13354                                                disabledSysParentPkg.childPackages.get(i);
13355                                        final PackageSetting disabledSysChildPs =
13356                                                mSettings.getDisabledSystemPkgLPr(
13357                                                        disabledSysChildPkg.packageName);
13358                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
13359                                                && canGrantOemPermission(
13360                                                        disabledSysChildPs, perm)) {
13361                                            allowed = true;
13362                                            break;
13363                                        }
13364                                    }
13365                                }
13366                            }
13367                        }
13368                    }
13369                } else {
13370                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
13371                            || (oemPermission && isOemApp(pkg)
13372                                    && canGrantOemPermission(
13373                                            mSettings.getPackageLPr(pkg.packageName), perm));
13374                }
13375            }
13376        }
13377        if (!allowed) {
13378            if (!allowed && (bp.protectionLevel
13379                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13380                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13381                // If this was a previously normal/dangerous permission that got moved
13382                // to a system permission as part of the runtime permission redesign, then
13383                // we still want to blindly grant it to old apps.
13384                allowed = true;
13385            }
13386            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13387                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13388                // If this permission is to be granted to the system installer and
13389                // this app is an installer, then it gets the permission.
13390                allowed = true;
13391            }
13392            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13393                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13394                // If this permission is to be granted to the system verifier and
13395                // this app is a verifier, then it gets the permission.
13396                allowed = true;
13397            }
13398            if (!allowed && (bp.protectionLevel
13399                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13400                    && isSystemApp(pkg)) {
13401                // Any pre-installed system app is allowed to get this permission.
13402                allowed = true;
13403            }
13404            if (!allowed && (bp.protectionLevel
13405                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13406                // For development permissions, a development permission
13407                // is granted only if it was already granted.
13408                allowed = origPermissions.hasInstallPermission(perm);
13409            }
13410            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13411                    && pkg.packageName.equals(mSetupWizardPackage)) {
13412                // If this permission is to be granted to the system setup wizard and
13413                // this app is a setup wizard, then it gets the permission.
13414                allowed = true;
13415            }
13416        }
13417        return allowed;
13418    }
13419
13420    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
13421        if (!ps.isOem()) {
13422            return false;
13423        }
13424        // all oem permissions must explicitly be granted or denied
13425        final Boolean granted =
13426                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
13427        if (granted == null) {
13428            throw new IllegalStateException("OEM permission" + permission + " requested by package "
13429                    + ps.name + " must be explicitly declared granted or not");
13430        }
13431        return Boolean.TRUE == granted;
13432    }
13433
13434    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13435        final int permCount = pkg.requestedPermissions.size();
13436        for (int j = 0; j < permCount; j++) {
13437            String requestedPermission = pkg.requestedPermissions.get(j);
13438            if (permission.equals(requestedPermission)) {
13439                return true;
13440            }
13441        }
13442        return false;
13443    }
13444
13445    final class ActivityIntentResolver
13446            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13447        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13448                boolean defaultOnly, int userId) {
13449            if (!sUserManager.exists(userId)) return null;
13450            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13451            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13452        }
13453
13454        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13455                int userId) {
13456            if (!sUserManager.exists(userId)) return null;
13457            mFlags = flags;
13458            return super.queryIntent(intent, resolvedType,
13459                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13460                    userId);
13461        }
13462
13463        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13464                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13465            if (!sUserManager.exists(userId)) return null;
13466            if (packageActivities == null) {
13467                return null;
13468            }
13469            mFlags = flags;
13470            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13471            final int N = packageActivities.size();
13472            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13473                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13474
13475            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13476            for (int i = 0; i < N; ++i) {
13477                intentFilters = packageActivities.get(i).intents;
13478                if (intentFilters != null && intentFilters.size() > 0) {
13479                    PackageParser.ActivityIntentInfo[] array =
13480                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13481                    intentFilters.toArray(array);
13482                    listCut.add(array);
13483                }
13484            }
13485            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13486        }
13487
13488        /**
13489         * Finds a privileged activity that matches the specified activity names.
13490         */
13491        private PackageParser.Activity findMatchingActivity(
13492                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13493            for (PackageParser.Activity sysActivity : activityList) {
13494                if (sysActivity.info.name.equals(activityInfo.name)) {
13495                    return sysActivity;
13496                }
13497                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13498                    return sysActivity;
13499                }
13500                if (sysActivity.info.targetActivity != null) {
13501                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13502                        return sysActivity;
13503                    }
13504                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13505                        return sysActivity;
13506                    }
13507                }
13508            }
13509            return null;
13510        }
13511
13512        public class IterGenerator<E> {
13513            public Iterator<E> generate(ActivityIntentInfo info) {
13514                return null;
13515            }
13516        }
13517
13518        public class ActionIterGenerator extends IterGenerator<String> {
13519            @Override
13520            public Iterator<String> generate(ActivityIntentInfo info) {
13521                return info.actionsIterator();
13522            }
13523        }
13524
13525        public class CategoriesIterGenerator extends IterGenerator<String> {
13526            @Override
13527            public Iterator<String> generate(ActivityIntentInfo info) {
13528                return info.categoriesIterator();
13529            }
13530        }
13531
13532        public class SchemesIterGenerator extends IterGenerator<String> {
13533            @Override
13534            public Iterator<String> generate(ActivityIntentInfo info) {
13535                return info.schemesIterator();
13536            }
13537        }
13538
13539        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13540            @Override
13541            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13542                return info.authoritiesIterator();
13543            }
13544        }
13545
13546        /**
13547         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13548         * MODIFIED. Do not pass in a list that should not be changed.
13549         */
13550        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13551                IterGenerator<T> generator, Iterator<T> searchIterator) {
13552            // loop through the set of actions; every one must be found in the intent filter
13553            while (searchIterator.hasNext()) {
13554                // we must have at least one filter in the list to consider a match
13555                if (intentList.size() == 0) {
13556                    break;
13557                }
13558
13559                final T searchAction = searchIterator.next();
13560
13561                // loop through the set of intent filters
13562                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13563                while (intentIter.hasNext()) {
13564                    final ActivityIntentInfo intentInfo = intentIter.next();
13565                    boolean selectionFound = false;
13566
13567                    // loop through the intent filter's selection criteria; at least one
13568                    // of them must match the searched criteria
13569                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13570                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13571                        final T intentSelection = intentSelectionIter.next();
13572                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13573                            selectionFound = true;
13574                            break;
13575                        }
13576                    }
13577
13578                    // the selection criteria wasn't found in this filter's set; this filter
13579                    // is not a potential match
13580                    if (!selectionFound) {
13581                        intentIter.remove();
13582                    }
13583                }
13584            }
13585        }
13586
13587        private boolean isProtectedAction(ActivityIntentInfo filter) {
13588            final Iterator<String> actionsIter = filter.actionsIterator();
13589            while (actionsIter != null && actionsIter.hasNext()) {
13590                final String filterAction = actionsIter.next();
13591                if (PROTECTED_ACTIONS.contains(filterAction)) {
13592                    return true;
13593                }
13594            }
13595            return false;
13596        }
13597
13598        /**
13599         * Adjusts the priority of the given intent filter according to policy.
13600         * <p>
13601         * <ul>
13602         * <li>The priority for non privileged applications is capped to '0'</li>
13603         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13604         * <li>The priority for unbundled updates to privileged applications is capped to the
13605         *      priority defined on the system partition</li>
13606         * </ul>
13607         * <p>
13608         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13609         * allowed to obtain any priority on any action.
13610         */
13611        private void adjustPriority(
13612                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13613            // nothing to do; priority is fine as-is
13614            if (intent.getPriority() <= 0) {
13615                return;
13616            }
13617
13618            final ActivityInfo activityInfo = intent.activity.info;
13619            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13620
13621            final boolean privilegedApp =
13622                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13623            if (!privilegedApp) {
13624                // non-privileged applications can never define a priority >0
13625                if (DEBUG_FILTERS) {
13626                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13627                            + " package: " + applicationInfo.packageName
13628                            + " activity: " + intent.activity.className
13629                            + " origPrio: " + intent.getPriority());
13630                }
13631                intent.setPriority(0);
13632                return;
13633            }
13634
13635            if (systemActivities == null) {
13636                // the system package is not disabled; we're parsing the system partition
13637                if (isProtectedAction(intent)) {
13638                    if (mDeferProtectedFilters) {
13639                        // We can't deal with these just yet. No component should ever obtain a
13640                        // >0 priority for a protected actions, with ONE exception -- the setup
13641                        // wizard. The setup wizard, however, cannot be known until we're able to
13642                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13643                        // until all intent filters have been processed. Chicken, meet egg.
13644                        // Let the filter temporarily have a high priority and rectify the
13645                        // priorities after all system packages have been scanned.
13646                        mProtectedFilters.add(intent);
13647                        if (DEBUG_FILTERS) {
13648                            Slog.i(TAG, "Protected action; save for later;"
13649                                    + " package: " + applicationInfo.packageName
13650                                    + " activity: " + intent.activity.className
13651                                    + " origPrio: " + intent.getPriority());
13652                        }
13653                        return;
13654                    } else {
13655                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13656                            Slog.i(TAG, "No setup wizard;"
13657                                + " All protected intents capped to priority 0");
13658                        }
13659                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13660                            if (DEBUG_FILTERS) {
13661                                Slog.i(TAG, "Found setup wizard;"
13662                                    + " allow priority " + intent.getPriority() + ";"
13663                                    + " package: " + intent.activity.info.packageName
13664                                    + " activity: " + intent.activity.className
13665                                    + " priority: " + intent.getPriority());
13666                            }
13667                            // setup wizard gets whatever it wants
13668                            return;
13669                        }
13670                        if (DEBUG_FILTERS) {
13671                            Slog.i(TAG, "Protected action; cap priority to 0;"
13672                                    + " package: " + intent.activity.info.packageName
13673                                    + " activity: " + intent.activity.className
13674                                    + " origPrio: " + intent.getPriority());
13675                        }
13676                        intent.setPriority(0);
13677                        return;
13678                    }
13679                }
13680                // privileged apps on the system image get whatever priority they request
13681                return;
13682            }
13683
13684            // privileged app unbundled update ... try to find the same activity
13685            final PackageParser.Activity foundActivity =
13686                    findMatchingActivity(systemActivities, activityInfo);
13687            if (foundActivity == null) {
13688                // this is a new activity; it cannot obtain >0 priority
13689                if (DEBUG_FILTERS) {
13690                    Slog.i(TAG, "New activity; cap priority to 0;"
13691                            + " package: " + applicationInfo.packageName
13692                            + " activity: " + intent.activity.className
13693                            + " origPrio: " + intent.getPriority());
13694                }
13695                intent.setPriority(0);
13696                return;
13697            }
13698
13699            // found activity, now check for filter equivalence
13700
13701            // a shallow copy is enough; we modify the list, not its contents
13702            final List<ActivityIntentInfo> intentListCopy =
13703                    new ArrayList<>(foundActivity.intents);
13704            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13705
13706            // find matching action subsets
13707            final Iterator<String> actionsIterator = intent.actionsIterator();
13708            if (actionsIterator != null) {
13709                getIntentListSubset(
13710                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13711                if (intentListCopy.size() == 0) {
13712                    // no more intents to match; we're not equivalent
13713                    if (DEBUG_FILTERS) {
13714                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13715                                + " package: " + applicationInfo.packageName
13716                                + " activity: " + intent.activity.className
13717                                + " origPrio: " + intent.getPriority());
13718                    }
13719                    intent.setPriority(0);
13720                    return;
13721                }
13722            }
13723
13724            // find matching category subsets
13725            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13726            if (categoriesIterator != null) {
13727                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13728                        categoriesIterator);
13729                if (intentListCopy.size() == 0) {
13730                    // no more intents to match; we're not equivalent
13731                    if (DEBUG_FILTERS) {
13732                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13733                                + " package: " + applicationInfo.packageName
13734                                + " activity: " + intent.activity.className
13735                                + " origPrio: " + intent.getPriority());
13736                    }
13737                    intent.setPriority(0);
13738                    return;
13739                }
13740            }
13741
13742            // find matching schemes subsets
13743            final Iterator<String> schemesIterator = intent.schemesIterator();
13744            if (schemesIterator != null) {
13745                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13746                        schemesIterator);
13747                if (intentListCopy.size() == 0) {
13748                    // no more intents to match; we're not equivalent
13749                    if (DEBUG_FILTERS) {
13750                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13751                                + " package: " + applicationInfo.packageName
13752                                + " activity: " + intent.activity.className
13753                                + " origPrio: " + intent.getPriority());
13754                    }
13755                    intent.setPriority(0);
13756                    return;
13757                }
13758            }
13759
13760            // find matching authorities subsets
13761            final Iterator<IntentFilter.AuthorityEntry>
13762                    authoritiesIterator = intent.authoritiesIterator();
13763            if (authoritiesIterator != null) {
13764                getIntentListSubset(intentListCopy,
13765                        new AuthoritiesIterGenerator(),
13766                        authoritiesIterator);
13767                if (intentListCopy.size() == 0) {
13768                    // no more intents to match; we're not equivalent
13769                    if (DEBUG_FILTERS) {
13770                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13771                                + " package: " + applicationInfo.packageName
13772                                + " activity: " + intent.activity.className
13773                                + " origPrio: " + intent.getPriority());
13774                    }
13775                    intent.setPriority(0);
13776                    return;
13777                }
13778            }
13779
13780            // we found matching filter(s); app gets the max priority of all intents
13781            int cappedPriority = 0;
13782            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13783                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13784            }
13785            if (intent.getPriority() > cappedPriority) {
13786                if (DEBUG_FILTERS) {
13787                    Slog.i(TAG, "Found matching filter(s);"
13788                            + " cap priority to " + cappedPriority + ";"
13789                            + " package: " + applicationInfo.packageName
13790                            + " activity: " + intent.activity.className
13791                            + " origPrio: " + intent.getPriority());
13792                }
13793                intent.setPriority(cappedPriority);
13794                return;
13795            }
13796            // all this for nothing; the requested priority was <= what was on the system
13797        }
13798
13799        public final void addActivity(PackageParser.Activity a, String type) {
13800            mActivities.put(a.getComponentName(), a);
13801            if (DEBUG_SHOW_INFO)
13802                Log.v(
13803                TAG, "  " + type + " " +
13804                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13805            if (DEBUG_SHOW_INFO)
13806                Log.v(TAG, "    Class=" + a.info.name);
13807            final int NI = a.intents.size();
13808            for (int j=0; j<NI; j++) {
13809                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13810                if ("activity".equals(type)) {
13811                    final PackageSetting ps =
13812                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13813                    final List<PackageParser.Activity> systemActivities =
13814                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13815                    adjustPriority(systemActivities, intent);
13816                }
13817                if (DEBUG_SHOW_INFO) {
13818                    Log.v(TAG, "    IntentFilter:");
13819                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13820                }
13821                if (!intent.debugCheck()) {
13822                    Log.w(TAG, "==> For Activity " + a.info.name);
13823                }
13824                addFilter(intent);
13825            }
13826        }
13827
13828        public final void removeActivity(PackageParser.Activity a, String type) {
13829            mActivities.remove(a.getComponentName());
13830            if (DEBUG_SHOW_INFO) {
13831                Log.v(TAG, "  " + type + " "
13832                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13833                                : a.info.name) + ":");
13834                Log.v(TAG, "    Class=" + a.info.name);
13835            }
13836            final int NI = a.intents.size();
13837            for (int j=0; j<NI; j++) {
13838                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13839                if (DEBUG_SHOW_INFO) {
13840                    Log.v(TAG, "    IntentFilter:");
13841                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13842                }
13843                removeFilter(intent);
13844            }
13845        }
13846
13847        @Override
13848        protected boolean allowFilterResult(
13849                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13850            ActivityInfo filterAi = filter.activity.info;
13851            for (int i=dest.size()-1; i>=0; i--) {
13852                ActivityInfo destAi = dest.get(i).activityInfo;
13853                if (destAi.name == filterAi.name
13854                        && destAi.packageName == filterAi.packageName) {
13855                    return false;
13856                }
13857            }
13858            return true;
13859        }
13860
13861        @Override
13862        protected ActivityIntentInfo[] newArray(int size) {
13863            return new ActivityIntentInfo[size];
13864        }
13865
13866        @Override
13867        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13868            if (!sUserManager.exists(userId)) return true;
13869            PackageParser.Package p = filter.activity.owner;
13870            if (p != null) {
13871                PackageSetting ps = (PackageSetting)p.mExtras;
13872                if (ps != null) {
13873                    // System apps are never considered stopped for purposes of
13874                    // filtering, because there may be no way for the user to
13875                    // actually re-launch them.
13876                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13877                            && ps.getStopped(userId);
13878                }
13879            }
13880            return false;
13881        }
13882
13883        @Override
13884        protected boolean isPackageForFilter(String packageName,
13885                PackageParser.ActivityIntentInfo info) {
13886            return packageName.equals(info.activity.owner.packageName);
13887        }
13888
13889        @Override
13890        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13891                int match, int userId) {
13892            if (!sUserManager.exists(userId)) return null;
13893            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13894                return null;
13895            }
13896            final PackageParser.Activity activity = info.activity;
13897            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13898            if (ps == null) {
13899                return null;
13900            }
13901            final PackageUserState userState = ps.readUserState(userId);
13902            ActivityInfo ai =
13903                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13904            if (ai == null) {
13905                return null;
13906            }
13907            final boolean matchExplicitlyVisibleOnly =
13908                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13909            final boolean matchVisibleToInstantApp =
13910                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13911            final boolean componentVisible =
13912                    matchVisibleToInstantApp
13913                    && info.isVisibleToInstantApp()
13914                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13915            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13916            // throw out filters that aren't visible to ephemeral apps
13917            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13918                return null;
13919            }
13920            // throw out instant app filters if we're not explicitly requesting them
13921            if (!matchInstantApp && userState.instantApp) {
13922                return null;
13923            }
13924            // throw out instant app filters if updates are available; will trigger
13925            // instant app resolution
13926            if (userState.instantApp && ps.isUpdateAvailable()) {
13927                return null;
13928            }
13929            final ResolveInfo res = new ResolveInfo();
13930            res.activityInfo = ai;
13931            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13932                res.filter = info;
13933            }
13934            if (info != null) {
13935                res.handleAllWebDataURI = info.handleAllWebDataURI();
13936            }
13937            res.priority = info.getPriority();
13938            res.preferredOrder = activity.owner.mPreferredOrder;
13939            //System.out.println("Result: " + res.activityInfo.className +
13940            //                   " = " + res.priority);
13941            res.match = match;
13942            res.isDefault = info.hasDefault;
13943            res.labelRes = info.labelRes;
13944            res.nonLocalizedLabel = info.nonLocalizedLabel;
13945            if (userNeedsBadging(userId)) {
13946                res.noResourceId = true;
13947            } else {
13948                res.icon = info.icon;
13949            }
13950            res.iconResourceId = info.icon;
13951            res.system = res.activityInfo.applicationInfo.isSystemApp();
13952            res.isInstantAppAvailable = userState.instantApp;
13953            return res;
13954        }
13955
13956        @Override
13957        protected void sortResults(List<ResolveInfo> results) {
13958            Collections.sort(results, mResolvePrioritySorter);
13959        }
13960
13961        @Override
13962        protected void dumpFilter(PrintWriter out, String prefix,
13963                PackageParser.ActivityIntentInfo filter) {
13964            out.print(prefix); out.print(
13965                    Integer.toHexString(System.identityHashCode(filter.activity)));
13966                    out.print(' ');
13967                    filter.activity.printComponentShortName(out);
13968                    out.print(" filter ");
13969                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13970        }
13971
13972        @Override
13973        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13974            return filter.activity;
13975        }
13976
13977        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13978            PackageParser.Activity activity = (PackageParser.Activity)label;
13979            out.print(prefix); out.print(
13980                    Integer.toHexString(System.identityHashCode(activity)));
13981                    out.print(' ');
13982                    activity.printComponentShortName(out);
13983            if (count > 1) {
13984                out.print(" ("); out.print(count); out.print(" filters)");
13985            }
13986            out.println();
13987        }
13988
13989        // Keys are String (activity class name), values are Activity.
13990        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13991                = new ArrayMap<ComponentName, PackageParser.Activity>();
13992        private int mFlags;
13993    }
13994
13995    private final class ServiceIntentResolver
13996            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13997        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13998                boolean defaultOnly, int userId) {
13999            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14000            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14001        }
14002
14003        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14004                int userId) {
14005            if (!sUserManager.exists(userId)) return null;
14006            mFlags = flags;
14007            return super.queryIntent(intent, resolvedType,
14008                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14009                    userId);
14010        }
14011
14012        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14013                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
14014            if (!sUserManager.exists(userId)) return null;
14015            if (packageServices == null) {
14016                return null;
14017            }
14018            mFlags = flags;
14019            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
14020            final int N = packageServices.size();
14021            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
14022                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
14023
14024            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
14025            for (int i = 0; i < N; ++i) {
14026                intentFilters = packageServices.get(i).intents;
14027                if (intentFilters != null && intentFilters.size() > 0) {
14028                    PackageParser.ServiceIntentInfo[] array =
14029                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
14030                    intentFilters.toArray(array);
14031                    listCut.add(array);
14032                }
14033            }
14034            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14035        }
14036
14037        public final void addService(PackageParser.Service s) {
14038            mServices.put(s.getComponentName(), s);
14039            if (DEBUG_SHOW_INFO) {
14040                Log.v(TAG, "  "
14041                        + (s.info.nonLocalizedLabel != null
14042                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14043                Log.v(TAG, "    Class=" + s.info.name);
14044            }
14045            final int NI = s.intents.size();
14046            int j;
14047            for (j=0; j<NI; j++) {
14048                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14049                if (DEBUG_SHOW_INFO) {
14050                    Log.v(TAG, "    IntentFilter:");
14051                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14052                }
14053                if (!intent.debugCheck()) {
14054                    Log.w(TAG, "==> For Service " + s.info.name);
14055                }
14056                addFilter(intent);
14057            }
14058        }
14059
14060        public final void removeService(PackageParser.Service s) {
14061            mServices.remove(s.getComponentName());
14062            if (DEBUG_SHOW_INFO) {
14063                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14064                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14065                Log.v(TAG, "    Class=" + s.info.name);
14066            }
14067            final int NI = s.intents.size();
14068            int j;
14069            for (j=0; j<NI; j++) {
14070                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14071                if (DEBUG_SHOW_INFO) {
14072                    Log.v(TAG, "    IntentFilter:");
14073                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14074                }
14075                removeFilter(intent);
14076            }
14077        }
14078
14079        @Override
14080        protected boolean allowFilterResult(
14081                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14082            ServiceInfo filterSi = filter.service.info;
14083            for (int i=dest.size()-1; i>=0; i--) {
14084                ServiceInfo destAi = dest.get(i).serviceInfo;
14085                if (destAi.name == filterSi.name
14086                        && destAi.packageName == filterSi.packageName) {
14087                    return false;
14088                }
14089            }
14090            return true;
14091        }
14092
14093        @Override
14094        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14095            return new PackageParser.ServiceIntentInfo[size];
14096        }
14097
14098        @Override
14099        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14100            if (!sUserManager.exists(userId)) return true;
14101            PackageParser.Package p = filter.service.owner;
14102            if (p != null) {
14103                PackageSetting ps = (PackageSetting)p.mExtras;
14104                if (ps != null) {
14105                    // System apps are never considered stopped for purposes of
14106                    // filtering, because there may be no way for the user to
14107                    // actually re-launch them.
14108                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14109                            && ps.getStopped(userId);
14110                }
14111            }
14112            return false;
14113        }
14114
14115        @Override
14116        protected boolean isPackageForFilter(String packageName,
14117                PackageParser.ServiceIntentInfo info) {
14118            return packageName.equals(info.service.owner.packageName);
14119        }
14120
14121        @Override
14122        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14123                int match, int userId) {
14124            if (!sUserManager.exists(userId)) return null;
14125            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14126            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14127                return null;
14128            }
14129            final PackageParser.Service service = info.service;
14130            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14131            if (ps == null) {
14132                return null;
14133            }
14134            final PackageUserState userState = ps.readUserState(userId);
14135            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14136                    userState, userId);
14137            if (si == null) {
14138                return null;
14139            }
14140            final boolean matchVisibleToInstantApp =
14141                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14142            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14143            // throw out filters that aren't visible to ephemeral apps
14144            if (matchVisibleToInstantApp
14145                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14146                return null;
14147            }
14148            // throw out ephemeral filters if we're not explicitly requesting them
14149            if (!isInstantApp && userState.instantApp) {
14150                return null;
14151            }
14152            // throw out instant app filters if updates are available; will trigger
14153            // instant app resolution
14154            if (userState.instantApp && ps.isUpdateAvailable()) {
14155                return null;
14156            }
14157            final ResolveInfo res = new ResolveInfo();
14158            res.serviceInfo = si;
14159            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14160                res.filter = filter;
14161            }
14162            res.priority = info.getPriority();
14163            res.preferredOrder = service.owner.mPreferredOrder;
14164            res.match = match;
14165            res.isDefault = info.hasDefault;
14166            res.labelRes = info.labelRes;
14167            res.nonLocalizedLabel = info.nonLocalizedLabel;
14168            res.icon = info.icon;
14169            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14170            return res;
14171        }
14172
14173        @Override
14174        protected void sortResults(List<ResolveInfo> results) {
14175            Collections.sort(results, mResolvePrioritySorter);
14176        }
14177
14178        @Override
14179        protected void dumpFilter(PrintWriter out, String prefix,
14180                PackageParser.ServiceIntentInfo filter) {
14181            out.print(prefix); out.print(
14182                    Integer.toHexString(System.identityHashCode(filter.service)));
14183                    out.print(' ');
14184                    filter.service.printComponentShortName(out);
14185                    out.print(" filter ");
14186                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14187        }
14188
14189        @Override
14190        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14191            return filter.service;
14192        }
14193
14194        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14195            PackageParser.Service service = (PackageParser.Service)label;
14196            out.print(prefix); out.print(
14197                    Integer.toHexString(System.identityHashCode(service)));
14198                    out.print(' ');
14199                    service.printComponentShortName(out);
14200            if (count > 1) {
14201                out.print(" ("); out.print(count); out.print(" filters)");
14202            }
14203            out.println();
14204        }
14205
14206//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14207//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14208//            final List<ResolveInfo> retList = Lists.newArrayList();
14209//            while (i.hasNext()) {
14210//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14211//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14212//                    retList.add(resolveInfo);
14213//                }
14214//            }
14215//            return retList;
14216//        }
14217
14218        // Keys are String (activity class name), values are Activity.
14219        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14220                = new ArrayMap<ComponentName, PackageParser.Service>();
14221        private int mFlags;
14222    }
14223
14224    private final class ProviderIntentResolver
14225            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14226        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14227                boolean defaultOnly, int userId) {
14228            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14229            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14230        }
14231
14232        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14233                int userId) {
14234            if (!sUserManager.exists(userId))
14235                return null;
14236            mFlags = flags;
14237            return super.queryIntent(intent, resolvedType,
14238                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14239                    userId);
14240        }
14241
14242        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14243                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14244            if (!sUserManager.exists(userId))
14245                return null;
14246            if (packageProviders == null) {
14247                return null;
14248            }
14249            mFlags = flags;
14250            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14251            final int N = packageProviders.size();
14252            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14253                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14254
14255            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14256            for (int i = 0; i < N; ++i) {
14257                intentFilters = packageProviders.get(i).intents;
14258                if (intentFilters != null && intentFilters.size() > 0) {
14259                    PackageParser.ProviderIntentInfo[] array =
14260                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14261                    intentFilters.toArray(array);
14262                    listCut.add(array);
14263                }
14264            }
14265            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14266        }
14267
14268        public final void addProvider(PackageParser.Provider p) {
14269            if (mProviders.containsKey(p.getComponentName())) {
14270                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14271                return;
14272            }
14273
14274            mProviders.put(p.getComponentName(), p);
14275            if (DEBUG_SHOW_INFO) {
14276                Log.v(TAG, "  "
14277                        + (p.info.nonLocalizedLabel != null
14278                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14279                Log.v(TAG, "    Class=" + p.info.name);
14280            }
14281            final int NI = p.intents.size();
14282            int j;
14283            for (j = 0; j < NI; j++) {
14284                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14285                if (DEBUG_SHOW_INFO) {
14286                    Log.v(TAG, "    IntentFilter:");
14287                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14288                }
14289                if (!intent.debugCheck()) {
14290                    Log.w(TAG, "==> For Provider " + p.info.name);
14291                }
14292                addFilter(intent);
14293            }
14294        }
14295
14296        public final void removeProvider(PackageParser.Provider p) {
14297            mProviders.remove(p.getComponentName());
14298            if (DEBUG_SHOW_INFO) {
14299                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14300                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14301                Log.v(TAG, "    Class=" + p.info.name);
14302            }
14303            final int NI = p.intents.size();
14304            int j;
14305            for (j = 0; j < NI; j++) {
14306                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14307                if (DEBUG_SHOW_INFO) {
14308                    Log.v(TAG, "    IntentFilter:");
14309                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14310                }
14311                removeFilter(intent);
14312            }
14313        }
14314
14315        @Override
14316        protected boolean allowFilterResult(
14317                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14318            ProviderInfo filterPi = filter.provider.info;
14319            for (int i = dest.size() - 1; i >= 0; i--) {
14320                ProviderInfo destPi = dest.get(i).providerInfo;
14321                if (destPi.name == filterPi.name
14322                        && destPi.packageName == filterPi.packageName) {
14323                    return false;
14324                }
14325            }
14326            return true;
14327        }
14328
14329        @Override
14330        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14331            return new PackageParser.ProviderIntentInfo[size];
14332        }
14333
14334        @Override
14335        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14336            if (!sUserManager.exists(userId))
14337                return true;
14338            PackageParser.Package p = filter.provider.owner;
14339            if (p != null) {
14340                PackageSetting ps = (PackageSetting) p.mExtras;
14341                if (ps != null) {
14342                    // System apps are never considered stopped for purposes of
14343                    // filtering, because there may be no way for the user to
14344                    // actually re-launch them.
14345                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14346                            && ps.getStopped(userId);
14347                }
14348            }
14349            return false;
14350        }
14351
14352        @Override
14353        protected boolean isPackageForFilter(String packageName,
14354                PackageParser.ProviderIntentInfo info) {
14355            return packageName.equals(info.provider.owner.packageName);
14356        }
14357
14358        @Override
14359        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14360                int match, int userId) {
14361            if (!sUserManager.exists(userId))
14362                return null;
14363            final PackageParser.ProviderIntentInfo info = filter;
14364            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14365                return null;
14366            }
14367            final PackageParser.Provider provider = info.provider;
14368            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14369            if (ps == null) {
14370                return null;
14371            }
14372            final PackageUserState userState = ps.readUserState(userId);
14373            final boolean matchVisibleToInstantApp =
14374                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14375            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14376            // throw out filters that aren't visible to instant applications
14377            if (matchVisibleToInstantApp
14378                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14379                return null;
14380            }
14381            // throw out instant application filters if we're not explicitly requesting them
14382            if (!isInstantApp && userState.instantApp) {
14383                return null;
14384            }
14385            // throw out instant application filters if updates are available; will trigger
14386            // instant application resolution
14387            if (userState.instantApp && ps.isUpdateAvailable()) {
14388                return null;
14389            }
14390            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14391                    userState, userId);
14392            if (pi == null) {
14393                return null;
14394            }
14395            final ResolveInfo res = new ResolveInfo();
14396            res.providerInfo = pi;
14397            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14398                res.filter = filter;
14399            }
14400            res.priority = info.getPriority();
14401            res.preferredOrder = provider.owner.mPreferredOrder;
14402            res.match = match;
14403            res.isDefault = info.hasDefault;
14404            res.labelRes = info.labelRes;
14405            res.nonLocalizedLabel = info.nonLocalizedLabel;
14406            res.icon = info.icon;
14407            res.system = res.providerInfo.applicationInfo.isSystemApp();
14408            return res;
14409        }
14410
14411        @Override
14412        protected void sortResults(List<ResolveInfo> results) {
14413            Collections.sort(results, mResolvePrioritySorter);
14414        }
14415
14416        @Override
14417        protected void dumpFilter(PrintWriter out, String prefix,
14418                PackageParser.ProviderIntentInfo filter) {
14419            out.print(prefix);
14420            out.print(
14421                    Integer.toHexString(System.identityHashCode(filter.provider)));
14422            out.print(' ');
14423            filter.provider.printComponentShortName(out);
14424            out.print(" filter ");
14425            out.println(Integer.toHexString(System.identityHashCode(filter)));
14426        }
14427
14428        @Override
14429        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14430            return filter.provider;
14431        }
14432
14433        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14434            PackageParser.Provider provider = (PackageParser.Provider)label;
14435            out.print(prefix); out.print(
14436                    Integer.toHexString(System.identityHashCode(provider)));
14437                    out.print(' ');
14438                    provider.printComponentShortName(out);
14439            if (count > 1) {
14440                out.print(" ("); out.print(count); out.print(" filters)");
14441            }
14442            out.println();
14443        }
14444
14445        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14446                = new ArrayMap<ComponentName, PackageParser.Provider>();
14447        private int mFlags;
14448    }
14449
14450    static final class EphemeralIntentResolver
14451            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14452        /**
14453         * The result that has the highest defined order. Ordering applies on a
14454         * per-package basis. Mapping is from package name to Pair of order and
14455         * EphemeralResolveInfo.
14456         * <p>
14457         * NOTE: This is implemented as a field variable for convenience and efficiency.
14458         * By having a field variable, we're able to track filter ordering as soon as
14459         * a non-zero order is defined. Otherwise, multiple loops across the result set
14460         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14461         * this needs to be contained entirely within {@link #filterResults}.
14462         */
14463        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14464
14465        @Override
14466        protected AuxiliaryResolveInfo[] newArray(int size) {
14467            return new AuxiliaryResolveInfo[size];
14468        }
14469
14470        @Override
14471        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14472            return true;
14473        }
14474
14475        @Override
14476        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14477                int userId) {
14478            if (!sUserManager.exists(userId)) {
14479                return null;
14480            }
14481            final String packageName = responseObj.resolveInfo.getPackageName();
14482            final Integer order = responseObj.getOrder();
14483            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14484                    mOrderResult.get(packageName);
14485            // ordering is enabled and this item's order isn't high enough
14486            if (lastOrderResult != null && lastOrderResult.first >= order) {
14487                return null;
14488            }
14489            final InstantAppResolveInfo res = responseObj.resolveInfo;
14490            if (order > 0) {
14491                // non-zero order, enable ordering
14492                mOrderResult.put(packageName, new Pair<>(order, res));
14493            }
14494            return responseObj;
14495        }
14496
14497        @Override
14498        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14499            // only do work if ordering is enabled [most of the time it won't be]
14500            if (mOrderResult.size() == 0) {
14501                return;
14502            }
14503            int resultSize = results.size();
14504            for (int i = 0; i < resultSize; i++) {
14505                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14506                final String packageName = info.getPackageName();
14507                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14508                if (savedInfo == null) {
14509                    // package doesn't having ordering
14510                    continue;
14511                }
14512                if (savedInfo.second == info) {
14513                    // circled back to the highest ordered item; remove from order list
14514                    mOrderResult.remove(packageName);
14515                    if (mOrderResult.size() == 0) {
14516                        // no more ordered items
14517                        break;
14518                    }
14519                    continue;
14520                }
14521                // item has a worse order, remove it from the result list
14522                results.remove(i);
14523                resultSize--;
14524                i--;
14525            }
14526        }
14527    }
14528
14529    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14530            new Comparator<ResolveInfo>() {
14531        public int compare(ResolveInfo r1, ResolveInfo r2) {
14532            int v1 = r1.priority;
14533            int v2 = r2.priority;
14534            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14535            if (v1 != v2) {
14536                return (v1 > v2) ? -1 : 1;
14537            }
14538            v1 = r1.preferredOrder;
14539            v2 = r2.preferredOrder;
14540            if (v1 != v2) {
14541                return (v1 > v2) ? -1 : 1;
14542            }
14543            if (r1.isDefault != r2.isDefault) {
14544                return r1.isDefault ? -1 : 1;
14545            }
14546            v1 = r1.match;
14547            v2 = r2.match;
14548            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14549            if (v1 != v2) {
14550                return (v1 > v2) ? -1 : 1;
14551            }
14552            if (r1.system != r2.system) {
14553                return r1.system ? -1 : 1;
14554            }
14555            if (r1.activityInfo != null) {
14556                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14557            }
14558            if (r1.serviceInfo != null) {
14559                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14560            }
14561            if (r1.providerInfo != null) {
14562                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14563            }
14564            return 0;
14565        }
14566    };
14567
14568    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14569            new Comparator<ProviderInfo>() {
14570        public int compare(ProviderInfo p1, ProviderInfo p2) {
14571            final int v1 = p1.initOrder;
14572            final int v2 = p2.initOrder;
14573            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14574        }
14575    };
14576
14577    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14578            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14579            final int[] userIds) {
14580        mHandler.post(new Runnable() {
14581            @Override
14582            public void run() {
14583                try {
14584                    final IActivityManager am = ActivityManager.getService();
14585                    if (am == null) return;
14586                    final int[] resolvedUserIds;
14587                    if (userIds == null) {
14588                        resolvedUserIds = am.getRunningUserIds();
14589                    } else {
14590                        resolvedUserIds = userIds;
14591                    }
14592                    for (int id : resolvedUserIds) {
14593                        final Intent intent = new Intent(action,
14594                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14595                        if (extras != null) {
14596                            intent.putExtras(extras);
14597                        }
14598                        if (targetPkg != null) {
14599                            intent.setPackage(targetPkg);
14600                        }
14601                        // Modify the UID when posting to other users
14602                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14603                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14604                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14605                            intent.putExtra(Intent.EXTRA_UID, uid);
14606                        }
14607                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14608                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14609                        if (DEBUG_BROADCASTS) {
14610                            RuntimeException here = new RuntimeException("here");
14611                            here.fillInStackTrace();
14612                            Slog.d(TAG, "Sending to user " + id + ": "
14613                                    + intent.toShortString(false, true, false, false)
14614                                    + " " + intent.getExtras(), here);
14615                        }
14616                        am.broadcastIntent(null, intent, null, finishedReceiver,
14617                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14618                                null, finishedReceiver != null, false, id);
14619                    }
14620                } catch (RemoteException ex) {
14621                }
14622            }
14623        });
14624    }
14625
14626    /**
14627     * Check if the external storage media is available. This is true if there
14628     * is a mounted external storage medium or if the external storage is
14629     * emulated.
14630     */
14631    private boolean isExternalMediaAvailable() {
14632        return mMediaMounted || Environment.isExternalStorageEmulated();
14633    }
14634
14635    @Override
14636    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14637        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14638            return null;
14639        }
14640        // writer
14641        synchronized (mPackages) {
14642            if (!isExternalMediaAvailable()) {
14643                // If the external storage is no longer mounted at this point,
14644                // the caller may not have been able to delete all of this
14645                // packages files and can not delete any more.  Bail.
14646                return null;
14647            }
14648            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14649            if (lastPackage != null) {
14650                pkgs.remove(lastPackage);
14651            }
14652            if (pkgs.size() > 0) {
14653                return pkgs.get(0);
14654            }
14655        }
14656        return null;
14657    }
14658
14659    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14660        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14661                userId, andCode ? 1 : 0, packageName);
14662        if (mSystemReady) {
14663            msg.sendToTarget();
14664        } else {
14665            if (mPostSystemReadyMessages == null) {
14666                mPostSystemReadyMessages = new ArrayList<>();
14667            }
14668            mPostSystemReadyMessages.add(msg);
14669        }
14670    }
14671
14672    void startCleaningPackages() {
14673        // reader
14674        if (!isExternalMediaAvailable()) {
14675            return;
14676        }
14677        synchronized (mPackages) {
14678            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14679                return;
14680            }
14681        }
14682        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14683        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14684        IActivityManager am = ActivityManager.getService();
14685        if (am != null) {
14686            int dcsUid = -1;
14687            synchronized (mPackages) {
14688                if (!mDefaultContainerWhitelisted) {
14689                    mDefaultContainerWhitelisted = true;
14690                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14691                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14692                }
14693            }
14694            try {
14695                if (dcsUid > 0) {
14696                    am.backgroundWhitelistUid(dcsUid);
14697                }
14698                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14699                        UserHandle.USER_SYSTEM);
14700            } catch (RemoteException e) {
14701            }
14702        }
14703    }
14704
14705    @Override
14706    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14707            int installFlags, String installerPackageName, int userId) {
14708        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14709
14710        final int callingUid = Binder.getCallingUid();
14711        enforceCrossUserPermission(callingUid, userId,
14712                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14713
14714        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14715            try {
14716                if (observer != null) {
14717                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14718                }
14719            } catch (RemoteException re) {
14720            }
14721            return;
14722        }
14723
14724        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14725            installFlags |= PackageManager.INSTALL_FROM_ADB;
14726
14727        } else {
14728            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14729            // about installerPackageName.
14730
14731            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14732            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14733        }
14734
14735        UserHandle user;
14736        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14737            user = UserHandle.ALL;
14738        } else {
14739            user = new UserHandle(userId);
14740        }
14741
14742        // Only system components can circumvent runtime permissions when installing.
14743        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14744                && mContext.checkCallingOrSelfPermission(Manifest.permission
14745                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14746            throw new SecurityException("You need the "
14747                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14748                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14749        }
14750
14751        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14752                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14753            throw new IllegalArgumentException(
14754                    "New installs into ASEC containers no longer supported");
14755        }
14756
14757        final File originFile = new File(originPath);
14758        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14759
14760        final Message msg = mHandler.obtainMessage(INIT_COPY);
14761        final VerificationInfo verificationInfo = new VerificationInfo(
14762                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14763        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14764                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14765                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14766                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14767        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14768        msg.obj = params;
14769
14770        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14771                System.identityHashCode(msg.obj));
14772        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14773                System.identityHashCode(msg.obj));
14774
14775        mHandler.sendMessage(msg);
14776    }
14777
14778
14779    /**
14780     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14781     * it is acting on behalf on an enterprise or the user).
14782     *
14783     * Note that the ordering of the conditionals in this method is important. The checks we perform
14784     * are as follows, in this order:
14785     *
14786     * 1) If the install is being performed by a system app, we can trust the app to have set the
14787     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14788     *    what it is.
14789     * 2) If the install is being performed by a device or profile owner app, the install reason
14790     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14791     *    set the install reason correctly. If the app targets an older SDK version where install
14792     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14793     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14794     * 3) In all other cases, the install is being performed by a regular app that is neither part
14795     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14796     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14797     *    set to enterprise policy and if so, change it to unknown instead.
14798     */
14799    private int fixUpInstallReason(String installerPackageName, int installerUid,
14800            int installReason) {
14801        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14802                == PERMISSION_GRANTED) {
14803            // If the install is being performed by a system app, we trust that app to have set the
14804            // install reason correctly.
14805            return installReason;
14806        }
14807
14808        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14809            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14810        if (dpm != null) {
14811            ComponentName owner = null;
14812            try {
14813                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14814                if (owner == null) {
14815                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14816                }
14817            } catch (RemoteException e) {
14818            }
14819            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14820                // If the install is being performed by a device or profile owner, the install
14821                // reason should be enterprise policy.
14822                return PackageManager.INSTALL_REASON_POLICY;
14823            }
14824        }
14825
14826        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14827            // If the install is being performed by a regular app (i.e. neither system app nor
14828            // device or profile owner), we have no reason to believe that the app is acting on
14829            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14830            // change it to unknown instead.
14831            return PackageManager.INSTALL_REASON_UNKNOWN;
14832        }
14833
14834        // If the install is being performed by a regular app and the install reason was set to any
14835        // value but enterprise policy, leave the install reason unchanged.
14836        return installReason;
14837    }
14838
14839    void installStage(String packageName, File stagedDir,
14840            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14841            String installerPackageName, int installerUid, UserHandle user,
14842            Certificate[][] certificates) {
14843        if (DEBUG_EPHEMERAL) {
14844            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14845                Slog.d(TAG, "Ephemeral install of " + packageName);
14846            }
14847        }
14848        final VerificationInfo verificationInfo = new VerificationInfo(
14849                sessionParams.originatingUri, sessionParams.referrerUri,
14850                sessionParams.originatingUid, installerUid);
14851
14852        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
14853
14854        final Message msg = mHandler.obtainMessage(INIT_COPY);
14855        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14856                sessionParams.installReason);
14857        final InstallParams params = new InstallParams(origin, null, observer,
14858                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14859                verificationInfo, user, sessionParams.abiOverride,
14860                sessionParams.grantedRuntimePermissions, certificates, installReason);
14861        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14862        msg.obj = params;
14863
14864        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14865                System.identityHashCode(msg.obj));
14866        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14867                System.identityHashCode(msg.obj));
14868
14869        mHandler.sendMessage(msg);
14870    }
14871
14872    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14873            int userId) {
14874        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14875        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14876                false /*startReceiver*/, pkgSetting.appId, userId);
14877
14878        // Send a session commit broadcast
14879        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14880        info.installReason = pkgSetting.getInstallReason(userId);
14881        info.appPackageName = packageName;
14882        sendSessionCommitBroadcast(info, userId);
14883    }
14884
14885    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14886            boolean includeStopped, int appId, int... userIds) {
14887        if (ArrayUtils.isEmpty(userIds)) {
14888            return;
14889        }
14890        Bundle extras = new Bundle(1);
14891        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14892        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14893
14894        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14895                packageName, extras, 0, null, null, userIds);
14896        if (sendBootCompleted) {
14897            mHandler.post(() -> {
14898                        for (int userId : userIds) {
14899                            sendBootCompletedBroadcastToSystemApp(
14900                                    packageName, includeStopped, userId);
14901                        }
14902                    }
14903            );
14904        }
14905    }
14906
14907    /**
14908     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14909     * automatically without needing an explicit launch.
14910     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14911     */
14912    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14913            int userId) {
14914        // If user is not running, the app didn't miss any broadcast
14915        if (!mUserManagerInternal.isUserRunning(userId)) {
14916            return;
14917        }
14918        final IActivityManager am = ActivityManager.getService();
14919        try {
14920            // Deliver LOCKED_BOOT_COMPLETED first
14921            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14922                    .setPackage(packageName);
14923            if (includeStopped) {
14924                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14925            }
14926            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14927            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14928                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14929
14930            // Deliver BOOT_COMPLETED only if user is unlocked
14931            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14932                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14933                if (includeStopped) {
14934                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14935                }
14936                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14937                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14938            }
14939        } catch (RemoteException e) {
14940            throw e.rethrowFromSystemServer();
14941        }
14942    }
14943
14944    @Override
14945    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14946            int userId) {
14947        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14948        PackageSetting pkgSetting;
14949        final int callingUid = Binder.getCallingUid();
14950        enforceCrossUserPermission(callingUid, userId,
14951                true /* requireFullPermission */, true /* checkShell */,
14952                "setApplicationHiddenSetting for user " + userId);
14953
14954        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14955            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14956            return false;
14957        }
14958
14959        long callingId = Binder.clearCallingIdentity();
14960        try {
14961            boolean sendAdded = false;
14962            boolean sendRemoved = false;
14963            // writer
14964            synchronized (mPackages) {
14965                pkgSetting = mSettings.mPackages.get(packageName);
14966                if (pkgSetting == null) {
14967                    return false;
14968                }
14969                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14970                    return false;
14971                }
14972                // Do not allow "android" is being disabled
14973                if ("android".equals(packageName)) {
14974                    Slog.w(TAG, "Cannot hide package: android");
14975                    return false;
14976                }
14977                // Cannot hide static shared libs as they are considered
14978                // a part of the using app (emulating static linking). Also
14979                // static libs are installed always on internal storage.
14980                PackageParser.Package pkg = mPackages.get(packageName);
14981                if (pkg != null && pkg.staticSharedLibName != null) {
14982                    Slog.w(TAG, "Cannot hide package: " + packageName
14983                            + " providing static shared library: "
14984                            + pkg.staticSharedLibName);
14985                    return false;
14986                }
14987                // Only allow protected packages to hide themselves.
14988                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14989                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14990                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14991                    return false;
14992                }
14993
14994                if (pkgSetting.getHidden(userId) != hidden) {
14995                    pkgSetting.setHidden(hidden, userId);
14996                    mSettings.writePackageRestrictionsLPr(userId);
14997                    if (hidden) {
14998                        sendRemoved = true;
14999                    } else {
15000                        sendAdded = true;
15001                    }
15002                }
15003            }
15004            if (sendAdded) {
15005                sendPackageAddedForUser(packageName, pkgSetting, userId);
15006                return true;
15007            }
15008            if (sendRemoved) {
15009                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
15010                        "hiding pkg");
15011                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
15012                return true;
15013            }
15014        } finally {
15015            Binder.restoreCallingIdentity(callingId);
15016        }
15017        return false;
15018    }
15019
15020    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
15021            int userId) {
15022        final PackageRemovedInfo info = new PackageRemovedInfo(this);
15023        info.removedPackage = packageName;
15024        info.installerPackageName = pkgSetting.installerPackageName;
15025        info.removedUsers = new int[] {userId};
15026        info.broadcastUsers = new int[] {userId};
15027        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
15028        info.sendPackageRemovedBroadcasts(true /*killApp*/);
15029    }
15030
15031    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
15032        if (pkgList.length > 0) {
15033            Bundle extras = new Bundle(1);
15034            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15035
15036            sendPackageBroadcast(
15037                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
15038                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
15039                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
15040                    new int[] {userId});
15041        }
15042    }
15043
15044    /**
15045     * Returns true if application is not found or there was an error. Otherwise it returns
15046     * the hidden state of the package for the given user.
15047     */
15048    @Override
15049    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
15050        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15051        final int callingUid = Binder.getCallingUid();
15052        enforceCrossUserPermission(callingUid, userId,
15053                true /* requireFullPermission */, false /* checkShell */,
15054                "getApplicationHidden for user " + userId);
15055        PackageSetting ps;
15056        long callingId = Binder.clearCallingIdentity();
15057        try {
15058            // writer
15059            synchronized (mPackages) {
15060                ps = mSettings.mPackages.get(packageName);
15061                if (ps == null) {
15062                    return true;
15063                }
15064                if (filterAppAccessLPr(ps, callingUid, userId)) {
15065                    return true;
15066                }
15067                return ps.getHidden(userId);
15068            }
15069        } finally {
15070            Binder.restoreCallingIdentity(callingId);
15071        }
15072    }
15073
15074    /**
15075     * @hide
15076     */
15077    @Override
15078    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15079            int installReason) {
15080        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15081                null);
15082        PackageSetting pkgSetting;
15083        final int callingUid = Binder.getCallingUid();
15084        enforceCrossUserPermission(callingUid, userId,
15085                true /* requireFullPermission */, true /* checkShell */,
15086                "installExistingPackage for user " + userId);
15087        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15088            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15089        }
15090
15091        long callingId = Binder.clearCallingIdentity();
15092        try {
15093            boolean installed = false;
15094            final boolean instantApp =
15095                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15096            final boolean fullApp =
15097                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15098
15099            // writer
15100            synchronized (mPackages) {
15101                pkgSetting = mSettings.mPackages.get(packageName);
15102                if (pkgSetting == null) {
15103                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15104                }
15105                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15106                    // only allow the existing package to be used if it's installed as a full
15107                    // application for at least one user
15108                    boolean installAllowed = false;
15109                    for (int checkUserId : sUserManager.getUserIds()) {
15110                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15111                        if (installAllowed) {
15112                            break;
15113                        }
15114                    }
15115                    if (!installAllowed) {
15116                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15117                    }
15118                }
15119                if (!pkgSetting.getInstalled(userId)) {
15120                    pkgSetting.setInstalled(true, userId);
15121                    pkgSetting.setHidden(false, userId);
15122                    pkgSetting.setInstallReason(installReason, userId);
15123                    mSettings.writePackageRestrictionsLPr(userId);
15124                    mSettings.writeKernelMappingLPr(pkgSetting);
15125                    installed = true;
15126                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15127                    // upgrade app from instant to full; we don't allow app downgrade
15128                    installed = true;
15129                }
15130                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15131            }
15132
15133            if (installed) {
15134                if (pkgSetting.pkg != null) {
15135                    synchronized (mInstallLock) {
15136                        // We don't need to freeze for a brand new install
15137                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15138                    }
15139                }
15140                sendPackageAddedForUser(packageName, pkgSetting, userId);
15141                synchronized (mPackages) {
15142                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15143                }
15144            }
15145        } finally {
15146            Binder.restoreCallingIdentity(callingId);
15147        }
15148
15149        return PackageManager.INSTALL_SUCCEEDED;
15150    }
15151
15152    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15153            boolean instantApp, boolean fullApp) {
15154        // no state specified; do nothing
15155        if (!instantApp && !fullApp) {
15156            return;
15157        }
15158        if (userId != UserHandle.USER_ALL) {
15159            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15160                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15161            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15162                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15163            }
15164        } else {
15165            for (int currentUserId : sUserManager.getUserIds()) {
15166                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15167                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15168                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15169                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15170                }
15171            }
15172        }
15173    }
15174
15175    boolean isUserRestricted(int userId, String restrictionKey) {
15176        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15177        if (restrictions.getBoolean(restrictionKey, false)) {
15178            Log.w(TAG, "User is restricted: " + restrictionKey);
15179            return true;
15180        }
15181        return false;
15182    }
15183
15184    @Override
15185    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15186            int userId) {
15187        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15188        final int callingUid = Binder.getCallingUid();
15189        enforceCrossUserPermission(callingUid, userId,
15190                true /* requireFullPermission */, true /* checkShell */,
15191                "setPackagesSuspended for user " + userId);
15192
15193        if (ArrayUtils.isEmpty(packageNames)) {
15194            return packageNames;
15195        }
15196
15197        // List of package names for whom the suspended state has changed.
15198        List<String> changedPackages = new ArrayList<>(packageNames.length);
15199        // List of package names for whom the suspended state is not set as requested in this
15200        // method.
15201        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15202        long callingId = Binder.clearCallingIdentity();
15203        try {
15204            for (int i = 0; i < packageNames.length; i++) {
15205                String packageName = packageNames[i];
15206                boolean changed = false;
15207                final int appId;
15208                synchronized (mPackages) {
15209                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15210                    if (pkgSetting == null
15211                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15212                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15213                                + "\". Skipping suspending/un-suspending.");
15214                        unactionedPackages.add(packageName);
15215                        continue;
15216                    }
15217                    appId = pkgSetting.appId;
15218                    if (pkgSetting.getSuspended(userId) != suspended) {
15219                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15220                            unactionedPackages.add(packageName);
15221                            continue;
15222                        }
15223                        pkgSetting.setSuspended(suspended, userId);
15224                        mSettings.writePackageRestrictionsLPr(userId);
15225                        changed = true;
15226                        changedPackages.add(packageName);
15227                    }
15228                }
15229
15230                if (changed && suspended) {
15231                    killApplication(packageName, UserHandle.getUid(userId, appId),
15232                            "suspending package");
15233                }
15234            }
15235        } finally {
15236            Binder.restoreCallingIdentity(callingId);
15237        }
15238
15239        if (!changedPackages.isEmpty()) {
15240            sendPackagesSuspendedForUser(changedPackages.toArray(
15241                    new String[changedPackages.size()]), userId, suspended);
15242        }
15243
15244        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15245    }
15246
15247    @Override
15248    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15249        final int callingUid = Binder.getCallingUid();
15250        enforceCrossUserPermission(callingUid, userId,
15251                true /* requireFullPermission */, false /* checkShell */,
15252                "isPackageSuspendedForUser for user " + userId);
15253        synchronized (mPackages) {
15254            final PackageSetting ps = mSettings.mPackages.get(packageName);
15255            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15256                throw new IllegalArgumentException("Unknown target package: " + packageName);
15257            }
15258            return ps.getSuspended(userId);
15259        }
15260    }
15261
15262    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15263        if (isPackageDeviceAdmin(packageName, userId)) {
15264            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15265                    + "\": has an active device admin");
15266            return false;
15267        }
15268
15269        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15270        if (packageName.equals(activeLauncherPackageName)) {
15271            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15272                    + "\": contains the active launcher");
15273            return false;
15274        }
15275
15276        if (packageName.equals(mRequiredInstallerPackage)) {
15277            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15278                    + "\": required for package installation");
15279            return false;
15280        }
15281
15282        if (packageName.equals(mRequiredUninstallerPackage)) {
15283            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15284                    + "\": required for package uninstallation");
15285            return false;
15286        }
15287
15288        if (packageName.equals(mRequiredVerifierPackage)) {
15289            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15290                    + "\": required for package verification");
15291            return false;
15292        }
15293
15294        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15295            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15296                    + "\": is the default dialer");
15297            return false;
15298        }
15299
15300        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15301            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15302                    + "\": protected package");
15303            return false;
15304        }
15305
15306        // Cannot suspend static shared libs as they are considered
15307        // a part of the using app (emulating static linking). Also
15308        // static libs are installed always on internal storage.
15309        PackageParser.Package pkg = mPackages.get(packageName);
15310        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15311            Slog.w(TAG, "Cannot suspend package: " + packageName
15312                    + " providing static shared library: "
15313                    + pkg.staticSharedLibName);
15314            return false;
15315        }
15316
15317        return true;
15318    }
15319
15320    private String getActiveLauncherPackageName(int userId) {
15321        Intent intent = new Intent(Intent.ACTION_MAIN);
15322        intent.addCategory(Intent.CATEGORY_HOME);
15323        ResolveInfo resolveInfo = resolveIntent(
15324                intent,
15325                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15326                PackageManager.MATCH_DEFAULT_ONLY,
15327                userId);
15328
15329        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15330    }
15331
15332    private String getDefaultDialerPackageName(int userId) {
15333        synchronized (mPackages) {
15334            return mSettings.getDefaultDialerPackageNameLPw(userId);
15335        }
15336    }
15337
15338    @Override
15339    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15340        mContext.enforceCallingOrSelfPermission(
15341                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15342                "Only package verification agents can verify applications");
15343
15344        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15345        final PackageVerificationResponse response = new PackageVerificationResponse(
15346                verificationCode, Binder.getCallingUid());
15347        msg.arg1 = id;
15348        msg.obj = response;
15349        mHandler.sendMessage(msg);
15350    }
15351
15352    @Override
15353    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15354            long millisecondsToDelay) {
15355        mContext.enforceCallingOrSelfPermission(
15356                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15357                "Only package verification agents can extend verification timeouts");
15358
15359        final PackageVerificationState state = mPendingVerification.get(id);
15360        final PackageVerificationResponse response = new PackageVerificationResponse(
15361                verificationCodeAtTimeout, Binder.getCallingUid());
15362
15363        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15364            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15365        }
15366        if (millisecondsToDelay < 0) {
15367            millisecondsToDelay = 0;
15368        }
15369        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15370                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15371            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15372        }
15373
15374        if ((state != null) && !state.timeoutExtended()) {
15375            state.extendTimeout();
15376
15377            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15378            msg.arg1 = id;
15379            msg.obj = response;
15380            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15381        }
15382    }
15383
15384    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15385            int verificationCode, UserHandle user) {
15386        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15387        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15388        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15389        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15390        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15391
15392        mContext.sendBroadcastAsUser(intent, user,
15393                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15394    }
15395
15396    private ComponentName matchComponentForVerifier(String packageName,
15397            List<ResolveInfo> receivers) {
15398        ActivityInfo targetReceiver = null;
15399
15400        final int NR = receivers.size();
15401        for (int i = 0; i < NR; i++) {
15402            final ResolveInfo info = receivers.get(i);
15403            if (info.activityInfo == null) {
15404                continue;
15405            }
15406
15407            if (packageName.equals(info.activityInfo.packageName)) {
15408                targetReceiver = info.activityInfo;
15409                break;
15410            }
15411        }
15412
15413        if (targetReceiver == null) {
15414            return null;
15415        }
15416
15417        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15418    }
15419
15420    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15421            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15422        if (pkgInfo.verifiers.length == 0) {
15423            return null;
15424        }
15425
15426        final int N = pkgInfo.verifiers.length;
15427        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15428        for (int i = 0; i < N; i++) {
15429            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15430
15431            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15432                    receivers);
15433            if (comp == null) {
15434                continue;
15435            }
15436
15437            final int verifierUid = getUidForVerifier(verifierInfo);
15438            if (verifierUid == -1) {
15439                continue;
15440            }
15441
15442            if (DEBUG_VERIFY) {
15443                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15444                        + " with the correct signature");
15445            }
15446            sufficientVerifiers.add(comp);
15447            verificationState.addSufficientVerifier(verifierUid);
15448        }
15449
15450        return sufficientVerifiers;
15451    }
15452
15453    private int getUidForVerifier(VerifierInfo verifierInfo) {
15454        synchronized (mPackages) {
15455            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15456            if (pkg == null) {
15457                return -1;
15458            } else if (pkg.mSignatures.length != 1) {
15459                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15460                        + " has more than one signature; ignoring");
15461                return -1;
15462            }
15463
15464            /*
15465             * If the public key of the package's signature does not match
15466             * our expected public key, then this is a different package and
15467             * we should skip.
15468             */
15469
15470            final byte[] expectedPublicKey;
15471            try {
15472                final Signature verifierSig = pkg.mSignatures[0];
15473                final PublicKey publicKey = verifierSig.getPublicKey();
15474                expectedPublicKey = publicKey.getEncoded();
15475            } catch (CertificateException e) {
15476                return -1;
15477            }
15478
15479            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15480
15481            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15482                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15483                        + " does not have the expected public key; ignoring");
15484                return -1;
15485            }
15486
15487            return pkg.applicationInfo.uid;
15488        }
15489    }
15490
15491    @Override
15492    public void finishPackageInstall(int token, boolean didLaunch) {
15493        enforceSystemOrRoot("Only the system is allowed to finish installs");
15494
15495        if (DEBUG_INSTALL) {
15496            Slog.v(TAG, "BM finishing package install for " + token);
15497        }
15498        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15499
15500        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15501        mHandler.sendMessage(msg);
15502    }
15503
15504    /**
15505     * Get the verification agent timeout.  Used for both the APK verifier and the
15506     * intent filter verifier.
15507     *
15508     * @return verification timeout in milliseconds
15509     */
15510    private long getVerificationTimeout() {
15511        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15512                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15513                DEFAULT_VERIFICATION_TIMEOUT);
15514    }
15515
15516    /**
15517     * Get the default verification agent response code.
15518     *
15519     * @return default verification response code
15520     */
15521    private int getDefaultVerificationResponse(UserHandle user) {
15522        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15523            return PackageManager.VERIFICATION_REJECT;
15524        }
15525        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15526                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15527                DEFAULT_VERIFICATION_RESPONSE);
15528    }
15529
15530    /**
15531     * Check whether or not package verification has been enabled.
15532     *
15533     * @return true if verification should be performed
15534     */
15535    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15536        if (!DEFAULT_VERIFY_ENABLE) {
15537            return false;
15538        }
15539
15540        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15541
15542        // Check if installing from ADB
15543        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15544            // Do not run verification in a test harness environment
15545            if (ActivityManager.isRunningInTestHarness()) {
15546                return false;
15547            }
15548            if (ensureVerifyAppsEnabled) {
15549                return true;
15550            }
15551            // Check if the developer does not want package verification for ADB installs
15552            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15553                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15554                return false;
15555            }
15556        } else {
15557            // only when not installed from ADB, skip verification for instant apps when
15558            // the installer and verifier are the same.
15559            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15560                if (mInstantAppInstallerActivity != null
15561                        && mInstantAppInstallerActivity.packageName.equals(
15562                                mRequiredVerifierPackage)) {
15563                    try {
15564                        mContext.getSystemService(AppOpsManager.class)
15565                                .checkPackage(installerUid, mRequiredVerifierPackage);
15566                        if (DEBUG_VERIFY) {
15567                            Slog.i(TAG, "disable verification for instant app");
15568                        }
15569                        return false;
15570                    } catch (SecurityException ignore) { }
15571                }
15572            }
15573        }
15574
15575        if (ensureVerifyAppsEnabled) {
15576            return true;
15577        }
15578
15579        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15580                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15581    }
15582
15583    @Override
15584    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15585            throws RemoteException {
15586        mContext.enforceCallingOrSelfPermission(
15587                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15588                "Only intentfilter verification agents can verify applications");
15589
15590        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15591        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15592                Binder.getCallingUid(), verificationCode, failedDomains);
15593        msg.arg1 = id;
15594        msg.obj = response;
15595        mHandler.sendMessage(msg);
15596    }
15597
15598    @Override
15599    public int getIntentVerificationStatus(String packageName, int userId) {
15600        final int callingUid = Binder.getCallingUid();
15601        if (UserHandle.getUserId(callingUid) != userId) {
15602            mContext.enforceCallingOrSelfPermission(
15603                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15604                    "getIntentVerificationStatus" + userId);
15605        }
15606        if (getInstantAppPackageName(callingUid) != null) {
15607            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15608        }
15609        synchronized (mPackages) {
15610            final PackageSetting ps = mSettings.mPackages.get(packageName);
15611            if (ps == null
15612                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15613                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15614            }
15615            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15616        }
15617    }
15618
15619    @Override
15620    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15621        mContext.enforceCallingOrSelfPermission(
15622                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15623
15624        boolean result = false;
15625        synchronized (mPackages) {
15626            final PackageSetting ps = mSettings.mPackages.get(packageName);
15627            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15628                return false;
15629            }
15630            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15631        }
15632        if (result) {
15633            scheduleWritePackageRestrictionsLocked(userId);
15634        }
15635        return result;
15636    }
15637
15638    @Override
15639    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15640            String packageName) {
15641        final int callingUid = Binder.getCallingUid();
15642        if (getInstantAppPackageName(callingUid) != null) {
15643            return ParceledListSlice.emptyList();
15644        }
15645        synchronized (mPackages) {
15646            final PackageSetting ps = mSettings.mPackages.get(packageName);
15647            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15648                return ParceledListSlice.emptyList();
15649            }
15650            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15651        }
15652    }
15653
15654    @Override
15655    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15656        if (TextUtils.isEmpty(packageName)) {
15657            return ParceledListSlice.emptyList();
15658        }
15659        final int callingUid = Binder.getCallingUid();
15660        final int callingUserId = UserHandle.getUserId(callingUid);
15661        synchronized (mPackages) {
15662            PackageParser.Package pkg = mPackages.get(packageName);
15663            if (pkg == null || pkg.activities == null) {
15664                return ParceledListSlice.emptyList();
15665            }
15666            if (pkg.mExtras == null) {
15667                return ParceledListSlice.emptyList();
15668            }
15669            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15670            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15671                return ParceledListSlice.emptyList();
15672            }
15673            final int count = pkg.activities.size();
15674            ArrayList<IntentFilter> result = new ArrayList<>();
15675            for (int n=0; n<count; n++) {
15676                PackageParser.Activity activity = pkg.activities.get(n);
15677                if (activity.intents != null && activity.intents.size() > 0) {
15678                    result.addAll(activity.intents);
15679                }
15680            }
15681            return new ParceledListSlice<>(result);
15682        }
15683    }
15684
15685    @Override
15686    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15687        mContext.enforceCallingOrSelfPermission(
15688                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15689        if (UserHandle.getCallingUserId() != userId) {
15690            mContext.enforceCallingOrSelfPermission(
15691                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15692        }
15693
15694        synchronized (mPackages) {
15695            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15696            if (packageName != null) {
15697                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15698                        packageName, userId);
15699            }
15700            return result;
15701        }
15702    }
15703
15704    @Override
15705    public String getDefaultBrowserPackageName(int userId) {
15706        if (UserHandle.getCallingUserId() != userId) {
15707            mContext.enforceCallingOrSelfPermission(
15708                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15709        }
15710        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15711            return null;
15712        }
15713        synchronized (mPackages) {
15714            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15715        }
15716    }
15717
15718    /**
15719     * Get the "allow unknown sources" setting.
15720     *
15721     * @return the current "allow unknown sources" setting
15722     */
15723    private int getUnknownSourcesSettings() {
15724        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15725                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15726                -1);
15727    }
15728
15729    @Override
15730    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15731        final int callingUid = Binder.getCallingUid();
15732        if (getInstantAppPackageName(callingUid) != null) {
15733            return;
15734        }
15735        // writer
15736        synchronized (mPackages) {
15737            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15738            if (targetPackageSetting == null
15739                    || filterAppAccessLPr(
15740                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15741                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15742            }
15743
15744            PackageSetting installerPackageSetting;
15745            if (installerPackageName != null) {
15746                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15747                if (installerPackageSetting == null) {
15748                    throw new IllegalArgumentException("Unknown installer package: "
15749                            + installerPackageName);
15750                }
15751            } else {
15752                installerPackageSetting = null;
15753            }
15754
15755            Signature[] callerSignature;
15756            Object obj = mSettings.getUserIdLPr(callingUid);
15757            if (obj != null) {
15758                if (obj instanceof SharedUserSetting) {
15759                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15760                } else if (obj instanceof PackageSetting) {
15761                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15762                } else {
15763                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15764                }
15765            } else {
15766                throw new SecurityException("Unknown calling UID: " + callingUid);
15767            }
15768
15769            // Verify: can't set installerPackageName to a package that is
15770            // not signed with the same cert as the caller.
15771            if (installerPackageSetting != null) {
15772                if (compareSignatures(callerSignature,
15773                        installerPackageSetting.signatures.mSignatures)
15774                        != PackageManager.SIGNATURE_MATCH) {
15775                    throw new SecurityException(
15776                            "Caller does not have same cert as new installer package "
15777                            + installerPackageName);
15778                }
15779            }
15780
15781            // Verify: if target already has an installer package, it must
15782            // be signed with the same cert as the caller.
15783            if (targetPackageSetting.installerPackageName != null) {
15784                PackageSetting setting = mSettings.mPackages.get(
15785                        targetPackageSetting.installerPackageName);
15786                // If the currently set package isn't valid, then it's always
15787                // okay to change it.
15788                if (setting != null) {
15789                    if (compareSignatures(callerSignature,
15790                            setting.signatures.mSignatures)
15791                            != PackageManager.SIGNATURE_MATCH) {
15792                        throw new SecurityException(
15793                                "Caller does not have same cert as old installer package "
15794                                + targetPackageSetting.installerPackageName);
15795                    }
15796                }
15797            }
15798
15799            // Okay!
15800            targetPackageSetting.installerPackageName = installerPackageName;
15801            if (installerPackageName != null) {
15802                mSettings.mInstallerPackages.add(installerPackageName);
15803            }
15804            scheduleWriteSettingsLocked();
15805        }
15806    }
15807
15808    @Override
15809    public void setApplicationCategoryHint(String packageName, int categoryHint,
15810            String callerPackageName) {
15811        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15812            throw new SecurityException("Instant applications don't have access to this method");
15813        }
15814        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15815                callerPackageName);
15816        synchronized (mPackages) {
15817            PackageSetting ps = mSettings.mPackages.get(packageName);
15818            if (ps == null) {
15819                throw new IllegalArgumentException("Unknown target package " + packageName);
15820            }
15821            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15822                throw new IllegalArgumentException("Unknown target package " + packageName);
15823            }
15824            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15825                throw new IllegalArgumentException("Calling package " + callerPackageName
15826                        + " is not installer for " + packageName);
15827            }
15828
15829            if (ps.categoryHint != categoryHint) {
15830                ps.categoryHint = categoryHint;
15831                scheduleWriteSettingsLocked();
15832            }
15833        }
15834    }
15835
15836    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15837        // Queue up an async operation since the package installation may take a little while.
15838        mHandler.post(new Runnable() {
15839            public void run() {
15840                mHandler.removeCallbacks(this);
15841                 // Result object to be returned
15842                PackageInstalledInfo res = new PackageInstalledInfo();
15843                res.setReturnCode(currentStatus);
15844                res.uid = -1;
15845                res.pkg = null;
15846                res.removedInfo = null;
15847                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15848                    args.doPreInstall(res.returnCode);
15849                    synchronized (mInstallLock) {
15850                        installPackageTracedLI(args, res);
15851                    }
15852                    args.doPostInstall(res.returnCode, res.uid);
15853                }
15854
15855                // A restore should be performed at this point if (a) the install
15856                // succeeded, (b) the operation is not an update, and (c) the new
15857                // package has not opted out of backup participation.
15858                final boolean update = res.removedInfo != null
15859                        && res.removedInfo.removedPackage != null;
15860                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15861                boolean doRestore = !update
15862                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15863
15864                // Set up the post-install work request bookkeeping.  This will be used
15865                // and cleaned up by the post-install event handling regardless of whether
15866                // there's a restore pass performed.  Token values are >= 1.
15867                int token;
15868                if (mNextInstallToken < 0) mNextInstallToken = 1;
15869                token = mNextInstallToken++;
15870
15871                PostInstallData data = new PostInstallData(args, res);
15872                mRunningInstalls.put(token, data);
15873                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15874
15875                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15876                    // Pass responsibility to the Backup Manager.  It will perform a
15877                    // restore if appropriate, then pass responsibility back to the
15878                    // Package Manager to run the post-install observer callbacks
15879                    // and broadcasts.
15880                    IBackupManager bm = IBackupManager.Stub.asInterface(
15881                            ServiceManager.getService(Context.BACKUP_SERVICE));
15882                    if (bm != null) {
15883                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15884                                + " to BM for possible restore");
15885                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15886                        try {
15887                            // TODO: http://b/22388012
15888                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15889                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15890                            } else {
15891                                doRestore = false;
15892                            }
15893                        } catch (RemoteException e) {
15894                            // can't happen; the backup manager is local
15895                        } catch (Exception e) {
15896                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15897                            doRestore = false;
15898                        }
15899                    } else {
15900                        Slog.e(TAG, "Backup Manager not found!");
15901                        doRestore = false;
15902                    }
15903                }
15904
15905                if (!doRestore) {
15906                    // No restore possible, or the Backup Manager was mysteriously not
15907                    // available -- just fire the post-install work request directly.
15908                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15909
15910                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15911
15912                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15913                    mHandler.sendMessage(msg);
15914                }
15915            }
15916        });
15917    }
15918
15919    /**
15920     * Callback from PackageSettings whenever an app is first transitioned out of the
15921     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15922     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15923     * here whether the app is the target of an ongoing install, and only send the
15924     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15925     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15926     * handling.
15927     */
15928    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15929        // Serialize this with the rest of the install-process message chain.  In the
15930        // restore-at-install case, this Runnable will necessarily run before the
15931        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15932        // are coherent.  In the non-restore case, the app has already completed install
15933        // and been launched through some other means, so it is not in a problematic
15934        // state for observers to see the FIRST_LAUNCH signal.
15935        mHandler.post(new Runnable() {
15936            @Override
15937            public void run() {
15938                for (int i = 0; i < mRunningInstalls.size(); i++) {
15939                    final PostInstallData data = mRunningInstalls.valueAt(i);
15940                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15941                        continue;
15942                    }
15943                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15944                        // right package; but is it for the right user?
15945                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15946                            if (userId == data.res.newUsers[uIndex]) {
15947                                if (DEBUG_BACKUP) {
15948                                    Slog.i(TAG, "Package " + pkgName
15949                                            + " being restored so deferring FIRST_LAUNCH");
15950                                }
15951                                return;
15952                            }
15953                        }
15954                    }
15955                }
15956                // didn't find it, so not being restored
15957                if (DEBUG_BACKUP) {
15958                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15959                }
15960                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15961            }
15962        });
15963    }
15964
15965    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15966        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15967                installerPkg, null, userIds);
15968    }
15969
15970    private abstract class HandlerParams {
15971        private static final int MAX_RETRIES = 4;
15972
15973        /**
15974         * Number of times startCopy() has been attempted and had a non-fatal
15975         * error.
15976         */
15977        private int mRetries = 0;
15978
15979        /** User handle for the user requesting the information or installation. */
15980        private final UserHandle mUser;
15981        String traceMethod;
15982        int traceCookie;
15983
15984        HandlerParams(UserHandle user) {
15985            mUser = user;
15986        }
15987
15988        UserHandle getUser() {
15989            return mUser;
15990        }
15991
15992        HandlerParams setTraceMethod(String traceMethod) {
15993            this.traceMethod = traceMethod;
15994            return this;
15995        }
15996
15997        HandlerParams setTraceCookie(int traceCookie) {
15998            this.traceCookie = traceCookie;
15999            return this;
16000        }
16001
16002        final boolean startCopy() {
16003            boolean res;
16004            try {
16005                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
16006
16007                if (++mRetries > MAX_RETRIES) {
16008                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
16009                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
16010                    handleServiceError();
16011                    return false;
16012                } else {
16013                    handleStartCopy();
16014                    res = true;
16015                }
16016            } catch (RemoteException e) {
16017                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
16018                mHandler.sendEmptyMessage(MCS_RECONNECT);
16019                res = false;
16020            }
16021            handleReturnCode();
16022            return res;
16023        }
16024
16025        final void serviceError() {
16026            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
16027            handleServiceError();
16028            handleReturnCode();
16029        }
16030
16031        abstract void handleStartCopy() throws RemoteException;
16032        abstract void handleServiceError();
16033        abstract void handleReturnCode();
16034    }
16035
16036    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
16037        for (File path : paths) {
16038            try {
16039                mcs.clearDirectory(path.getAbsolutePath());
16040            } catch (RemoteException e) {
16041            }
16042        }
16043    }
16044
16045    static class OriginInfo {
16046        /**
16047         * Location where install is coming from, before it has been
16048         * copied/renamed into place. This could be a single monolithic APK
16049         * file, or a cluster directory. This location may be untrusted.
16050         */
16051        final File file;
16052
16053        /**
16054         * Flag indicating that {@link #file} or {@link #cid} has already been
16055         * staged, meaning downstream users don't need to defensively copy the
16056         * contents.
16057         */
16058        final boolean staged;
16059
16060        /**
16061         * Flag indicating that {@link #file} or {@link #cid} is an already
16062         * installed app that is being moved.
16063         */
16064        final boolean existing;
16065
16066        final String resolvedPath;
16067        final File resolvedFile;
16068
16069        static OriginInfo fromNothing() {
16070            return new OriginInfo(null, false, false);
16071        }
16072
16073        static OriginInfo fromUntrustedFile(File file) {
16074            return new OriginInfo(file, false, false);
16075        }
16076
16077        static OriginInfo fromExistingFile(File file) {
16078            return new OriginInfo(file, false, true);
16079        }
16080
16081        static OriginInfo fromStagedFile(File file) {
16082            return new OriginInfo(file, true, false);
16083        }
16084
16085        private OriginInfo(File file, boolean staged, boolean existing) {
16086            this.file = file;
16087            this.staged = staged;
16088            this.existing = existing;
16089
16090            if (file != null) {
16091                resolvedPath = file.getAbsolutePath();
16092                resolvedFile = file;
16093            } else {
16094                resolvedPath = null;
16095                resolvedFile = null;
16096            }
16097        }
16098    }
16099
16100    static class MoveInfo {
16101        final int moveId;
16102        final String fromUuid;
16103        final String toUuid;
16104        final String packageName;
16105        final String dataAppName;
16106        final int appId;
16107        final String seinfo;
16108        final int targetSdkVersion;
16109
16110        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16111                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16112            this.moveId = moveId;
16113            this.fromUuid = fromUuid;
16114            this.toUuid = toUuid;
16115            this.packageName = packageName;
16116            this.dataAppName = dataAppName;
16117            this.appId = appId;
16118            this.seinfo = seinfo;
16119            this.targetSdkVersion = targetSdkVersion;
16120        }
16121    }
16122
16123    static class VerificationInfo {
16124        /** A constant used to indicate that a uid value is not present. */
16125        public static final int NO_UID = -1;
16126
16127        /** URI referencing where the package was downloaded from. */
16128        final Uri originatingUri;
16129
16130        /** HTTP referrer URI associated with the originatingURI. */
16131        final Uri referrer;
16132
16133        /** UID of the application that the install request originated from. */
16134        final int originatingUid;
16135
16136        /** UID of application requesting the install */
16137        final int installerUid;
16138
16139        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16140            this.originatingUri = originatingUri;
16141            this.referrer = referrer;
16142            this.originatingUid = originatingUid;
16143            this.installerUid = installerUid;
16144        }
16145    }
16146
16147    class InstallParams extends HandlerParams {
16148        final OriginInfo origin;
16149        final MoveInfo move;
16150        final IPackageInstallObserver2 observer;
16151        int installFlags;
16152        final String installerPackageName;
16153        final String volumeUuid;
16154        private InstallArgs mArgs;
16155        private int mRet;
16156        final String packageAbiOverride;
16157        final String[] grantedRuntimePermissions;
16158        final VerificationInfo verificationInfo;
16159        final Certificate[][] certificates;
16160        final int installReason;
16161
16162        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16163                int installFlags, String installerPackageName, String volumeUuid,
16164                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16165                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16166            super(user);
16167            this.origin = origin;
16168            this.move = move;
16169            this.observer = observer;
16170            this.installFlags = installFlags;
16171            this.installerPackageName = installerPackageName;
16172            this.volumeUuid = volumeUuid;
16173            this.verificationInfo = verificationInfo;
16174            this.packageAbiOverride = packageAbiOverride;
16175            this.grantedRuntimePermissions = grantedPermissions;
16176            this.certificates = certificates;
16177            this.installReason = installReason;
16178        }
16179
16180        @Override
16181        public String toString() {
16182            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16183                    + " file=" + origin.file + "}";
16184        }
16185
16186        private int installLocationPolicy(PackageInfoLite pkgLite) {
16187            String packageName = pkgLite.packageName;
16188            int installLocation = pkgLite.installLocation;
16189            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16190            // reader
16191            synchronized (mPackages) {
16192                // Currently installed package which the new package is attempting to replace or
16193                // null if no such package is installed.
16194                PackageParser.Package installedPkg = mPackages.get(packageName);
16195                // Package which currently owns the data which the new package will own if installed.
16196                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16197                // will be null whereas dataOwnerPkg will contain information about the package
16198                // which was uninstalled while keeping its data.
16199                PackageParser.Package dataOwnerPkg = installedPkg;
16200                if (dataOwnerPkg  == null) {
16201                    PackageSetting ps = mSettings.mPackages.get(packageName);
16202                    if (ps != null) {
16203                        dataOwnerPkg = ps.pkg;
16204                    }
16205                }
16206
16207                if (dataOwnerPkg != null) {
16208                    // If installed, the package will get access to data left on the device by its
16209                    // predecessor. As a security measure, this is permited only if this is not a
16210                    // version downgrade or if the predecessor package is marked as debuggable and
16211                    // a downgrade is explicitly requested.
16212                    //
16213                    // On debuggable platform builds, downgrades are permitted even for
16214                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16215                    // not offer security guarantees and thus it's OK to disable some security
16216                    // mechanisms to make debugging/testing easier on those builds. However, even on
16217                    // debuggable builds downgrades of packages are permitted only if requested via
16218                    // installFlags. This is because we aim to keep the behavior of debuggable
16219                    // platform builds as close as possible to the behavior of non-debuggable
16220                    // platform builds.
16221                    final boolean downgradeRequested =
16222                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16223                    final boolean packageDebuggable =
16224                                (dataOwnerPkg.applicationInfo.flags
16225                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16226                    final boolean downgradePermitted =
16227                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16228                    if (!downgradePermitted) {
16229                        try {
16230                            checkDowngrade(dataOwnerPkg, pkgLite);
16231                        } catch (PackageManagerException e) {
16232                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16233                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16234                        }
16235                    }
16236                }
16237
16238                if (installedPkg != null) {
16239                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16240                        // Check for updated system application.
16241                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16242                            if (onSd) {
16243                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16244                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16245                            }
16246                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16247                        } else {
16248                            if (onSd) {
16249                                // Install flag overrides everything.
16250                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16251                            }
16252                            // If current upgrade specifies particular preference
16253                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16254                                // Application explicitly specified internal.
16255                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16256                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16257                                // App explictly prefers external. Let policy decide
16258                            } else {
16259                                // Prefer previous location
16260                                if (isExternal(installedPkg)) {
16261                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16262                                }
16263                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16264                            }
16265                        }
16266                    } else {
16267                        // Invalid install. Return error code
16268                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16269                    }
16270                }
16271            }
16272            // All the special cases have been taken care of.
16273            // Return result based on recommended install location.
16274            if (onSd) {
16275                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16276            }
16277            return pkgLite.recommendedInstallLocation;
16278        }
16279
16280        /*
16281         * Invoke remote method to get package information and install
16282         * location values. Override install location based on default
16283         * policy if needed and then create install arguments based
16284         * on the install location.
16285         */
16286        public void handleStartCopy() throws RemoteException {
16287            int ret = PackageManager.INSTALL_SUCCEEDED;
16288
16289            // If we're already staged, we've firmly committed to an install location
16290            if (origin.staged) {
16291                if (origin.file != null) {
16292                    installFlags |= PackageManager.INSTALL_INTERNAL;
16293                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16294                } else {
16295                    throw new IllegalStateException("Invalid stage location");
16296                }
16297            }
16298
16299            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16300            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16301            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16302            PackageInfoLite pkgLite = null;
16303
16304            if (onInt && onSd) {
16305                // Check if both bits are set.
16306                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16307                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16308            } else if (onSd && ephemeral) {
16309                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16310                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16311            } else {
16312                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16313                        packageAbiOverride);
16314
16315                if (DEBUG_EPHEMERAL && ephemeral) {
16316                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16317                }
16318
16319                /*
16320                 * If we have too little free space, try to free cache
16321                 * before giving up.
16322                 */
16323                if (!origin.staged && pkgLite.recommendedInstallLocation
16324                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16325                    // TODO: focus freeing disk space on the target device
16326                    final StorageManager storage = StorageManager.from(mContext);
16327                    final long lowThreshold = storage.getStorageLowBytes(
16328                            Environment.getDataDirectory());
16329
16330                    final long sizeBytes = mContainerService.calculateInstalledSize(
16331                            origin.resolvedPath, packageAbiOverride);
16332
16333                    try {
16334                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16335                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16336                                installFlags, packageAbiOverride);
16337                    } catch (InstallerException e) {
16338                        Slog.w(TAG, "Failed to free cache", e);
16339                    }
16340
16341                    /*
16342                     * The cache free must have deleted the file we
16343                     * downloaded to install.
16344                     *
16345                     * TODO: fix the "freeCache" call to not delete
16346                     *       the file we care about.
16347                     */
16348                    if (pkgLite.recommendedInstallLocation
16349                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16350                        pkgLite.recommendedInstallLocation
16351                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16352                    }
16353                }
16354            }
16355
16356            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16357                int loc = pkgLite.recommendedInstallLocation;
16358                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16359                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16360                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16361                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16362                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16363                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16364                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16365                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16366                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16367                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16368                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16369                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16370                } else {
16371                    // Override with defaults if needed.
16372                    loc = installLocationPolicy(pkgLite);
16373                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16374                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16375                    } else if (!onSd && !onInt) {
16376                        // Override install location with flags
16377                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16378                            // Set the flag to install on external media.
16379                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16380                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16381                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16382                            if (DEBUG_EPHEMERAL) {
16383                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16384                            }
16385                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16386                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16387                                    |PackageManager.INSTALL_INTERNAL);
16388                        } else {
16389                            // Make sure the flag for installing on external
16390                            // media is unset
16391                            installFlags |= PackageManager.INSTALL_INTERNAL;
16392                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16393                        }
16394                    }
16395                }
16396            }
16397
16398            final InstallArgs args = createInstallArgs(this);
16399            mArgs = args;
16400
16401            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16402                // TODO: http://b/22976637
16403                // Apps installed for "all" users use the device owner to verify the app
16404                UserHandle verifierUser = getUser();
16405                if (verifierUser == UserHandle.ALL) {
16406                    verifierUser = UserHandle.SYSTEM;
16407                }
16408
16409                /*
16410                 * Determine if we have any installed package verifiers. If we
16411                 * do, then we'll defer to them to verify the packages.
16412                 */
16413                final int requiredUid = mRequiredVerifierPackage == null ? -1
16414                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16415                                verifierUser.getIdentifier());
16416                final int installerUid =
16417                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16418                if (!origin.existing && requiredUid != -1
16419                        && isVerificationEnabled(
16420                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16421                    final Intent verification = new Intent(
16422                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16423                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16424                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16425                            PACKAGE_MIME_TYPE);
16426                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16427
16428                    // Query all live verifiers based on current user state
16429                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16430                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16431                            false /*allowDynamicSplits*/);
16432
16433                    if (DEBUG_VERIFY) {
16434                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16435                                + verification.toString() + " with " + pkgLite.verifiers.length
16436                                + " optional verifiers");
16437                    }
16438
16439                    final int verificationId = mPendingVerificationToken++;
16440
16441                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16442
16443                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16444                            installerPackageName);
16445
16446                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16447                            installFlags);
16448
16449                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16450                            pkgLite.packageName);
16451
16452                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16453                            pkgLite.versionCode);
16454
16455                    if (verificationInfo != null) {
16456                        if (verificationInfo.originatingUri != null) {
16457                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16458                                    verificationInfo.originatingUri);
16459                        }
16460                        if (verificationInfo.referrer != null) {
16461                            verification.putExtra(Intent.EXTRA_REFERRER,
16462                                    verificationInfo.referrer);
16463                        }
16464                        if (verificationInfo.originatingUid >= 0) {
16465                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16466                                    verificationInfo.originatingUid);
16467                        }
16468                        if (verificationInfo.installerUid >= 0) {
16469                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16470                                    verificationInfo.installerUid);
16471                        }
16472                    }
16473
16474                    final PackageVerificationState verificationState = new PackageVerificationState(
16475                            requiredUid, args);
16476
16477                    mPendingVerification.append(verificationId, verificationState);
16478
16479                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16480                            receivers, verificationState);
16481
16482                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16483                    final long idleDuration = getVerificationTimeout();
16484
16485                    /*
16486                     * If any sufficient verifiers were listed in the package
16487                     * manifest, attempt to ask them.
16488                     */
16489                    if (sufficientVerifiers != null) {
16490                        final int N = sufficientVerifiers.size();
16491                        if (N == 0) {
16492                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16493                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16494                        } else {
16495                            for (int i = 0; i < N; i++) {
16496                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16497                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16498                                        verifierComponent.getPackageName(), idleDuration,
16499                                        verifierUser.getIdentifier(), false, "package verifier");
16500
16501                                final Intent sufficientIntent = new Intent(verification);
16502                                sufficientIntent.setComponent(verifierComponent);
16503                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16504                            }
16505                        }
16506                    }
16507
16508                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16509                            mRequiredVerifierPackage, receivers);
16510                    if (ret == PackageManager.INSTALL_SUCCEEDED
16511                            && mRequiredVerifierPackage != null) {
16512                        Trace.asyncTraceBegin(
16513                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16514                        /*
16515                         * Send the intent to the required verification agent,
16516                         * but only start the verification timeout after the
16517                         * target BroadcastReceivers have run.
16518                         */
16519                        verification.setComponent(requiredVerifierComponent);
16520                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16521                                mRequiredVerifierPackage, idleDuration,
16522                                verifierUser.getIdentifier(), false, "package verifier");
16523                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16524                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16525                                new BroadcastReceiver() {
16526                                    @Override
16527                                    public void onReceive(Context context, Intent intent) {
16528                                        final Message msg = mHandler
16529                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16530                                        msg.arg1 = verificationId;
16531                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16532                                    }
16533                                }, null, 0, null, null);
16534
16535                        /*
16536                         * We don't want the copy to proceed until verification
16537                         * succeeds, so null out this field.
16538                         */
16539                        mArgs = null;
16540                    }
16541                } else {
16542                    /*
16543                     * No package verification is enabled, so immediately start
16544                     * the remote call to initiate copy using temporary file.
16545                     */
16546                    ret = args.copyApk(mContainerService, true);
16547                }
16548            }
16549
16550            mRet = ret;
16551        }
16552
16553        @Override
16554        void handleReturnCode() {
16555            // If mArgs is null, then MCS couldn't be reached. When it
16556            // reconnects, it will try again to install. At that point, this
16557            // will succeed.
16558            if (mArgs != null) {
16559                processPendingInstall(mArgs, mRet);
16560            }
16561        }
16562
16563        @Override
16564        void handleServiceError() {
16565            mArgs = createInstallArgs(this);
16566            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16567        }
16568    }
16569
16570    private InstallArgs createInstallArgs(InstallParams params) {
16571        if (params.move != null) {
16572            return new MoveInstallArgs(params);
16573        } else {
16574            return new FileInstallArgs(params);
16575        }
16576    }
16577
16578    /**
16579     * Create args that describe an existing installed package. Typically used
16580     * when cleaning up old installs, or used as a move source.
16581     */
16582    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16583            String resourcePath, String[] instructionSets) {
16584        return new FileInstallArgs(codePath, resourcePath, instructionSets);
16585    }
16586
16587    static abstract class InstallArgs {
16588        /** @see InstallParams#origin */
16589        final OriginInfo origin;
16590        /** @see InstallParams#move */
16591        final MoveInfo move;
16592
16593        final IPackageInstallObserver2 observer;
16594        // Always refers to PackageManager flags only
16595        final int installFlags;
16596        final String installerPackageName;
16597        final String volumeUuid;
16598        final UserHandle user;
16599        final String abiOverride;
16600        final String[] installGrantPermissions;
16601        /** If non-null, drop an async trace when the install completes */
16602        final String traceMethod;
16603        final int traceCookie;
16604        final Certificate[][] certificates;
16605        final int installReason;
16606
16607        // The list of instruction sets supported by this app. This is currently
16608        // only used during the rmdex() phase to clean up resources. We can get rid of this
16609        // if we move dex files under the common app path.
16610        /* nullable */ String[] instructionSets;
16611
16612        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16613                int installFlags, String installerPackageName, String volumeUuid,
16614                UserHandle user, String[] instructionSets,
16615                String abiOverride, String[] installGrantPermissions,
16616                String traceMethod, int traceCookie, Certificate[][] certificates,
16617                int installReason) {
16618            this.origin = origin;
16619            this.move = move;
16620            this.installFlags = installFlags;
16621            this.observer = observer;
16622            this.installerPackageName = installerPackageName;
16623            this.volumeUuid = volumeUuid;
16624            this.user = user;
16625            this.instructionSets = instructionSets;
16626            this.abiOverride = abiOverride;
16627            this.installGrantPermissions = installGrantPermissions;
16628            this.traceMethod = traceMethod;
16629            this.traceCookie = traceCookie;
16630            this.certificates = certificates;
16631            this.installReason = installReason;
16632        }
16633
16634        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16635        abstract int doPreInstall(int status);
16636
16637        /**
16638         * Rename package into final resting place. All paths on the given
16639         * scanned package should be updated to reflect the rename.
16640         */
16641        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16642        abstract int doPostInstall(int status, int uid);
16643
16644        /** @see PackageSettingBase#codePathString */
16645        abstract String getCodePath();
16646        /** @see PackageSettingBase#resourcePathString */
16647        abstract String getResourcePath();
16648
16649        // Need installer lock especially for dex file removal.
16650        abstract void cleanUpResourcesLI();
16651        abstract boolean doPostDeleteLI(boolean delete);
16652
16653        /**
16654         * Called before the source arguments are copied. This is used mostly
16655         * for MoveParams when it needs to read the source file to put it in the
16656         * destination.
16657         */
16658        int doPreCopy() {
16659            return PackageManager.INSTALL_SUCCEEDED;
16660        }
16661
16662        /**
16663         * Called after the source arguments are copied. This is used mostly for
16664         * MoveParams when it needs to read the source file to put it in the
16665         * destination.
16666         */
16667        int doPostCopy(int uid) {
16668            return PackageManager.INSTALL_SUCCEEDED;
16669        }
16670
16671        protected boolean isFwdLocked() {
16672            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16673        }
16674
16675        protected boolean isExternalAsec() {
16676            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16677        }
16678
16679        protected boolean isEphemeral() {
16680            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16681        }
16682
16683        UserHandle getUser() {
16684            return user;
16685        }
16686    }
16687
16688    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16689        if (!allCodePaths.isEmpty()) {
16690            if (instructionSets == null) {
16691                throw new IllegalStateException("instructionSet == null");
16692            }
16693            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16694            for (String codePath : allCodePaths) {
16695                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16696                    try {
16697                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16698                    } catch (InstallerException ignored) {
16699                    }
16700                }
16701            }
16702        }
16703    }
16704
16705    /**
16706     * Logic to handle installation of non-ASEC applications, including copying
16707     * and renaming logic.
16708     */
16709    class FileInstallArgs extends InstallArgs {
16710        private File codeFile;
16711        private File resourceFile;
16712
16713        // Example topology:
16714        // /data/app/com.example/base.apk
16715        // /data/app/com.example/split_foo.apk
16716        // /data/app/com.example/lib/arm/libfoo.so
16717        // /data/app/com.example/lib/arm64/libfoo.so
16718        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16719
16720        /** New install */
16721        FileInstallArgs(InstallParams params) {
16722            super(params.origin, params.move, params.observer, params.installFlags,
16723                    params.installerPackageName, params.volumeUuid,
16724                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16725                    params.grantedRuntimePermissions,
16726                    params.traceMethod, params.traceCookie, params.certificates,
16727                    params.installReason);
16728            if (isFwdLocked()) {
16729                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16730            }
16731        }
16732
16733        /** Existing install */
16734        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16735            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16736                    null, null, null, 0, null /*certificates*/,
16737                    PackageManager.INSTALL_REASON_UNKNOWN);
16738            this.codeFile = (codePath != null) ? new File(codePath) : null;
16739            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16740        }
16741
16742        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16743            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16744            try {
16745                return doCopyApk(imcs, temp);
16746            } finally {
16747                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16748            }
16749        }
16750
16751        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16752            if (origin.staged) {
16753                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16754                codeFile = origin.file;
16755                resourceFile = origin.file;
16756                return PackageManager.INSTALL_SUCCEEDED;
16757            }
16758
16759            try {
16760                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16761                final File tempDir =
16762                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16763                codeFile = tempDir;
16764                resourceFile = tempDir;
16765            } catch (IOException e) {
16766                Slog.w(TAG, "Failed to create copy file: " + e);
16767                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16768            }
16769
16770            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16771                @Override
16772                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16773                    if (!FileUtils.isValidExtFilename(name)) {
16774                        throw new IllegalArgumentException("Invalid filename: " + name);
16775                    }
16776                    try {
16777                        final File file = new File(codeFile, name);
16778                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16779                                O_RDWR | O_CREAT, 0644);
16780                        Os.chmod(file.getAbsolutePath(), 0644);
16781                        return new ParcelFileDescriptor(fd);
16782                    } catch (ErrnoException e) {
16783                        throw new RemoteException("Failed to open: " + e.getMessage());
16784                    }
16785                }
16786            };
16787
16788            int ret = PackageManager.INSTALL_SUCCEEDED;
16789            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16790            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16791                Slog.e(TAG, "Failed to copy package");
16792                return ret;
16793            }
16794
16795            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16796            NativeLibraryHelper.Handle handle = null;
16797            try {
16798                handle = NativeLibraryHelper.Handle.create(codeFile);
16799                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16800                        abiOverride);
16801            } catch (IOException e) {
16802                Slog.e(TAG, "Copying native libraries failed", e);
16803                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16804            } finally {
16805                IoUtils.closeQuietly(handle);
16806            }
16807
16808            return ret;
16809        }
16810
16811        int doPreInstall(int status) {
16812            if (status != PackageManager.INSTALL_SUCCEEDED) {
16813                cleanUp();
16814            }
16815            return status;
16816        }
16817
16818        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16819            if (status != PackageManager.INSTALL_SUCCEEDED) {
16820                cleanUp();
16821                return false;
16822            }
16823
16824            final File targetDir = codeFile.getParentFile();
16825            final File beforeCodeFile = codeFile;
16826            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16827
16828            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16829            try {
16830                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16831            } catch (ErrnoException e) {
16832                Slog.w(TAG, "Failed to rename", e);
16833                return false;
16834            }
16835
16836            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16837                Slog.w(TAG, "Failed to restorecon");
16838                return false;
16839            }
16840
16841            // Reflect the rename internally
16842            codeFile = afterCodeFile;
16843            resourceFile = afterCodeFile;
16844
16845            // Reflect the rename in scanned details
16846            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16847            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16848                    afterCodeFile, pkg.baseCodePath));
16849            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16850                    afterCodeFile, pkg.splitCodePaths));
16851
16852            // Reflect the rename in app info
16853            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16854            pkg.setApplicationInfoCodePath(pkg.codePath);
16855            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16856            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16857            pkg.setApplicationInfoResourcePath(pkg.codePath);
16858            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16859            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16860
16861            return true;
16862        }
16863
16864        int doPostInstall(int status, int uid) {
16865            if (status != PackageManager.INSTALL_SUCCEEDED) {
16866                cleanUp();
16867            }
16868            return status;
16869        }
16870
16871        @Override
16872        String getCodePath() {
16873            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16874        }
16875
16876        @Override
16877        String getResourcePath() {
16878            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16879        }
16880
16881        private boolean cleanUp() {
16882            if (codeFile == null || !codeFile.exists()) {
16883                return false;
16884            }
16885
16886            removeCodePathLI(codeFile);
16887
16888            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16889                resourceFile.delete();
16890            }
16891
16892            return true;
16893        }
16894
16895        void cleanUpResourcesLI() {
16896            // Try enumerating all code paths before deleting
16897            List<String> allCodePaths = Collections.EMPTY_LIST;
16898            if (codeFile != null && codeFile.exists()) {
16899                try {
16900                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16901                    allCodePaths = pkg.getAllCodePaths();
16902                } catch (PackageParserException e) {
16903                    // Ignored; we tried our best
16904                }
16905            }
16906
16907            cleanUp();
16908            removeDexFiles(allCodePaths, instructionSets);
16909        }
16910
16911        boolean doPostDeleteLI(boolean delete) {
16912            // XXX err, shouldn't we respect the delete flag?
16913            cleanUpResourcesLI();
16914            return true;
16915        }
16916    }
16917
16918    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16919            PackageManagerException {
16920        if (copyRet < 0) {
16921            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16922                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16923                throw new PackageManagerException(copyRet, message);
16924            }
16925        }
16926    }
16927
16928    /**
16929     * Extract the StorageManagerService "container ID" from the full code path of an
16930     * .apk.
16931     */
16932    static String cidFromCodePath(String fullCodePath) {
16933        int eidx = fullCodePath.lastIndexOf("/");
16934        String subStr1 = fullCodePath.substring(0, eidx);
16935        int sidx = subStr1.lastIndexOf("/");
16936        return subStr1.substring(sidx+1, eidx);
16937    }
16938
16939    /**
16940     * Logic to handle movement of existing installed applications.
16941     */
16942    class MoveInstallArgs extends InstallArgs {
16943        private File codeFile;
16944        private File resourceFile;
16945
16946        /** New install */
16947        MoveInstallArgs(InstallParams params) {
16948            super(params.origin, params.move, params.observer, params.installFlags,
16949                    params.installerPackageName, params.volumeUuid,
16950                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16951                    params.grantedRuntimePermissions,
16952                    params.traceMethod, params.traceCookie, params.certificates,
16953                    params.installReason);
16954        }
16955
16956        int copyApk(IMediaContainerService imcs, boolean temp) {
16957            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16958                    + move.fromUuid + " to " + move.toUuid);
16959            synchronized (mInstaller) {
16960                try {
16961                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16962                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16963                } catch (InstallerException e) {
16964                    Slog.w(TAG, "Failed to move app", e);
16965                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16966                }
16967            }
16968
16969            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16970            resourceFile = codeFile;
16971            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16972
16973            return PackageManager.INSTALL_SUCCEEDED;
16974        }
16975
16976        int doPreInstall(int status) {
16977            if (status != PackageManager.INSTALL_SUCCEEDED) {
16978                cleanUp(move.toUuid);
16979            }
16980            return status;
16981        }
16982
16983        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16984            if (status != PackageManager.INSTALL_SUCCEEDED) {
16985                cleanUp(move.toUuid);
16986                return false;
16987            }
16988
16989            // Reflect the move in app info
16990            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16991            pkg.setApplicationInfoCodePath(pkg.codePath);
16992            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16993            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16994            pkg.setApplicationInfoResourcePath(pkg.codePath);
16995            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16996            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16997
16998            return true;
16999        }
17000
17001        int doPostInstall(int status, int uid) {
17002            if (status == PackageManager.INSTALL_SUCCEEDED) {
17003                cleanUp(move.fromUuid);
17004            } else {
17005                cleanUp(move.toUuid);
17006            }
17007            return status;
17008        }
17009
17010        @Override
17011        String getCodePath() {
17012            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17013        }
17014
17015        @Override
17016        String getResourcePath() {
17017            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17018        }
17019
17020        private boolean cleanUp(String volumeUuid) {
17021            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17022                    move.dataAppName);
17023            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17024            final int[] userIds = sUserManager.getUserIds();
17025            synchronized (mInstallLock) {
17026                // Clean up both app data and code
17027                // All package moves are frozen until finished
17028                for (int userId : userIds) {
17029                    try {
17030                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17031                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17032                    } catch (InstallerException e) {
17033                        Slog.w(TAG, String.valueOf(e));
17034                    }
17035                }
17036                removeCodePathLI(codeFile);
17037            }
17038            return true;
17039        }
17040
17041        void cleanUpResourcesLI() {
17042            throw new UnsupportedOperationException();
17043        }
17044
17045        boolean doPostDeleteLI(boolean delete) {
17046            throw new UnsupportedOperationException();
17047        }
17048    }
17049
17050    static String getAsecPackageName(String packageCid) {
17051        int idx = packageCid.lastIndexOf("-");
17052        if (idx == -1) {
17053            return packageCid;
17054        }
17055        return packageCid.substring(0, idx);
17056    }
17057
17058    // Utility method used to create code paths based on package name and available index.
17059    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17060        String idxStr = "";
17061        int idx = 1;
17062        // Fall back to default value of idx=1 if prefix is not
17063        // part of oldCodePath
17064        if (oldCodePath != null) {
17065            String subStr = oldCodePath;
17066            // Drop the suffix right away
17067            if (suffix != null && subStr.endsWith(suffix)) {
17068                subStr = subStr.substring(0, subStr.length() - suffix.length());
17069            }
17070            // If oldCodePath already contains prefix find out the
17071            // ending index to either increment or decrement.
17072            int sidx = subStr.lastIndexOf(prefix);
17073            if (sidx != -1) {
17074                subStr = subStr.substring(sidx + prefix.length());
17075                if (subStr != null) {
17076                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17077                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17078                    }
17079                    try {
17080                        idx = Integer.parseInt(subStr);
17081                        if (idx <= 1) {
17082                            idx++;
17083                        } else {
17084                            idx--;
17085                        }
17086                    } catch(NumberFormatException e) {
17087                    }
17088                }
17089            }
17090        }
17091        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17092        return prefix + idxStr;
17093    }
17094
17095    private File getNextCodePath(File targetDir, String packageName) {
17096        File result;
17097        SecureRandom random = new SecureRandom();
17098        byte[] bytes = new byte[16];
17099        do {
17100            random.nextBytes(bytes);
17101            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17102            result = new File(targetDir, packageName + "-" + suffix);
17103        } while (result.exists());
17104        return result;
17105    }
17106
17107    // Utility method that returns the relative package path with respect
17108    // to the installation directory. Like say for /data/data/com.test-1.apk
17109    // string com.test-1 is returned.
17110    static String deriveCodePathName(String codePath) {
17111        if (codePath == null) {
17112            return null;
17113        }
17114        final File codeFile = new File(codePath);
17115        final String name = codeFile.getName();
17116        if (codeFile.isDirectory()) {
17117            return name;
17118        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17119            final int lastDot = name.lastIndexOf('.');
17120            return name.substring(0, lastDot);
17121        } else {
17122            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17123            return null;
17124        }
17125    }
17126
17127    static class PackageInstalledInfo {
17128        String name;
17129        int uid;
17130        // The set of users that originally had this package installed.
17131        int[] origUsers;
17132        // The set of users that now have this package installed.
17133        int[] newUsers;
17134        PackageParser.Package pkg;
17135        int returnCode;
17136        String returnMsg;
17137        String installerPackageName;
17138        PackageRemovedInfo removedInfo;
17139        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17140
17141        public void setError(int code, String msg) {
17142            setReturnCode(code);
17143            setReturnMessage(msg);
17144            Slog.w(TAG, msg);
17145        }
17146
17147        public void setError(String msg, PackageParserException e) {
17148            setReturnCode(e.error);
17149            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17150            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17151            for (int i = 0; i < childCount; i++) {
17152                addedChildPackages.valueAt(i).setError(msg, e);
17153            }
17154            Slog.w(TAG, msg, e);
17155        }
17156
17157        public void setError(String msg, PackageManagerException e) {
17158            returnCode = e.error;
17159            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17160            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17161            for (int i = 0; i < childCount; i++) {
17162                addedChildPackages.valueAt(i).setError(msg, e);
17163            }
17164            Slog.w(TAG, msg, e);
17165        }
17166
17167        public void setReturnCode(int returnCode) {
17168            this.returnCode = returnCode;
17169            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17170            for (int i = 0; i < childCount; i++) {
17171                addedChildPackages.valueAt(i).returnCode = returnCode;
17172            }
17173        }
17174
17175        private void setReturnMessage(String returnMsg) {
17176            this.returnMsg = returnMsg;
17177            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17178            for (int i = 0; i < childCount; i++) {
17179                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17180            }
17181        }
17182
17183        // In some error cases we want to convey more info back to the observer
17184        String origPackage;
17185        String origPermission;
17186    }
17187
17188    /*
17189     * Install a non-existing package.
17190     */
17191    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17192            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17193            PackageInstalledInfo res, int installReason) {
17194        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17195
17196        // Remember this for later, in case we need to rollback this install
17197        String pkgName = pkg.packageName;
17198
17199        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17200
17201        synchronized(mPackages) {
17202            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17203            if (renamedPackage != null) {
17204                // A package with the same name is already installed, though
17205                // it has been renamed to an older name.  The package we
17206                // are trying to install should be installed as an update to
17207                // the existing one, but that has not been requested, so bail.
17208                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17209                        + " without first uninstalling package running as "
17210                        + renamedPackage);
17211                return;
17212            }
17213            if (mPackages.containsKey(pkgName)) {
17214                // Don't allow installation over an existing package with the same name.
17215                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17216                        + " without first uninstalling.");
17217                return;
17218            }
17219        }
17220
17221        try {
17222            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17223                    System.currentTimeMillis(), user);
17224
17225            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17226
17227            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17228                prepareAppDataAfterInstallLIF(newPackage);
17229
17230            } else {
17231                // Remove package from internal structures, but keep around any
17232                // data that might have already existed
17233                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17234                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17235            }
17236        } catch (PackageManagerException e) {
17237            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17238        }
17239
17240        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17241    }
17242
17243    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17244        // Can't rotate keys during boot or if sharedUser.
17245        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17246                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17247            return false;
17248        }
17249        // app is using upgradeKeySets; make sure all are valid
17250        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17251        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17252        for (int i = 0; i < upgradeKeySets.length; i++) {
17253            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17254                Slog.wtf(TAG, "Package "
17255                         + (oldPs.name != null ? oldPs.name : "<null>")
17256                         + " contains upgrade-key-set reference to unknown key-set: "
17257                         + upgradeKeySets[i]
17258                         + " reverting to signatures check.");
17259                return false;
17260            }
17261        }
17262        return true;
17263    }
17264
17265    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17266        // Upgrade keysets are being used.  Determine if new package has a superset of the
17267        // required keys.
17268        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17269        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17270        for (int i = 0; i < upgradeKeySets.length; i++) {
17271            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17272            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17273                return true;
17274            }
17275        }
17276        return false;
17277    }
17278
17279    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17280        try (DigestInputStream digestStream =
17281                new DigestInputStream(new FileInputStream(file), digest)) {
17282            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17283        }
17284    }
17285
17286    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17287            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17288            int installReason) {
17289        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17290
17291        final PackageParser.Package oldPackage;
17292        final PackageSetting ps;
17293        final String pkgName = pkg.packageName;
17294        final int[] allUsers;
17295        final int[] installedUsers;
17296
17297        synchronized(mPackages) {
17298            oldPackage = mPackages.get(pkgName);
17299            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17300
17301            // don't allow upgrade to target a release SDK from a pre-release SDK
17302            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17303                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17304            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17305                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17306            if (oldTargetsPreRelease
17307                    && !newTargetsPreRelease
17308                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17309                Slog.w(TAG, "Can't install package targeting released sdk");
17310                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17311                return;
17312            }
17313
17314            ps = mSettings.mPackages.get(pkgName);
17315
17316            // verify signatures are valid
17317            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17318                if (!checkUpgradeKeySetLP(ps, pkg)) {
17319                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17320                            "New package not signed by keys specified by upgrade-keysets: "
17321                                    + pkgName);
17322                    return;
17323                }
17324            } else {
17325                // default to original signature matching
17326                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17327                        != PackageManager.SIGNATURE_MATCH) {
17328                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17329                            "New package has a different signature: " + pkgName);
17330                    return;
17331                }
17332            }
17333
17334            // don't allow a system upgrade unless the upgrade hash matches
17335            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17336                byte[] digestBytes = null;
17337                try {
17338                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17339                    updateDigest(digest, new File(pkg.baseCodePath));
17340                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17341                        for (String path : pkg.splitCodePaths) {
17342                            updateDigest(digest, new File(path));
17343                        }
17344                    }
17345                    digestBytes = digest.digest();
17346                } catch (NoSuchAlgorithmException | IOException e) {
17347                    res.setError(INSTALL_FAILED_INVALID_APK,
17348                            "Could not compute hash: " + pkgName);
17349                    return;
17350                }
17351                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17352                    res.setError(INSTALL_FAILED_INVALID_APK,
17353                            "New package fails restrict-update check: " + pkgName);
17354                    return;
17355                }
17356                // retain upgrade restriction
17357                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17358            }
17359
17360            // Check for shared user id changes
17361            String invalidPackageName =
17362                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17363            if (invalidPackageName != null) {
17364                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17365                        "Package " + invalidPackageName + " tried to change user "
17366                                + oldPackage.mSharedUserId);
17367                return;
17368            }
17369
17370            // In case of rollback, remember per-user/profile install state
17371            allUsers = sUserManager.getUserIds();
17372            installedUsers = ps.queryInstalledUsers(allUsers, true);
17373
17374            // don't allow an upgrade from full to ephemeral
17375            if (isInstantApp) {
17376                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17377                    for (int currentUser : allUsers) {
17378                        if (!ps.getInstantApp(currentUser)) {
17379                            // can't downgrade from full to instant
17380                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17381                                    + " for user: " + currentUser);
17382                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17383                            return;
17384                        }
17385                    }
17386                } else if (!ps.getInstantApp(user.getIdentifier())) {
17387                    // can't downgrade from full to instant
17388                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17389                            + " for user: " + user.getIdentifier());
17390                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17391                    return;
17392                }
17393            }
17394        }
17395
17396        // Update what is removed
17397        res.removedInfo = new PackageRemovedInfo(this);
17398        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17399        res.removedInfo.removedPackage = oldPackage.packageName;
17400        res.removedInfo.installerPackageName = ps.installerPackageName;
17401        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17402        res.removedInfo.isUpdate = true;
17403        res.removedInfo.origUsers = installedUsers;
17404        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17405        for (int i = 0; i < installedUsers.length; i++) {
17406            final int userId = installedUsers[i];
17407            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17408        }
17409
17410        final int childCount = (oldPackage.childPackages != null)
17411                ? oldPackage.childPackages.size() : 0;
17412        for (int i = 0; i < childCount; i++) {
17413            boolean childPackageUpdated = false;
17414            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17415            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17416            if (res.addedChildPackages != null) {
17417                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17418                if (childRes != null) {
17419                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17420                    childRes.removedInfo.removedPackage = childPkg.packageName;
17421                    if (childPs != null) {
17422                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17423                    }
17424                    childRes.removedInfo.isUpdate = true;
17425                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17426                    childPackageUpdated = true;
17427                }
17428            }
17429            if (!childPackageUpdated) {
17430                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17431                childRemovedRes.removedPackage = childPkg.packageName;
17432                if (childPs != null) {
17433                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17434                }
17435                childRemovedRes.isUpdate = false;
17436                childRemovedRes.dataRemoved = true;
17437                synchronized (mPackages) {
17438                    if (childPs != null) {
17439                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17440                    }
17441                }
17442                if (res.removedInfo.removedChildPackages == null) {
17443                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17444                }
17445                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17446            }
17447        }
17448
17449        boolean sysPkg = (isSystemApp(oldPackage));
17450        if (sysPkg) {
17451            // Set the system/privileged/oem flags as needed
17452            final boolean privileged =
17453                    (oldPackage.applicationInfo.privateFlags
17454                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17455            final boolean oem =
17456                    (oldPackage.applicationInfo.privateFlags
17457                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17458            final int systemPolicyFlags = policyFlags
17459                    | PackageParser.PARSE_IS_SYSTEM
17460                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
17461                    | (oem ? PARSE_IS_OEM : 0);
17462
17463            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17464                    user, allUsers, installerPackageName, res, installReason);
17465        } else {
17466            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17467                    user, allUsers, installerPackageName, res, installReason);
17468        }
17469    }
17470
17471    @Override
17472    public List<String> getPreviousCodePaths(String packageName) {
17473        final int callingUid = Binder.getCallingUid();
17474        final List<String> result = new ArrayList<>();
17475        if (getInstantAppPackageName(callingUid) != null) {
17476            return result;
17477        }
17478        final PackageSetting ps = mSettings.mPackages.get(packageName);
17479        if (ps != null
17480                && ps.oldCodePaths != null
17481                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17482            result.addAll(ps.oldCodePaths);
17483        }
17484        return result;
17485    }
17486
17487    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17488            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17489            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17490            int installReason) {
17491        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17492                + deletedPackage);
17493
17494        String pkgName = deletedPackage.packageName;
17495        boolean deletedPkg = true;
17496        boolean addedPkg = false;
17497        boolean updatedSettings = false;
17498        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17499        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17500                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17501
17502        final long origUpdateTime = (pkg.mExtras != null)
17503                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17504
17505        // First delete the existing package while retaining the data directory
17506        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17507                res.removedInfo, true, pkg)) {
17508            // If the existing package wasn't successfully deleted
17509            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17510            deletedPkg = false;
17511        } else {
17512            // Successfully deleted the old package; proceed with replace.
17513
17514            // If deleted package lived in a container, give users a chance to
17515            // relinquish resources before killing.
17516            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17517                if (DEBUG_INSTALL) {
17518                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17519                }
17520                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17521                final ArrayList<String> pkgList = new ArrayList<String>(1);
17522                pkgList.add(deletedPackage.applicationInfo.packageName);
17523                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17524            }
17525
17526            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17527                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17528            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17529
17530            try {
17531                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17532                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17533                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17534                        installReason);
17535
17536                // Update the in-memory copy of the previous code paths.
17537                PackageSetting ps = mSettings.mPackages.get(pkgName);
17538                if (!killApp) {
17539                    if (ps.oldCodePaths == null) {
17540                        ps.oldCodePaths = new ArraySet<>();
17541                    }
17542                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17543                    if (deletedPackage.splitCodePaths != null) {
17544                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17545                    }
17546                } else {
17547                    ps.oldCodePaths = null;
17548                }
17549                if (ps.childPackageNames != null) {
17550                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17551                        final String childPkgName = ps.childPackageNames.get(i);
17552                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17553                        childPs.oldCodePaths = ps.oldCodePaths;
17554                    }
17555                }
17556                // set instant app status, but, only if it's explicitly specified
17557                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17558                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17559                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17560                prepareAppDataAfterInstallLIF(newPackage);
17561                addedPkg = true;
17562                mDexManager.notifyPackageUpdated(newPackage.packageName,
17563                        newPackage.baseCodePath, newPackage.splitCodePaths);
17564            } catch (PackageManagerException e) {
17565                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17566            }
17567        }
17568
17569        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17570            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17571
17572            // Revert all internal state mutations and added folders for the failed install
17573            if (addedPkg) {
17574                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17575                        res.removedInfo, true, null);
17576            }
17577
17578            // Restore the old package
17579            if (deletedPkg) {
17580                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17581                File restoreFile = new File(deletedPackage.codePath);
17582                // Parse old package
17583                boolean oldExternal = isExternal(deletedPackage);
17584                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17585                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17586                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17587                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17588                try {
17589                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17590                            null);
17591                } catch (PackageManagerException e) {
17592                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17593                            + e.getMessage());
17594                    return;
17595                }
17596
17597                synchronized (mPackages) {
17598                    // Ensure the installer package name up to date
17599                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17600
17601                    // Update permissions for restored package
17602                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17603
17604                    mSettings.writeLPr();
17605                }
17606
17607                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17608            }
17609        } else {
17610            synchronized (mPackages) {
17611                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17612                if (ps != null) {
17613                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17614                    if (res.removedInfo.removedChildPackages != null) {
17615                        final int childCount = res.removedInfo.removedChildPackages.size();
17616                        // Iterate in reverse as we may modify the collection
17617                        for (int i = childCount - 1; i >= 0; i--) {
17618                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17619                            if (res.addedChildPackages.containsKey(childPackageName)) {
17620                                res.removedInfo.removedChildPackages.removeAt(i);
17621                            } else {
17622                                PackageRemovedInfo childInfo = res.removedInfo
17623                                        .removedChildPackages.valueAt(i);
17624                                childInfo.removedForAllUsers = mPackages.get(
17625                                        childInfo.removedPackage) == null;
17626                            }
17627                        }
17628                    }
17629                }
17630            }
17631        }
17632    }
17633
17634    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17635            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17636            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17637            int installReason) {
17638        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17639                + ", old=" + deletedPackage);
17640
17641        final boolean disabledSystem;
17642
17643        // Remove existing system package
17644        removePackageLI(deletedPackage, true);
17645
17646        synchronized (mPackages) {
17647            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17648        }
17649        if (!disabledSystem) {
17650            // We didn't need to disable the .apk as a current system package,
17651            // which means we are replacing another update that is already
17652            // installed.  We need to make sure to delete the older one's .apk.
17653            res.removedInfo.args = createInstallArgsForExisting(0,
17654                    deletedPackage.applicationInfo.getCodePath(),
17655                    deletedPackage.applicationInfo.getResourcePath(),
17656                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17657        } else {
17658            res.removedInfo.args = null;
17659        }
17660
17661        // Successfully disabled the old package. Now proceed with re-installation
17662        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17663                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17664        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17665
17666        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17667        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17668                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17669
17670        PackageParser.Package newPackage = null;
17671        try {
17672            // Add the package to the internal data structures
17673            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17674
17675            // Set the update and install times
17676            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17677            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17678                    System.currentTimeMillis());
17679
17680            // Update the package dynamic state if succeeded
17681            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17682                // Now that the install succeeded make sure we remove data
17683                // directories for any child package the update removed.
17684                final int deletedChildCount = (deletedPackage.childPackages != null)
17685                        ? deletedPackage.childPackages.size() : 0;
17686                final int newChildCount = (newPackage.childPackages != null)
17687                        ? newPackage.childPackages.size() : 0;
17688                for (int i = 0; i < deletedChildCount; i++) {
17689                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17690                    boolean childPackageDeleted = true;
17691                    for (int j = 0; j < newChildCount; j++) {
17692                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17693                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17694                            childPackageDeleted = false;
17695                            break;
17696                        }
17697                    }
17698                    if (childPackageDeleted) {
17699                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17700                                deletedChildPkg.packageName);
17701                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17702                            PackageRemovedInfo removedChildRes = res.removedInfo
17703                                    .removedChildPackages.get(deletedChildPkg.packageName);
17704                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17705                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17706                        }
17707                    }
17708                }
17709
17710                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17711                        installReason);
17712                prepareAppDataAfterInstallLIF(newPackage);
17713
17714                mDexManager.notifyPackageUpdated(newPackage.packageName,
17715                            newPackage.baseCodePath, newPackage.splitCodePaths);
17716            }
17717        } catch (PackageManagerException e) {
17718            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17719            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17720        }
17721
17722        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17723            // Re installation failed. Restore old information
17724            // Remove new pkg information
17725            if (newPackage != null) {
17726                removeInstalledPackageLI(newPackage, true);
17727            }
17728            // Add back the old system package
17729            try {
17730                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17731            } catch (PackageManagerException e) {
17732                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17733            }
17734
17735            synchronized (mPackages) {
17736                if (disabledSystem) {
17737                    enableSystemPackageLPw(deletedPackage);
17738                }
17739
17740                // Ensure the installer package name up to date
17741                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17742
17743                // Update permissions for restored package
17744                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17745
17746                mSettings.writeLPr();
17747            }
17748
17749            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17750                    + " after failed upgrade");
17751        }
17752    }
17753
17754    /**
17755     * Checks whether the parent or any of the child packages have a change shared
17756     * user. For a package to be a valid update the shred users of the parent and
17757     * the children should match. We may later support changing child shared users.
17758     * @param oldPkg The updated package.
17759     * @param newPkg The update package.
17760     * @return The shared user that change between the versions.
17761     */
17762    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17763            PackageParser.Package newPkg) {
17764        // Check parent shared user
17765        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17766            return newPkg.packageName;
17767        }
17768        // Check child shared users
17769        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17770        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17771        for (int i = 0; i < newChildCount; i++) {
17772            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17773            // If this child was present, did it have the same shared user?
17774            for (int j = 0; j < oldChildCount; j++) {
17775                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17776                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17777                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17778                    return newChildPkg.packageName;
17779                }
17780            }
17781        }
17782        return null;
17783    }
17784
17785    private void removeNativeBinariesLI(PackageSetting ps) {
17786        // Remove the lib path for the parent package
17787        if (ps != null) {
17788            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17789            // Remove the lib path for the child packages
17790            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17791            for (int i = 0; i < childCount; i++) {
17792                PackageSetting childPs = null;
17793                synchronized (mPackages) {
17794                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17795                }
17796                if (childPs != null) {
17797                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17798                            .legacyNativeLibraryPathString);
17799                }
17800            }
17801        }
17802    }
17803
17804    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17805        // Enable the parent package
17806        mSettings.enableSystemPackageLPw(pkg.packageName);
17807        // Enable the child packages
17808        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17809        for (int i = 0; i < childCount; i++) {
17810            PackageParser.Package childPkg = pkg.childPackages.get(i);
17811            mSettings.enableSystemPackageLPw(childPkg.packageName);
17812        }
17813    }
17814
17815    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17816            PackageParser.Package newPkg) {
17817        // Disable the parent package (parent always replaced)
17818        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17819        // Disable the child packages
17820        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17821        for (int i = 0; i < childCount; i++) {
17822            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17823            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17824            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17825        }
17826        return disabled;
17827    }
17828
17829    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17830            String installerPackageName) {
17831        // Enable the parent package
17832        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17833        // Enable the child packages
17834        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17835        for (int i = 0; i < childCount; i++) {
17836            PackageParser.Package childPkg = pkg.childPackages.get(i);
17837            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17838        }
17839    }
17840
17841    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17842        // Collect all used permissions in the UID
17843        ArraySet<String> usedPermissions = new ArraySet<>();
17844        final int packageCount = su.packages.size();
17845        for (int i = 0; i < packageCount; i++) {
17846            PackageSetting ps = su.packages.valueAt(i);
17847            if (ps.pkg == null) {
17848                continue;
17849            }
17850            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17851            for (int j = 0; j < requestedPermCount; j++) {
17852                String permission = ps.pkg.requestedPermissions.get(j);
17853                BasePermission bp = mSettings.mPermissions.get(permission);
17854                if (bp != null) {
17855                    usedPermissions.add(permission);
17856                }
17857            }
17858        }
17859
17860        PermissionsState permissionsState = su.getPermissionsState();
17861        // Prune install permissions
17862        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17863        final int installPermCount = installPermStates.size();
17864        for (int i = installPermCount - 1; i >= 0;  i--) {
17865            PermissionState permissionState = installPermStates.get(i);
17866            if (!usedPermissions.contains(permissionState.getName())) {
17867                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17868                if (bp != null) {
17869                    permissionsState.revokeInstallPermission(bp);
17870                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17871                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17872                }
17873            }
17874        }
17875
17876        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17877
17878        // Prune runtime permissions
17879        for (int userId : allUserIds) {
17880            List<PermissionState> runtimePermStates = permissionsState
17881                    .getRuntimePermissionStates(userId);
17882            final int runtimePermCount = runtimePermStates.size();
17883            for (int i = runtimePermCount - 1; i >= 0; i--) {
17884                PermissionState permissionState = runtimePermStates.get(i);
17885                if (!usedPermissions.contains(permissionState.getName())) {
17886                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17887                    if (bp != null) {
17888                        permissionsState.revokeRuntimePermission(bp, userId);
17889                        permissionsState.updatePermissionFlags(bp, userId,
17890                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17891                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17892                                runtimePermissionChangedUserIds, userId);
17893                    }
17894                }
17895            }
17896        }
17897
17898        return runtimePermissionChangedUserIds;
17899    }
17900
17901    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17902            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17903        // Update the parent package setting
17904        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17905                res, user, installReason);
17906        // Update the child packages setting
17907        final int childCount = (newPackage.childPackages != null)
17908                ? newPackage.childPackages.size() : 0;
17909        for (int i = 0; i < childCount; i++) {
17910            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17911            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17912            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17913                    childRes.origUsers, childRes, user, installReason);
17914        }
17915    }
17916
17917    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17918            String installerPackageName, int[] allUsers, int[] installedForUsers,
17919            PackageInstalledInfo res, UserHandle user, int installReason) {
17920        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17921
17922        String pkgName = newPackage.packageName;
17923        synchronized (mPackages) {
17924            //write settings. the installStatus will be incomplete at this stage.
17925            //note that the new package setting would have already been
17926            //added to mPackages. It hasn't been persisted yet.
17927            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17928            // TODO: Remove this write? It's also written at the end of this method
17929            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17930            mSettings.writeLPr();
17931            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17932        }
17933
17934        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17935        synchronized (mPackages) {
17936            updatePermissionsLPw(newPackage.packageName, newPackage,
17937                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17938                            ? UPDATE_PERMISSIONS_ALL : 0));
17939            // For system-bundled packages, we assume that installing an upgraded version
17940            // of the package implies that the user actually wants to run that new code,
17941            // so we enable the package.
17942            PackageSetting ps = mSettings.mPackages.get(pkgName);
17943            final int userId = user.getIdentifier();
17944            if (ps != null) {
17945                if (isSystemApp(newPackage)) {
17946                    if (DEBUG_INSTALL) {
17947                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17948                    }
17949                    // Enable system package for requested users
17950                    if (res.origUsers != null) {
17951                        for (int origUserId : res.origUsers) {
17952                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17953                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17954                                        origUserId, installerPackageName);
17955                            }
17956                        }
17957                    }
17958                    // Also convey the prior install/uninstall state
17959                    if (allUsers != null && installedForUsers != null) {
17960                        for (int currentUserId : allUsers) {
17961                            final boolean installed = ArrayUtils.contains(
17962                                    installedForUsers, currentUserId);
17963                            if (DEBUG_INSTALL) {
17964                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17965                            }
17966                            ps.setInstalled(installed, currentUserId);
17967                        }
17968                        // these install state changes will be persisted in the
17969                        // upcoming call to mSettings.writeLPr().
17970                    }
17971                }
17972                // It's implied that when a user requests installation, they want the app to be
17973                // installed and enabled.
17974                if (userId != UserHandle.USER_ALL) {
17975                    ps.setInstalled(true, userId);
17976                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17977                }
17978
17979                // When replacing an existing package, preserve the original install reason for all
17980                // users that had the package installed before.
17981                final Set<Integer> previousUserIds = new ArraySet<>();
17982                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17983                    final int installReasonCount = res.removedInfo.installReasons.size();
17984                    for (int i = 0; i < installReasonCount; i++) {
17985                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17986                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17987                        ps.setInstallReason(previousInstallReason, previousUserId);
17988                        previousUserIds.add(previousUserId);
17989                    }
17990                }
17991
17992                // Set install reason for users that are having the package newly installed.
17993                if (userId == UserHandle.USER_ALL) {
17994                    for (int currentUserId : sUserManager.getUserIds()) {
17995                        if (!previousUserIds.contains(currentUserId)) {
17996                            ps.setInstallReason(installReason, currentUserId);
17997                        }
17998                    }
17999                } else if (!previousUserIds.contains(userId)) {
18000                    ps.setInstallReason(installReason, userId);
18001                }
18002                mSettings.writeKernelMappingLPr(ps);
18003            }
18004            res.name = pkgName;
18005            res.uid = newPackage.applicationInfo.uid;
18006            res.pkg = newPackage;
18007            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18008            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18009            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18010            //to update install status
18011            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18012            mSettings.writeLPr();
18013            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18014        }
18015
18016        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18017    }
18018
18019    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18020        try {
18021            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18022            installPackageLI(args, res);
18023        } finally {
18024            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18025        }
18026    }
18027
18028    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18029        final int installFlags = args.installFlags;
18030        final String installerPackageName = args.installerPackageName;
18031        final String volumeUuid = args.volumeUuid;
18032        final File tmpPackageFile = new File(args.getCodePath());
18033        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18034        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18035                || (args.volumeUuid != null));
18036        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18037        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18038        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18039        final boolean virtualPreload =
18040                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18041        boolean replace = false;
18042        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18043        if (args.move != null) {
18044            // moving a complete application; perform an initial scan on the new install location
18045            scanFlags |= SCAN_INITIAL;
18046        }
18047        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18048            scanFlags |= SCAN_DONT_KILL_APP;
18049        }
18050        if (instantApp) {
18051            scanFlags |= SCAN_AS_INSTANT_APP;
18052        }
18053        if (fullApp) {
18054            scanFlags |= SCAN_AS_FULL_APP;
18055        }
18056        if (virtualPreload) {
18057            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18058        }
18059
18060        // Result object to be returned
18061        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18062        res.installerPackageName = installerPackageName;
18063
18064        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18065
18066        // Sanity check
18067        if (instantApp && (forwardLocked || onExternal)) {
18068            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18069                    + " external=" + onExternal);
18070            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18071            return;
18072        }
18073
18074        // Retrieve PackageSettings and parse package
18075        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18076                | PackageParser.PARSE_ENFORCE_CODE
18077                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18078                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18079                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18080                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18081        PackageParser pp = new PackageParser();
18082        pp.setSeparateProcesses(mSeparateProcesses);
18083        pp.setDisplayMetrics(mMetrics);
18084        pp.setCallback(mPackageParserCallback);
18085
18086        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18087        final PackageParser.Package pkg;
18088        try {
18089            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18090        } catch (PackageParserException e) {
18091            res.setError("Failed parse during installPackageLI", e);
18092            return;
18093        } finally {
18094            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18095        }
18096
18097        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18098        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18099            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18100            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18101                    "Instant app package must target O");
18102            return;
18103        }
18104        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18105            Slog.w(TAG, "Instant app package " + pkg.packageName
18106                    + " does not target targetSandboxVersion 2");
18107            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18108                    "Instant app package must use targetSanboxVersion 2");
18109            return;
18110        }
18111
18112        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18113            // Static shared libraries have synthetic package names
18114            renameStaticSharedLibraryPackage(pkg);
18115
18116            // No static shared libs on external storage
18117            if (onExternal) {
18118                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18119                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18120                        "Packages declaring static-shared libs cannot be updated");
18121                return;
18122            }
18123        }
18124
18125        // If we are installing a clustered package add results for the children
18126        if (pkg.childPackages != null) {
18127            synchronized (mPackages) {
18128                final int childCount = pkg.childPackages.size();
18129                for (int i = 0; i < childCount; i++) {
18130                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18131                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18132                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18133                    childRes.pkg = childPkg;
18134                    childRes.name = childPkg.packageName;
18135                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18136                    if (childPs != null) {
18137                        childRes.origUsers = childPs.queryInstalledUsers(
18138                                sUserManager.getUserIds(), true);
18139                    }
18140                    if ((mPackages.containsKey(childPkg.packageName))) {
18141                        childRes.removedInfo = new PackageRemovedInfo(this);
18142                        childRes.removedInfo.removedPackage = childPkg.packageName;
18143                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18144                    }
18145                    if (res.addedChildPackages == null) {
18146                        res.addedChildPackages = new ArrayMap<>();
18147                    }
18148                    res.addedChildPackages.put(childPkg.packageName, childRes);
18149                }
18150            }
18151        }
18152
18153        // If package doesn't declare API override, mark that we have an install
18154        // time CPU ABI override.
18155        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18156            pkg.cpuAbiOverride = args.abiOverride;
18157        }
18158
18159        String pkgName = res.name = pkg.packageName;
18160        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18161            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18162                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18163                return;
18164            }
18165        }
18166
18167        try {
18168            // either use what we've been given or parse directly from the APK
18169            if (args.certificates != null) {
18170                try {
18171                    PackageParser.populateCertificates(pkg, args.certificates);
18172                } catch (PackageParserException e) {
18173                    // there was something wrong with the certificates we were given;
18174                    // try to pull them from the APK
18175                    PackageParser.collectCertificates(pkg, parseFlags);
18176                }
18177            } else {
18178                PackageParser.collectCertificates(pkg, parseFlags);
18179            }
18180        } catch (PackageParserException e) {
18181            res.setError("Failed collect during installPackageLI", e);
18182            return;
18183        }
18184
18185        // Get rid of all references to package scan path via parser.
18186        pp = null;
18187        String oldCodePath = null;
18188        boolean systemApp = false;
18189        synchronized (mPackages) {
18190            // Check if installing already existing package
18191            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18192                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18193                if (pkg.mOriginalPackages != null
18194                        && pkg.mOriginalPackages.contains(oldName)
18195                        && mPackages.containsKey(oldName)) {
18196                    // This package is derived from an original package,
18197                    // and this device has been updating from that original
18198                    // name.  We must continue using the original name, so
18199                    // rename the new package here.
18200                    pkg.setPackageName(oldName);
18201                    pkgName = pkg.packageName;
18202                    replace = true;
18203                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18204                            + oldName + " pkgName=" + pkgName);
18205                } else if (mPackages.containsKey(pkgName)) {
18206                    // This package, under its official name, already exists
18207                    // on the device; we should replace it.
18208                    replace = true;
18209                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18210                }
18211
18212                // Child packages are installed through the parent package
18213                if (pkg.parentPackage != null) {
18214                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18215                            "Package " + pkg.packageName + " is child of package "
18216                                    + pkg.parentPackage.parentPackage + ". Child packages "
18217                                    + "can be updated only through the parent package.");
18218                    return;
18219                }
18220
18221                if (replace) {
18222                    // Prevent apps opting out from runtime permissions
18223                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18224                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18225                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18226                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18227                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18228                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18229                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18230                                        + " doesn't support runtime permissions but the old"
18231                                        + " target SDK " + oldTargetSdk + " does.");
18232                        return;
18233                    }
18234                    // Prevent apps from downgrading their targetSandbox.
18235                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18236                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18237                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18238                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18239                                "Package " + pkg.packageName + " new target sandbox "
18240                                + newTargetSandbox + " is incompatible with the previous value of"
18241                                + oldTargetSandbox + ".");
18242                        return;
18243                    }
18244
18245                    // Prevent installing of child packages
18246                    if (oldPackage.parentPackage != null) {
18247                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18248                                "Package " + pkg.packageName + " is child of package "
18249                                        + oldPackage.parentPackage + ". Child packages "
18250                                        + "can be updated only through the parent package.");
18251                        return;
18252                    }
18253                }
18254            }
18255
18256            PackageSetting ps = mSettings.mPackages.get(pkgName);
18257            if (ps != null) {
18258                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18259
18260                // Static shared libs have same package with different versions where
18261                // we internally use a synthetic package name to allow multiple versions
18262                // of the same package, therefore we need to compare signatures against
18263                // the package setting for the latest library version.
18264                PackageSetting signatureCheckPs = ps;
18265                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18266                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18267                    if (libraryEntry != null) {
18268                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18269                    }
18270                }
18271
18272                // Quick sanity check that we're signed correctly if updating;
18273                // we'll check this again later when scanning, but we want to
18274                // bail early here before tripping over redefined permissions.
18275                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18276                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18277                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18278                                + pkg.packageName + " upgrade keys do not match the "
18279                                + "previously installed version");
18280                        return;
18281                    }
18282                } else {
18283                    try {
18284                        verifySignaturesLP(signatureCheckPs, pkg);
18285                    } catch (PackageManagerException e) {
18286                        res.setError(e.error, e.getMessage());
18287                        return;
18288                    }
18289                }
18290
18291                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18292                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18293                    systemApp = (ps.pkg.applicationInfo.flags &
18294                            ApplicationInfo.FLAG_SYSTEM) != 0;
18295                }
18296                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18297            }
18298
18299            int N = pkg.permissions.size();
18300            for (int i = N-1; i >= 0; i--) {
18301                PackageParser.Permission perm = pkg.permissions.get(i);
18302                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18303
18304                // Don't allow anyone but the system to define ephemeral permissions.
18305                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18306                        && !systemApp) {
18307                    Slog.w(TAG, "Non-System package " + pkg.packageName
18308                            + " attempting to delcare ephemeral permission "
18309                            + perm.info.name + "; Removing ephemeral.");
18310                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18311                }
18312
18313                // Check whether the newly-scanned package wants to define an already-defined perm
18314                if (bp != null) {
18315                    // If the defining package is signed with our cert, it's okay.  This
18316                    // also includes the "updating the same package" case, of course.
18317                    // "updating same package" could also involve key-rotation.
18318                    final boolean sigsOk;
18319                    if (bp.sourcePackage.equals(pkg.packageName)
18320                            && (bp.packageSetting instanceof PackageSetting)
18321                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18322                                    scanFlags))) {
18323                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18324                    } else {
18325                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18326                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18327                    }
18328                    if (!sigsOk) {
18329                        // If the owning package is the system itself, we log but allow
18330                        // install to proceed; we fail the install on all other permission
18331                        // redefinitions.
18332                        if (!bp.sourcePackage.equals("android")) {
18333                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18334                                    + pkg.packageName + " attempting to redeclare permission "
18335                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18336                            res.origPermission = perm.info.name;
18337                            res.origPackage = bp.sourcePackage;
18338                            return;
18339                        } else {
18340                            Slog.w(TAG, "Package " + pkg.packageName
18341                                    + " attempting to redeclare system permission "
18342                                    + perm.info.name + "; ignoring new declaration");
18343                            pkg.permissions.remove(i);
18344                        }
18345                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18346                        // Prevent apps to change protection level to dangerous from any other
18347                        // type as this would allow a privilege escalation where an app adds a
18348                        // normal/signature permission in other app's group and later redefines
18349                        // it as dangerous leading to the group auto-grant.
18350                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18351                                == PermissionInfo.PROTECTION_DANGEROUS) {
18352                            if (bp != null && !bp.isRuntime()) {
18353                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18354                                        + "non-runtime permission " + perm.info.name
18355                                        + " to runtime; keeping old protection level");
18356                                perm.info.protectionLevel = bp.protectionLevel;
18357                            }
18358                        }
18359                    }
18360                }
18361            }
18362        }
18363
18364        if (systemApp) {
18365            if (onExternal) {
18366                // Abort update; system app can't be replaced with app on sdcard
18367                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18368                        "Cannot install updates to system apps on sdcard");
18369                return;
18370            } else if (instantApp) {
18371                // Abort update; system app can't be replaced with an instant app
18372                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18373                        "Cannot update a system app with an instant app");
18374                return;
18375            }
18376        }
18377
18378        if (args.move != null) {
18379            // We did an in-place move, so dex is ready to roll
18380            scanFlags |= SCAN_NO_DEX;
18381            scanFlags |= SCAN_MOVE;
18382
18383            synchronized (mPackages) {
18384                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18385                if (ps == null) {
18386                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18387                            "Missing settings for moved package " + pkgName);
18388                }
18389
18390                // We moved the entire application as-is, so bring over the
18391                // previously derived ABI information.
18392                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18393                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18394            }
18395
18396        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18397            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18398            scanFlags |= SCAN_NO_DEX;
18399
18400            try {
18401                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18402                    args.abiOverride : pkg.cpuAbiOverride);
18403                final boolean extractNativeLibs = !pkg.isLibrary();
18404                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18405                        extractNativeLibs, mAppLib32InstallDir);
18406            } catch (PackageManagerException pme) {
18407                Slog.e(TAG, "Error deriving application ABI", pme);
18408                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18409                return;
18410            }
18411
18412            // Shared libraries for the package need to be updated.
18413            synchronized (mPackages) {
18414                try {
18415                    updateSharedLibrariesLPr(pkg, null);
18416                } catch (PackageManagerException e) {
18417                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18418                }
18419            }
18420        }
18421
18422        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18423            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18424            return;
18425        }
18426
18427        // Verify if we need to dexopt the app.
18428        //
18429        // NOTE: it is *important* to call dexopt after doRename which will sync the
18430        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18431        //
18432        // We only need to dexopt if the package meets ALL of the following conditions:
18433        //   1) it is not forward locked.
18434        //   2) it is not on on an external ASEC container.
18435        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18436        //
18437        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18438        // complete, so we skip this step during installation. Instead, we'll take extra time
18439        // the first time the instant app starts. It's preferred to do it this way to provide
18440        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18441        // middle of running an instant app. The default behaviour can be overridden
18442        // via gservices.
18443        final boolean performDexopt = !forwardLocked
18444            && !pkg.applicationInfo.isExternalAsec()
18445            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18446                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18447
18448        if (performDexopt) {
18449            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18450            // Do not run PackageDexOptimizer through the local performDexOpt
18451            // method because `pkg` may not be in `mPackages` yet.
18452            //
18453            // Also, don't fail application installs if the dexopt step fails.
18454            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18455                REASON_INSTALL,
18456                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18457            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18458                null /* instructionSets */,
18459                getOrCreateCompilerPackageStats(pkg),
18460                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18461                dexoptOptions);
18462            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18463        }
18464
18465        // Notify BackgroundDexOptService that the package has been changed.
18466        // If this is an update of a package which used to fail to compile,
18467        // BackgroundDexOptService will remove it from its blacklist.
18468        // TODO: Layering violation
18469        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18470
18471        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18472
18473        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18474                "installPackageLI")) {
18475            if (replace) {
18476                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18477                    // Static libs have a synthetic package name containing the version
18478                    // and cannot be updated as an update would get a new package name,
18479                    // unless this is the exact same version code which is useful for
18480                    // development.
18481                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18482                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18483                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18484                                + "static-shared libs cannot be updated");
18485                        return;
18486                    }
18487                }
18488                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18489                        installerPackageName, res, args.installReason);
18490            } else {
18491                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18492                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18493            }
18494        }
18495
18496        synchronized (mPackages) {
18497            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18498            if (ps != null) {
18499                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18500                ps.setUpdateAvailable(false /*updateAvailable*/);
18501            }
18502
18503            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18504            for (int i = 0; i < childCount; i++) {
18505                PackageParser.Package childPkg = pkg.childPackages.get(i);
18506                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18507                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18508                if (childPs != null) {
18509                    childRes.newUsers = childPs.queryInstalledUsers(
18510                            sUserManager.getUserIds(), true);
18511                }
18512            }
18513
18514            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18515                updateSequenceNumberLP(ps, res.newUsers);
18516                updateInstantAppInstallerLocked(pkgName);
18517            }
18518        }
18519    }
18520
18521    private void startIntentFilterVerifications(int userId, boolean replacing,
18522            PackageParser.Package pkg) {
18523        if (mIntentFilterVerifierComponent == null) {
18524            Slog.w(TAG, "No IntentFilter verification will not be done as "
18525                    + "there is no IntentFilterVerifier available!");
18526            return;
18527        }
18528
18529        final int verifierUid = getPackageUid(
18530                mIntentFilterVerifierComponent.getPackageName(),
18531                MATCH_DEBUG_TRIAGED_MISSING,
18532                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18533
18534        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18535        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18536        mHandler.sendMessage(msg);
18537
18538        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18539        for (int i = 0; i < childCount; i++) {
18540            PackageParser.Package childPkg = pkg.childPackages.get(i);
18541            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18542            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18543            mHandler.sendMessage(msg);
18544        }
18545    }
18546
18547    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18548            PackageParser.Package pkg) {
18549        int size = pkg.activities.size();
18550        if (size == 0) {
18551            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18552                    "No activity, so no need to verify any IntentFilter!");
18553            return;
18554        }
18555
18556        final boolean hasDomainURLs = hasDomainURLs(pkg);
18557        if (!hasDomainURLs) {
18558            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18559                    "No domain URLs, so no need to verify any IntentFilter!");
18560            return;
18561        }
18562
18563        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18564                + " if any IntentFilter from the " + size
18565                + " Activities needs verification ...");
18566
18567        int count = 0;
18568        final String packageName = pkg.packageName;
18569
18570        synchronized (mPackages) {
18571            // If this is a new install and we see that we've already run verification for this
18572            // package, we have nothing to do: it means the state was restored from backup.
18573            if (!replacing) {
18574                IntentFilterVerificationInfo ivi =
18575                        mSettings.getIntentFilterVerificationLPr(packageName);
18576                if (ivi != null) {
18577                    if (DEBUG_DOMAIN_VERIFICATION) {
18578                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18579                                + ivi.getStatusString());
18580                    }
18581                    return;
18582                }
18583            }
18584
18585            // If any filters need to be verified, then all need to be.
18586            boolean needToVerify = false;
18587            for (PackageParser.Activity a : pkg.activities) {
18588                for (ActivityIntentInfo filter : a.intents) {
18589                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18590                        if (DEBUG_DOMAIN_VERIFICATION) {
18591                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18592                        }
18593                        needToVerify = true;
18594                        break;
18595                    }
18596                }
18597            }
18598
18599            if (needToVerify) {
18600                final int verificationId = mIntentFilterVerificationToken++;
18601                for (PackageParser.Activity a : pkg.activities) {
18602                    for (ActivityIntentInfo filter : a.intents) {
18603                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18604                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18605                                    "Verification needed for IntentFilter:" + filter.toString());
18606                            mIntentFilterVerifier.addOneIntentFilterVerification(
18607                                    verifierUid, userId, verificationId, filter, packageName);
18608                            count++;
18609                        }
18610                    }
18611                }
18612            }
18613        }
18614
18615        if (count > 0) {
18616            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18617                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18618                    +  " for userId:" + userId);
18619            mIntentFilterVerifier.startVerifications(userId);
18620        } else {
18621            if (DEBUG_DOMAIN_VERIFICATION) {
18622                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18623            }
18624        }
18625    }
18626
18627    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18628        final ComponentName cn  = filter.activity.getComponentName();
18629        final String packageName = cn.getPackageName();
18630
18631        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18632                packageName);
18633        if (ivi == null) {
18634            return true;
18635        }
18636        int status = ivi.getStatus();
18637        switch (status) {
18638            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18639            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18640                return true;
18641
18642            default:
18643                // Nothing to do
18644                return false;
18645        }
18646    }
18647
18648    private static boolean isMultiArch(ApplicationInfo info) {
18649        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18650    }
18651
18652    private static boolean isExternal(PackageParser.Package pkg) {
18653        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18654    }
18655
18656    private static boolean isExternal(PackageSetting ps) {
18657        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18658    }
18659
18660    private static boolean isSystemApp(PackageParser.Package pkg) {
18661        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18662    }
18663
18664    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18665        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18666    }
18667
18668    private static boolean isOemApp(PackageParser.Package pkg) {
18669        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
18670    }
18671
18672    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18673        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18674    }
18675
18676    private static boolean isSystemApp(PackageSetting ps) {
18677        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18678    }
18679
18680    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18681        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18682    }
18683
18684    private int packageFlagsToInstallFlags(PackageSetting ps) {
18685        int installFlags = 0;
18686        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18687            // This existing package was an external ASEC install when we have
18688            // the external flag without a UUID
18689            installFlags |= PackageManager.INSTALL_EXTERNAL;
18690        }
18691        if (ps.isForwardLocked()) {
18692            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18693        }
18694        return installFlags;
18695    }
18696
18697    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18698        if (isExternal(pkg)) {
18699            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18700                return StorageManager.UUID_PRIMARY_PHYSICAL;
18701            } else {
18702                return pkg.volumeUuid;
18703            }
18704        } else {
18705            return StorageManager.UUID_PRIVATE_INTERNAL;
18706        }
18707    }
18708
18709    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18710        if (isExternal(pkg)) {
18711            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18712                return mSettings.getExternalVersion();
18713            } else {
18714                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18715            }
18716        } else {
18717            return mSettings.getInternalVersion();
18718        }
18719    }
18720
18721    private void deleteTempPackageFiles() {
18722        final FilenameFilter filter = new FilenameFilter() {
18723            public boolean accept(File dir, String name) {
18724                return name.startsWith("vmdl") && name.endsWith(".tmp");
18725            }
18726        };
18727        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18728            file.delete();
18729        }
18730    }
18731
18732    @Override
18733    public void deletePackageAsUser(String packageName, int versionCode,
18734            IPackageDeleteObserver observer, int userId, int flags) {
18735        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18736                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18737    }
18738
18739    @Override
18740    public void deletePackageVersioned(VersionedPackage versionedPackage,
18741            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18742        final int callingUid = Binder.getCallingUid();
18743        mContext.enforceCallingOrSelfPermission(
18744                android.Manifest.permission.DELETE_PACKAGES, null);
18745        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18746        Preconditions.checkNotNull(versionedPackage);
18747        Preconditions.checkNotNull(observer);
18748        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18749                PackageManager.VERSION_CODE_HIGHEST,
18750                Integer.MAX_VALUE, "versionCode must be >= -1");
18751
18752        final String packageName = versionedPackage.getPackageName();
18753        final int versionCode = versionedPackage.getVersionCode();
18754        final String internalPackageName;
18755        synchronized (mPackages) {
18756            // Normalize package name to handle renamed packages and static libs
18757            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18758                    versionedPackage.getVersionCode());
18759        }
18760
18761        final int uid = Binder.getCallingUid();
18762        if (!isOrphaned(internalPackageName)
18763                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18764            try {
18765                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18766                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18767                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18768                observer.onUserActionRequired(intent);
18769            } catch (RemoteException re) {
18770            }
18771            return;
18772        }
18773        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18774        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18775        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18776            mContext.enforceCallingOrSelfPermission(
18777                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18778                    "deletePackage for user " + userId);
18779        }
18780
18781        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18782            try {
18783                observer.onPackageDeleted(packageName,
18784                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18785            } catch (RemoteException re) {
18786            }
18787            return;
18788        }
18789
18790        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18791            try {
18792                observer.onPackageDeleted(packageName,
18793                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18794            } catch (RemoteException re) {
18795            }
18796            return;
18797        }
18798
18799        if (DEBUG_REMOVE) {
18800            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18801                    + " deleteAllUsers: " + deleteAllUsers + " version="
18802                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18803                    ? "VERSION_CODE_HIGHEST" : versionCode));
18804        }
18805        // Queue up an async operation since the package deletion may take a little while.
18806        mHandler.post(new Runnable() {
18807            public void run() {
18808                mHandler.removeCallbacks(this);
18809                int returnCode;
18810                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18811                boolean doDeletePackage = true;
18812                if (ps != null) {
18813                    final boolean targetIsInstantApp =
18814                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18815                    doDeletePackage = !targetIsInstantApp
18816                            || canViewInstantApps;
18817                }
18818                if (doDeletePackage) {
18819                    if (!deleteAllUsers) {
18820                        returnCode = deletePackageX(internalPackageName, versionCode,
18821                                userId, deleteFlags);
18822                    } else {
18823                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18824                                internalPackageName, users);
18825                        // If nobody is blocking uninstall, proceed with delete for all users
18826                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18827                            returnCode = deletePackageX(internalPackageName, versionCode,
18828                                    userId, deleteFlags);
18829                        } else {
18830                            // Otherwise uninstall individually for users with blockUninstalls=false
18831                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18832                            for (int userId : users) {
18833                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18834                                    returnCode = deletePackageX(internalPackageName, versionCode,
18835                                            userId, userFlags);
18836                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18837                                        Slog.w(TAG, "Package delete failed for user " + userId
18838                                                + ", returnCode " + returnCode);
18839                                    }
18840                                }
18841                            }
18842                            // The app has only been marked uninstalled for certain users.
18843                            // We still need to report that delete was blocked
18844                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18845                        }
18846                    }
18847                } else {
18848                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18849                }
18850                try {
18851                    observer.onPackageDeleted(packageName, returnCode, null);
18852                } catch (RemoteException e) {
18853                    Log.i(TAG, "Observer no longer exists.");
18854                } //end catch
18855            } //end run
18856        });
18857    }
18858
18859    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18860        if (pkg.staticSharedLibName != null) {
18861            return pkg.manifestPackageName;
18862        }
18863        return pkg.packageName;
18864    }
18865
18866    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18867        // Handle renamed packages
18868        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18869        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18870
18871        // Is this a static library?
18872        SparseArray<SharedLibraryEntry> versionedLib =
18873                mStaticLibsByDeclaringPackage.get(packageName);
18874        if (versionedLib == null || versionedLib.size() <= 0) {
18875            return packageName;
18876        }
18877
18878        // Figure out which lib versions the caller can see
18879        SparseIntArray versionsCallerCanSee = null;
18880        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18881        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18882                && callingAppId != Process.ROOT_UID) {
18883            versionsCallerCanSee = new SparseIntArray();
18884            String libName = versionedLib.valueAt(0).info.getName();
18885            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18886            if (uidPackages != null) {
18887                for (String uidPackage : uidPackages) {
18888                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18889                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18890                    if (libIdx >= 0) {
18891                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18892                        versionsCallerCanSee.append(libVersion, libVersion);
18893                    }
18894                }
18895            }
18896        }
18897
18898        // Caller can see nothing - done
18899        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18900            return packageName;
18901        }
18902
18903        // Find the version the caller can see and the app version code
18904        SharedLibraryEntry highestVersion = null;
18905        final int versionCount = versionedLib.size();
18906        for (int i = 0; i < versionCount; i++) {
18907            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18908            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18909                    libEntry.info.getVersion()) < 0) {
18910                continue;
18911            }
18912            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18913            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18914                if (libVersionCode == versionCode) {
18915                    return libEntry.apk;
18916                }
18917            } else if (highestVersion == null) {
18918                highestVersion = libEntry;
18919            } else if (libVersionCode  > highestVersion.info
18920                    .getDeclaringPackage().getVersionCode()) {
18921                highestVersion = libEntry;
18922            }
18923        }
18924
18925        if (highestVersion != null) {
18926            return highestVersion.apk;
18927        }
18928
18929        return packageName;
18930    }
18931
18932    boolean isCallerVerifier(int callingUid) {
18933        final int callingUserId = UserHandle.getUserId(callingUid);
18934        return mRequiredVerifierPackage != null &&
18935                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
18936    }
18937
18938    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18939        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18940              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18941            return true;
18942        }
18943        final int callingUserId = UserHandle.getUserId(callingUid);
18944        // If the caller installed the pkgName, then allow it to silently uninstall.
18945        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18946            return true;
18947        }
18948
18949        // Allow package verifier to silently uninstall.
18950        if (mRequiredVerifierPackage != null &&
18951                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18952            return true;
18953        }
18954
18955        // Allow package uninstaller to silently uninstall.
18956        if (mRequiredUninstallerPackage != null &&
18957                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18958            return true;
18959        }
18960
18961        // Allow storage manager to silently uninstall.
18962        if (mStorageManagerPackage != null &&
18963                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18964            return true;
18965        }
18966
18967        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18968        // uninstall for device owner provisioning.
18969        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18970                == PERMISSION_GRANTED) {
18971            return true;
18972        }
18973
18974        return false;
18975    }
18976
18977    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18978        int[] result = EMPTY_INT_ARRAY;
18979        for (int userId : userIds) {
18980            if (getBlockUninstallForUser(packageName, userId)) {
18981                result = ArrayUtils.appendInt(result, userId);
18982            }
18983        }
18984        return result;
18985    }
18986
18987    @Override
18988    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18989        final int callingUid = Binder.getCallingUid();
18990        if (getInstantAppPackageName(callingUid) != null
18991                && !isCallerSameApp(packageName, callingUid)) {
18992            return false;
18993        }
18994        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18995    }
18996
18997    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18998        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18999                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19000        try {
19001            if (dpm != null) {
19002                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19003                        /* callingUserOnly =*/ false);
19004                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19005                        : deviceOwnerComponentName.getPackageName();
19006                // Does the package contains the device owner?
19007                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19008                // this check is probably not needed, since DO should be registered as a device
19009                // admin on some user too. (Original bug for this: b/17657954)
19010                if (packageName.equals(deviceOwnerPackageName)) {
19011                    return true;
19012                }
19013                // Does it contain a device admin for any user?
19014                int[] users;
19015                if (userId == UserHandle.USER_ALL) {
19016                    users = sUserManager.getUserIds();
19017                } else {
19018                    users = new int[]{userId};
19019                }
19020                for (int i = 0; i < users.length; ++i) {
19021                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19022                        return true;
19023                    }
19024                }
19025            }
19026        } catch (RemoteException e) {
19027        }
19028        return false;
19029    }
19030
19031    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19032        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19033    }
19034
19035    /**
19036     *  This method is an internal method that could be get invoked either
19037     *  to delete an installed package or to clean up a failed installation.
19038     *  After deleting an installed package, a broadcast is sent to notify any
19039     *  listeners that the package has been removed. For cleaning up a failed
19040     *  installation, the broadcast is not necessary since the package's
19041     *  installation wouldn't have sent the initial broadcast either
19042     *  The key steps in deleting a package are
19043     *  deleting the package information in internal structures like mPackages,
19044     *  deleting the packages base directories through installd
19045     *  updating mSettings to reflect current status
19046     *  persisting settings for later use
19047     *  sending a broadcast if necessary
19048     */
19049    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19050        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19051        final boolean res;
19052
19053        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19054                ? UserHandle.USER_ALL : userId;
19055
19056        if (isPackageDeviceAdmin(packageName, removeUser)) {
19057            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19058            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19059        }
19060
19061        PackageSetting uninstalledPs = null;
19062        PackageParser.Package pkg = null;
19063
19064        // for the uninstall-updates case and restricted profiles, remember the per-
19065        // user handle installed state
19066        int[] allUsers;
19067        synchronized (mPackages) {
19068            uninstalledPs = mSettings.mPackages.get(packageName);
19069            if (uninstalledPs == null) {
19070                Slog.w(TAG, "Not removing non-existent package " + packageName);
19071                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19072            }
19073
19074            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19075                    && uninstalledPs.versionCode != versionCode) {
19076                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19077                        + uninstalledPs.versionCode + " != " + versionCode);
19078                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19079            }
19080
19081            // Static shared libs can be declared by any package, so let us not
19082            // allow removing a package if it provides a lib others depend on.
19083            pkg = mPackages.get(packageName);
19084
19085            allUsers = sUserManager.getUserIds();
19086
19087            if (pkg != null && pkg.staticSharedLibName != null) {
19088                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19089                        pkg.staticSharedLibVersion);
19090                if (libEntry != null) {
19091                    for (int currUserId : allUsers) {
19092                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19093                            continue;
19094                        }
19095                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19096                                libEntry.info, 0, currUserId);
19097                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19098                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19099                                    + " hosting lib " + libEntry.info.getName() + " version "
19100                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19101                                    + " for user " + currUserId);
19102                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19103                        }
19104                    }
19105                }
19106            }
19107
19108            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19109        }
19110
19111        final int freezeUser;
19112        if (isUpdatedSystemApp(uninstalledPs)
19113                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19114            // We're downgrading a system app, which will apply to all users, so
19115            // freeze them all during the downgrade
19116            freezeUser = UserHandle.USER_ALL;
19117        } else {
19118            freezeUser = removeUser;
19119        }
19120
19121        synchronized (mInstallLock) {
19122            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19123            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19124                    deleteFlags, "deletePackageX")) {
19125                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19126                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19127            }
19128            synchronized (mPackages) {
19129                if (res) {
19130                    if (pkg != null) {
19131                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19132                    }
19133                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19134                    updateInstantAppInstallerLocked(packageName);
19135                }
19136            }
19137        }
19138
19139        if (res) {
19140            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19141            info.sendPackageRemovedBroadcasts(killApp);
19142            info.sendSystemPackageUpdatedBroadcasts();
19143            info.sendSystemPackageAppearedBroadcasts();
19144        }
19145        // Force a gc here.
19146        Runtime.getRuntime().gc();
19147        // Delete the resources here after sending the broadcast to let
19148        // other processes clean up before deleting resources.
19149        if (info.args != null) {
19150            synchronized (mInstallLock) {
19151                info.args.doPostDeleteLI(true);
19152            }
19153        }
19154
19155        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19156    }
19157
19158    static class PackageRemovedInfo {
19159        final PackageSender packageSender;
19160        String removedPackage;
19161        String installerPackageName;
19162        int uid = -1;
19163        int removedAppId = -1;
19164        int[] origUsers;
19165        int[] removedUsers = null;
19166        int[] broadcastUsers = null;
19167        SparseArray<Integer> installReasons;
19168        boolean isRemovedPackageSystemUpdate = false;
19169        boolean isUpdate;
19170        boolean dataRemoved;
19171        boolean removedForAllUsers;
19172        boolean isStaticSharedLib;
19173        // Clean up resources deleted packages.
19174        InstallArgs args = null;
19175        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19176        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19177
19178        PackageRemovedInfo(PackageSender packageSender) {
19179            this.packageSender = packageSender;
19180        }
19181
19182        void sendPackageRemovedBroadcasts(boolean killApp) {
19183            sendPackageRemovedBroadcastInternal(killApp);
19184            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19185            for (int i = 0; i < childCount; i++) {
19186                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19187                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19188            }
19189        }
19190
19191        void sendSystemPackageUpdatedBroadcasts() {
19192            if (isRemovedPackageSystemUpdate) {
19193                sendSystemPackageUpdatedBroadcastsInternal();
19194                final int childCount = (removedChildPackages != null)
19195                        ? removedChildPackages.size() : 0;
19196                for (int i = 0; i < childCount; i++) {
19197                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19198                    if (childInfo.isRemovedPackageSystemUpdate) {
19199                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19200                    }
19201                }
19202            }
19203        }
19204
19205        void sendSystemPackageAppearedBroadcasts() {
19206            final int packageCount = (appearedChildPackages != null)
19207                    ? appearedChildPackages.size() : 0;
19208            for (int i = 0; i < packageCount; i++) {
19209                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19210                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19211                    true /*sendBootCompleted*/, false /*startReceiver*/,
19212                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19213            }
19214        }
19215
19216        private void sendSystemPackageUpdatedBroadcastsInternal() {
19217            Bundle extras = new Bundle(2);
19218            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19219            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19220            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19221                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19222            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19223                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19224            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19225                null, null, 0, removedPackage, null, null);
19226            if (installerPackageName != null) {
19227                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19228                        removedPackage, extras, 0 /*flags*/,
19229                        installerPackageName, null, null);
19230                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19231                        removedPackage, extras, 0 /*flags*/,
19232                        installerPackageName, null, null);
19233            }
19234        }
19235
19236        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19237            // Don't send static shared library removal broadcasts as these
19238            // libs are visible only the the apps that depend on them an one
19239            // cannot remove the library if it has a dependency.
19240            if (isStaticSharedLib) {
19241                return;
19242            }
19243            Bundle extras = new Bundle(2);
19244            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19245            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19246            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19247            if (isUpdate || isRemovedPackageSystemUpdate) {
19248                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19249            }
19250            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19251            if (removedPackage != null) {
19252                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19253                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19254                if (installerPackageName != null) {
19255                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19256                            removedPackage, extras, 0 /*flags*/,
19257                            installerPackageName, null, broadcastUsers);
19258                }
19259                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19260                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19261                        removedPackage, extras,
19262                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19263                        null, null, broadcastUsers);
19264                }
19265            }
19266            if (removedAppId >= 0) {
19267                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19268                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19269                    null, null, broadcastUsers);
19270            }
19271        }
19272
19273        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19274            removedUsers = userIds;
19275            if (removedUsers == null) {
19276                broadcastUsers = null;
19277                return;
19278            }
19279
19280            broadcastUsers = EMPTY_INT_ARRAY;
19281            for (int i = userIds.length - 1; i >= 0; --i) {
19282                final int userId = userIds[i];
19283                if (deletedPackageSetting.getInstantApp(userId)) {
19284                    continue;
19285                }
19286                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19287            }
19288        }
19289    }
19290
19291    /*
19292     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19293     * flag is not set, the data directory is removed as well.
19294     * make sure this flag is set for partially installed apps. If not its meaningless to
19295     * delete a partially installed application.
19296     */
19297    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19298            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19299        String packageName = ps.name;
19300        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19301        // Retrieve object to delete permissions for shared user later on
19302        final PackageParser.Package deletedPkg;
19303        final PackageSetting deletedPs;
19304        // reader
19305        synchronized (mPackages) {
19306            deletedPkg = mPackages.get(packageName);
19307            deletedPs = mSettings.mPackages.get(packageName);
19308            if (outInfo != null) {
19309                outInfo.removedPackage = packageName;
19310                outInfo.installerPackageName = ps.installerPackageName;
19311                outInfo.isStaticSharedLib = deletedPkg != null
19312                        && deletedPkg.staticSharedLibName != null;
19313                outInfo.populateUsers(deletedPs == null ? null
19314                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19315            }
19316        }
19317
19318        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19319
19320        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19321            final PackageParser.Package resolvedPkg;
19322            if (deletedPkg != null) {
19323                resolvedPkg = deletedPkg;
19324            } else {
19325                // We don't have a parsed package when it lives on an ejected
19326                // adopted storage device, so fake something together
19327                resolvedPkg = new PackageParser.Package(ps.name);
19328                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19329            }
19330            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19331                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19332            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19333            if (outInfo != null) {
19334                outInfo.dataRemoved = true;
19335            }
19336            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19337        }
19338
19339        int removedAppId = -1;
19340
19341        // writer
19342        synchronized (mPackages) {
19343            boolean installedStateChanged = false;
19344            if (deletedPs != null) {
19345                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19346                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19347                    clearDefaultBrowserIfNeeded(packageName);
19348                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19349                    removedAppId = mSettings.removePackageLPw(packageName);
19350                    if (outInfo != null) {
19351                        outInfo.removedAppId = removedAppId;
19352                    }
19353                    updatePermissionsLPw(deletedPs.name, null, 0);
19354                    if (deletedPs.sharedUser != null) {
19355                        // Remove permissions associated with package. Since runtime
19356                        // permissions are per user we have to kill the removed package
19357                        // or packages running under the shared user of the removed
19358                        // package if revoking the permissions requested only by the removed
19359                        // package is successful and this causes a change in gids.
19360                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19361                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19362                                    userId);
19363                            if (userIdToKill == UserHandle.USER_ALL
19364                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19365                                // If gids changed for this user, kill all affected packages.
19366                                mHandler.post(new Runnable() {
19367                                    @Override
19368                                    public void run() {
19369                                        // This has to happen with no lock held.
19370                                        killApplication(deletedPs.name, deletedPs.appId,
19371                                                KILL_APP_REASON_GIDS_CHANGED);
19372                                    }
19373                                });
19374                                break;
19375                            }
19376                        }
19377                    }
19378                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19379                }
19380                // make sure to preserve per-user disabled state if this removal was just
19381                // a downgrade of a system app to the factory package
19382                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19383                    if (DEBUG_REMOVE) {
19384                        Slog.d(TAG, "Propagating install state across downgrade");
19385                    }
19386                    for (int userId : allUserHandles) {
19387                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19388                        if (DEBUG_REMOVE) {
19389                            Slog.d(TAG, "    user " + userId + " => " + installed);
19390                        }
19391                        if (installed != ps.getInstalled(userId)) {
19392                            installedStateChanged = true;
19393                        }
19394                        ps.setInstalled(installed, userId);
19395                    }
19396                }
19397            }
19398            // can downgrade to reader
19399            if (writeSettings) {
19400                // Save settings now
19401                mSettings.writeLPr();
19402            }
19403            if (installedStateChanged) {
19404                mSettings.writeKernelMappingLPr(ps);
19405            }
19406        }
19407        if (removedAppId != -1) {
19408            // A user ID was deleted here. Go through all users and remove it
19409            // from KeyStore.
19410            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19411        }
19412    }
19413
19414    static boolean locationIsPrivileged(File path) {
19415        try {
19416            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19417                    .getCanonicalPath();
19418            return path.getCanonicalPath().startsWith(privilegedAppDir);
19419        } catch (IOException e) {
19420            Slog.e(TAG, "Unable to access code path " + path);
19421        }
19422        return false;
19423    }
19424
19425    static boolean locationIsOem(File path) {
19426        try {
19427            return path.getCanonicalPath().startsWith(
19428                    Environment.getOemDirectory().getCanonicalPath());
19429        } catch (IOException e) {
19430            Slog.e(TAG, "Unable to access code path " + path);
19431        }
19432        return false;
19433    }
19434
19435    /*
19436     * Tries to delete system package.
19437     */
19438    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19439            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19440            boolean writeSettings) {
19441        if (deletedPs.parentPackageName != null) {
19442            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19443            return false;
19444        }
19445
19446        final boolean applyUserRestrictions
19447                = (allUserHandles != null) && (outInfo.origUsers != null);
19448        final PackageSetting disabledPs;
19449        // Confirm if the system package has been updated
19450        // An updated system app can be deleted. This will also have to restore
19451        // the system pkg from system partition
19452        // reader
19453        synchronized (mPackages) {
19454            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19455        }
19456
19457        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19458                + " disabledPs=" + disabledPs);
19459
19460        if (disabledPs == null) {
19461            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19462            return false;
19463        } else if (DEBUG_REMOVE) {
19464            Slog.d(TAG, "Deleting system pkg from data partition");
19465        }
19466
19467        if (DEBUG_REMOVE) {
19468            if (applyUserRestrictions) {
19469                Slog.d(TAG, "Remembering install states:");
19470                for (int userId : allUserHandles) {
19471                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19472                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19473                }
19474            }
19475        }
19476
19477        // Delete the updated package
19478        outInfo.isRemovedPackageSystemUpdate = true;
19479        if (outInfo.removedChildPackages != null) {
19480            final int childCount = (deletedPs.childPackageNames != null)
19481                    ? deletedPs.childPackageNames.size() : 0;
19482            for (int i = 0; i < childCount; i++) {
19483                String childPackageName = deletedPs.childPackageNames.get(i);
19484                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19485                        .contains(childPackageName)) {
19486                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19487                            childPackageName);
19488                    if (childInfo != null) {
19489                        childInfo.isRemovedPackageSystemUpdate = true;
19490                    }
19491                }
19492            }
19493        }
19494
19495        if (disabledPs.versionCode < deletedPs.versionCode) {
19496            // Delete data for downgrades
19497            flags &= ~PackageManager.DELETE_KEEP_DATA;
19498        } else {
19499            // Preserve data by setting flag
19500            flags |= PackageManager.DELETE_KEEP_DATA;
19501        }
19502
19503        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19504                outInfo, writeSettings, disabledPs.pkg);
19505        if (!ret) {
19506            return false;
19507        }
19508
19509        // writer
19510        synchronized (mPackages) {
19511            // NOTE: The system package always needs to be enabled; even if it's for
19512            // a compressed stub. If we don't, installing the system package fails
19513            // during scan [scanning checks the disabled packages]. We will reverse
19514            // this later, after we've "installed" the stub.
19515            // Reinstate the old system package
19516            enableSystemPackageLPw(disabledPs.pkg);
19517            // Remove any native libraries from the upgraded package.
19518            removeNativeBinariesLI(deletedPs);
19519        }
19520
19521        // Install the system package
19522        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19523        try {
19524            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19525                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19526        } catch (PackageManagerException e) {
19527            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19528                    + e.getMessage());
19529            return false;
19530        } finally {
19531            if (disabledPs.pkg.isStub) {
19532                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19533            }
19534        }
19535        return true;
19536    }
19537
19538    /**
19539     * Installs a package that's already on the system partition.
19540     */
19541    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19542            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19543            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19544                    throws PackageManagerException {
19545        int parseFlags = mDefParseFlags
19546                | PackageParser.PARSE_MUST_BE_APK
19547                | PackageParser.PARSE_IS_SYSTEM
19548                | PackageParser.PARSE_IS_SYSTEM_DIR;
19549        if (isPrivileged || locationIsPrivileged(codePath)) {
19550            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19551        }
19552        if (locationIsOem(codePath)) {
19553            parseFlags |= PackageParser.PARSE_IS_OEM;
19554        }
19555
19556        final PackageParser.Package newPkg =
19557                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19558
19559        try {
19560            // update shared libraries for the newly re-installed system package
19561            updateSharedLibrariesLPr(newPkg, null);
19562        } catch (PackageManagerException e) {
19563            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19564        }
19565
19566        prepareAppDataAfterInstallLIF(newPkg);
19567
19568        // writer
19569        synchronized (mPackages) {
19570            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19571
19572            // Propagate the permissions state as we do not want to drop on the floor
19573            // runtime permissions. The update permissions method below will take
19574            // care of removing obsolete permissions and grant install permissions.
19575            if (origPermissionState != null) {
19576                ps.getPermissionsState().copyFrom(origPermissionState);
19577            }
19578            updatePermissionsLPw(newPkg.packageName, newPkg,
19579                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19580
19581            final boolean applyUserRestrictions
19582                    = (allUserHandles != null) && (origUserHandles != null);
19583            if (applyUserRestrictions) {
19584                boolean installedStateChanged = false;
19585                if (DEBUG_REMOVE) {
19586                    Slog.d(TAG, "Propagating install state across reinstall");
19587                }
19588                for (int userId : allUserHandles) {
19589                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19590                    if (DEBUG_REMOVE) {
19591                        Slog.d(TAG, "    user " + userId + " => " + installed);
19592                    }
19593                    if (installed != ps.getInstalled(userId)) {
19594                        installedStateChanged = true;
19595                    }
19596                    ps.setInstalled(installed, userId);
19597
19598                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19599                }
19600                // Regardless of writeSettings we need to ensure that this restriction
19601                // state propagation is persisted
19602                mSettings.writeAllUsersPackageRestrictionsLPr();
19603                if (installedStateChanged) {
19604                    mSettings.writeKernelMappingLPr(ps);
19605                }
19606            }
19607            // can downgrade to reader here
19608            if (writeSettings) {
19609                mSettings.writeLPr();
19610            }
19611        }
19612        return newPkg;
19613    }
19614
19615    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19616            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19617            PackageRemovedInfo outInfo, boolean writeSettings,
19618            PackageParser.Package replacingPackage) {
19619        synchronized (mPackages) {
19620            if (outInfo != null) {
19621                outInfo.uid = ps.appId;
19622            }
19623
19624            if (outInfo != null && outInfo.removedChildPackages != null) {
19625                final int childCount = (ps.childPackageNames != null)
19626                        ? ps.childPackageNames.size() : 0;
19627                for (int i = 0; i < childCount; i++) {
19628                    String childPackageName = ps.childPackageNames.get(i);
19629                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19630                    if (childPs == null) {
19631                        return false;
19632                    }
19633                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19634                            childPackageName);
19635                    if (childInfo != null) {
19636                        childInfo.uid = childPs.appId;
19637                    }
19638                }
19639            }
19640        }
19641
19642        // Delete package data from internal structures and also remove data if flag is set
19643        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19644
19645        // Delete the child packages data
19646        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19647        for (int i = 0; i < childCount; i++) {
19648            PackageSetting childPs;
19649            synchronized (mPackages) {
19650                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19651            }
19652            if (childPs != null) {
19653                PackageRemovedInfo childOutInfo = (outInfo != null
19654                        && outInfo.removedChildPackages != null)
19655                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19656                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19657                        && (replacingPackage != null
19658                        && !replacingPackage.hasChildPackage(childPs.name))
19659                        ? flags & ~DELETE_KEEP_DATA : flags;
19660                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19661                        deleteFlags, writeSettings);
19662            }
19663        }
19664
19665        // Delete application code and resources only for parent packages
19666        if (ps.parentPackageName == null) {
19667            if (deleteCodeAndResources && (outInfo != null)) {
19668                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19669                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19670                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19671            }
19672        }
19673
19674        return true;
19675    }
19676
19677    @Override
19678    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19679            int userId) {
19680        mContext.enforceCallingOrSelfPermission(
19681                android.Manifest.permission.DELETE_PACKAGES, null);
19682        synchronized (mPackages) {
19683            // Cannot block uninstall of static shared libs as they are
19684            // considered a part of the using app (emulating static linking).
19685            // Also static libs are installed always on internal storage.
19686            PackageParser.Package pkg = mPackages.get(packageName);
19687            if (pkg != null && pkg.staticSharedLibName != null) {
19688                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19689                        + " providing static shared library: " + pkg.staticSharedLibName);
19690                return false;
19691            }
19692            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19693            mSettings.writePackageRestrictionsLPr(userId);
19694        }
19695        return true;
19696    }
19697
19698    @Override
19699    public boolean getBlockUninstallForUser(String packageName, int userId) {
19700        synchronized (mPackages) {
19701            final PackageSetting ps = mSettings.mPackages.get(packageName);
19702            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19703                return false;
19704            }
19705            return mSettings.getBlockUninstallLPr(userId, packageName);
19706        }
19707    }
19708
19709    @Override
19710    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19711        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19712        synchronized (mPackages) {
19713            PackageSetting ps = mSettings.mPackages.get(packageName);
19714            if (ps == null) {
19715                Log.w(TAG, "Package doesn't exist: " + packageName);
19716                return false;
19717            }
19718            if (systemUserApp) {
19719                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19720            } else {
19721                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19722            }
19723            mSettings.writeLPr();
19724        }
19725        return true;
19726    }
19727
19728    /*
19729     * This method handles package deletion in general
19730     */
19731    private boolean deletePackageLIF(String packageName, UserHandle user,
19732            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19733            PackageRemovedInfo outInfo, boolean writeSettings,
19734            PackageParser.Package replacingPackage) {
19735        if (packageName == null) {
19736            Slog.w(TAG, "Attempt to delete null packageName.");
19737            return false;
19738        }
19739
19740        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19741
19742        PackageSetting ps;
19743        synchronized (mPackages) {
19744            ps = mSettings.mPackages.get(packageName);
19745            if (ps == null) {
19746                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19747                return false;
19748            }
19749
19750            if (ps.parentPackageName != null && (!isSystemApp(ps)
19751                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19752                if (DEBUG_REMOVE) {
19753                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19754                            + ((user == null) ? UserHandle.USER_ALL : user));
19755                }
19756                final int removedUserId = (user != null) ? user.getIdentifier()
19757                        : UserHandle.USER_ALL;
19758                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19759                    return false;
19760                }
19761                markPackageUninstalledForUserLPw(ps, user);
19762                scheduleWritePackageRestrictionsLocked(user);
19763                return true;
19764            }
19765        }
19766
19767        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19768                && user.getIdentifier() != UserHandle.USER_ALL)) {
19769            // The caller is asking that the package only be deleted for a single
19770            // user.  To do this, we just mark its uninstalled state and delete
19771            // its data. If this is a system app, we only allow this to happen if
19772            // they have set the special DELETE_SYSTEM_APP which requests different
19773            // semantics than normal for uninstalling system apps.
19774            markPackageUninstalledForUserLPw(ps, user);
19775
19776            if (!isSystemApp(ps)) {
19777                // Do not uninstall the APK if an app should be cached
19778                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19779                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19780                    // Other user still have this package installed, so all
19781                    // we need to do is clear this user's data and save that
19782                    // it is uninstalled.
19783                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19784                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19785                        return false;
19786                    }
19787                    scheduleWritePackageRestrictionsLocked(user);
19788                    return true;
19789                } else {
19790                    // We need to set it back to 'installed' so the uninstall
19791                    // broadcasts will be sent correctly.
19792                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19793                    ps.setInstalled(true, user.getIdentifier());
19794                    mSettings.writeKernelMappingLPr(ps);
19795                }
19796            } else {
19797                // This is a system app, so we assume that the
19798                // other users still have this package installed, so all
19799                // we need to do is clear this user's data and save that
19800                // it is uninstalled.
19801                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19802                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19803                    return false;
19804                }
19805                scheduleWritePackageRestrictionsLocked(user);
19806                return true;
19807            }
19808        }
19809
19810        // If we are deleting a composite package for all users, keep track
19811        // of result for each child.
19812        if (ps.childPackageNames != null && outInfo != null) {
19813            synchronized (mPackages) {
19814                final int childCount = ps.childPackageNames.size();
19815                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19816                for (int i = 0; i < childCount; i++) {
19817                    String childPackageName = ps.childPackageNames.get(i);
19818                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19819                    childInfo.removedPackage = childPackageName;
19820                    childInfo.installerPackageName = ps.installerPackageName;
19821                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19822                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19823                    if (childPs != null) {
19824                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19825                    }
19826                }
19827            }
19828        }
19829
19830        boolean ret = false;
19831        if (isSystemApp(ps)) {
19832            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19833            // When an updated system application is deleted we delete the existing resources
19834            // as well and fall back to existing code in system partition
19835            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19836        } else {
19837            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19838            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19839                    outInfo, writeSettings, replacingPackage);
19840        }
19841
19842        // Take a note whether we deleted the package for all users
19843        if (outInfo != null) {
19844            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19845            if (outInfo.removedChildPackages != null) {
19846                synchronized (mPackages) {
19847                    final int childCount = outInfo.removedChildPackages.size();
19848                    for (int i = 0; i < childCount; i++) {
19849                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19850                        if (childInfo != null) {
19851                            childInfo.removedForAllUsers = mPackages.get(
19852                                    childInfo.removedPackage) == null;
19853                        }
19854                    }
19855                }
19856            }
19857            // If we uninstalled an update to a system app there may be some
19858            // child packages that appeared as they are declared in the system
19859            // app but were not declared in the update.
19860            if (isSystemApp(ps)) {
19861                synchronized (mPackages) {
19862                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19863                    final int childCount = (updatedPs.childPackageNames != null)
19864                            ? updatedPs.childPackageNames.size() : 0;
19865                    for (int i = 0; i < childCount; i++) {
19866                        String childPackageName = updatedPs.childPackageNames.get(i);
19867                        if (outInfo.removedChildPackages == null
19868                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19869                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19870                            if (childPs == null) {
19871                                continue;
19872                            }
19873                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19874                            installRes.name = childPackageName;
19875                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19876                            installRes.pkg = mPackages.get(childPackageName);
19877                            installRes.uid = childPs.pkg.applicationInfo.uid;
19878                            if (outInfo.appearedChildPackages == null) {
19879                                outInfo.appearedChildPackages = new ArrayMap<>();
19880                            }
19881                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19882                        }
19883                    }
19884                }
19885            }
19886        }
19887
19888        return ret;
19889    }
19890
19891    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19892        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19893                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19894        for (int nextUserId : userIds) {
19895            if (DEBUG_REMOVE) {
19896                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19897            }
19898            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19899                    false /*installed*/,
19900                    true /*stopped*/,
19901                    true /*notLaunched*/,
19902                    false /*hidden*/,
19903                    false /*suspended*/,
19904                    false /*instantApp*/,
19905                    false /*virtualPreload*/,
19906                    null /*lastDisableAppCaller*/,
19907                    null /*enabledComponents*/,
19908                    null /*disabledComponents*/,
19909                    ps.readUserState(nextUserId).domainVerificationStatus,
19910                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19911        }
19912        mSettings.writeKernelMappingLPr(ps);
19913    }
19914
19915    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19916            PackageRemovedInfo outInfo) {
19917        final PackageParser.Package pkg;
19918        synchronized (mPackages) {
19919            pkg = mPackages.get(ps.name);
19920        }
19921
19922        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19923                : new int[] {userId};
19924        for (int nextUserId : userIds) {
19925            if (DEBUG_REMOVE) {
19926                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19927                        + nextUserId);
19928            }
19929
19930            destroyAppDataLIF(pkg, userId,
19931                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19932            destroyAppProfilesLIF(pkg, userId);
19933            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19934            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19935            schedulePackageCleaning(ps.name, nextUserId, false);
19936            synchronized (mPackages) {
19937                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19938                    scheduleWritePackageRestrictionsLocked(nextUserId);
19939                }
19940                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19941            }
19942        }
19943
19944        if (outInfo != null) {
19945            outInfo.removedPackage = ps.name;
19946            outInfo.installerPackageName = ps.installerPackageName;
19947            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19948            outInfo.removedAppId = ps.appId;
19949            outInfo.removedUsers = userIds;
19950            outInfo.broadcastUsers = userIds;
19951        }
19952
19953        return true;
19954    }
19955
19956    private final class ClearStorageConnection implements ServiceConnection {
19957        IMediaContainerService mContainerService;
19958
19959        @Override
19960        public void onServiceConnected(ComponentName name, IBinder service) {
19961            synchronized (this) {
19962                mContainerService = IMediaContainerService.Stub
19963                        .asInterface(Binder.allowBlocking(service));
19964                notifyAll();
19965            }
19966        }
19967
19968        @Override
19969        public void onServiceDisconnected(ComponentName name) {
19970        }
19971    }
19972
19973    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19974        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19975
19976        final boolean mounted;
19977        if (Environment.isExternalStorageEmulated()) {
19978            mounted = true;
19979        } else {
19980            final String status = Environment.getExternalStorageState();
19981
19982            mounted = status.equals(Environment.MEDIA_MOUNTED)
19983                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19984        }
19985
19986        if (!mounted) {
19987            return;
19988        }
19989
19990        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19991        int[] users;
19992        if (userId == UserHandle.USER_ALL) {
19993            users = sUserManager.getUserIds();
19994        } else {
19995            users = new int[] { userId };
19996        }
19997        final ClearStorageConnection conn = new ClearStorageConnection();
19998        if (mContext.bindServiceAsUser(
19999                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20000            try {
20001                for (int curUser : users) {
20002                    long timeout = SystemClock.uptimeMillis() + 5000;
20003                    synchronized (conn) {
20004                        long now;
20005                        while (conn.mContainerService == null &&
20006                                (now = SystemClock.uptimeMillis()) < timeout) {
20007                            try {
20008                                conn.wait(timeout - now);
20009                            } catch (InterruptedException e) {
20010                            }
20011                        }
20012                    }
20013                    if (conn.mContainerService == null) {
20014                        return;
20015                    }
20016
20017                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20018                    clearDirectory(conn.mContainerService,
20019                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20020                    if (allData) {
20021                        clearDirectory(conn.mContainerService,
20022                                userEnv.buildExternalStorageAppDataDirs(packageName));
20023                        clearDirectory(conn.mContainerService,
20024                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20025                    }
20026                }
20027            } finally {
20028                mContext.unbindService(conn);
20029            }
20030        }
20031    }
20032
20033    @Override
20034    public void clearApplicationProfileData(String packageName) {
20035        enforceSystemOrRoot("Only the system can clear all profile data");
20036
20037        final PackageParser.Package pkg;
20038        synchronized (mPackages) {
20039            pkg = mPackages.get(packageName);
20040        }
20041
20042        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20043            synchronized (mInstallLock) {
20044                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20045            }
20046        }
20047    }
20048
20049    @Override
20050    public void clearApplicationUserData(final String packageName,
20051            final IPackageDataObserver observer, final int userId) {
20052        mContext.enforceCallingOrSelfPermission(
20053                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20054
20055        final int callingUid = Binder.getCallingUid();
20056        enforceCrossUserPermission(callingUid, userId,
20057                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20058
20059        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20060        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20061        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20062            throw new SecurityException("Cannot clear data for a protected package: "
20063                    + packageName);
20064        }
20065        // Queue up an async operation since the package deletion may take a little while.
20066        mHandler.post(new Runnable() {
20067            public void run() {
20068                mHandler.removeCallbacks(this);
20069                final boolean succeeded;
20070                if (!filterApp) {
20071                    try (PackageFreezer freezer = freezePackage(packageName,
20072                            "clearApplicationUserData")) {
20073                        synchronized (mInstallLock) {
20074                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20075                        }
20076                        clearExternalStorageDataSync(packageName, userId, true);
20077                        synchronized (mPackages) {
20078                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20079                                    packageName, userId);
20080                        }
20081                    }
20082                    if (succeeded) {
20083                        // invoke DeviceStorageMonitor's update method to clear any notifications
20084                        DeviceStorageMonitorInternal dsm = LocalServices
20085                                .getService(DeviceStorageMonitorInternal.class);
20086                        if (dsm != null) {
20087                            dsm.checkMemory();
20088                        }
20089                    }
20090                } else {
20091                    succeeded = false;
20092                }
20093                if (observer != null) {
20094                    try {
20095                        observer.onRemoveCompleted(packageName, succeeded);
20096                    } catch (RemoteException e) {
20097                        Log.i(TAG, "Observer no longer exists.");
20098                    }
20099                } //end if observer
20100            } //end run
20101        });
20102    }
20103
20104    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20105        if (packageName == null) {
20106            Slog.w(TAG, "Attempt to delete null packageName.");
20107            return false;
20108        }
20109
20110        // Try finding details about the requested package
20111        PackageParser.Package pkg;
20112        synchronized (mPackages) {
20113            pkg = mPackages.get(packageName);
20114            if (pkg == null) {
20115                final PackageSetting ps = mSettings.mPackages.get(packageName);
20116                if (ps != null) {
20117                    pkg = ps.pkg;
20118                }
20119            }
20120
20121            if (pkg == null) {
20122                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20123                return false;
20124            }
20125
20126            PackageSetting ps = (PackageSetting) pkg.mExtras;
20127            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20128        }
20129
20130        clearAppDataLIF(pkg, userId,
20131                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20132
20133        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20134        removeKeystoreDataIfNeeded(userId, appId);
20135
20136        UserManagerInternal umInternal = getUserManagerInternal();
20137        final int flags;
20138        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20139            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20140        } else if (umInternal.isUserRunning(userId)) {
20141            flags = StorageManager.FLAG_STORAGE_DE;
20142        } else {
20143            flags = 0;
20144        }
20145        prepareAppDataContentsLIF(pkg, userId, flags);
20146
20147        return true;
20148    }
20149
20150    /**
20151     * Reverts user permission state changes (permissions and flags) in
20152     * all packages for a given user.
20153     *
20154     * @param userId The device user for which to do a reset.
20155     */
20156    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20157        final int packageCount = mPackages.size();
20158        for (int i = 0; i < packageCount; i++) {
20159            PackageParser.Package pkg = mPackages.valueAt(i);
20160            PackageSetting ps = (PackageSetting) pkg.mExtras;
20161            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20162        }
20163    }
20164
20165    private void resetNetworkPolicies(int userId) {
20166        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20167    }
20168
20169    /**
20170     * Reverts user permission state changes (permissions and flags).
20171     *
20172     * @param ps The package for which to reset.
20173     * @param userId The device user for which to do a reset.
20174     */
20175    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20176            final PackageSetting ps, final int userId) {
20177        if (ps.pkg == null) {
20178            return;
20179        }
20180
20181        // These are flags that can change base on user actions.
20182        final int userSettableMask = FLAG_PERMISSION_USER_SET
20183                | FLAG_PERMISSION_USER_FIXED
20184                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20185                | FLAG_PERMISSION_REVIEW_REQUIRED;
20186
20187        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20188                | FLAG_PERMISSION_POLICY_FIXED;
20189
20190        boolean writeInstallPermissions = false;
20191        boolean writeRuntimePermissions = false;
20192
20193        final int permissionCount = ps.pkg.requestedPermissions.size();
20194        for (int i = 0; i < permissionCount; i++) {
20195            String permission = ps.pkg.requestedPermissions.get(i);
20196
20197            BasePermission bp = mSettings.mPermissions.get(permission);
20198            if (bp == null) {
20199                continue;
20200            }
20201
20202            // If shared user we just reset the state to which only this app contributed.
20203            if (ps.sharedUser != null) {
20204                boolean used = false;
20205                final int packageCount = ps.sharedUser.packages.size();
20206                for (int j = 0; j < packageCount; j++) {
20207                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20208                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20209                            && pkg.pkg.requestedPermissions.contains(permission)) {
20210                        used = true;
20211                        break;
20212                    }
20213                }
20214                if (used) {
20215                    continue;
20216                }
20217            }
20218
20219            PermissionsState permissionsState = ps.getPermissionsState();
20220
20221            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20222
20223            // Always clear the user settable flags.
20224            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20225                    bp.name) != null;
20226            // If permission review is enabled and this is a legacy app, mark the
20227            // permission as requiring a review as this is the initial state.
20228            int flags = 0;
20229            if (mPermissionReviewRequired
20230                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20231                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20232            }
20233            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20234                if (hasInstallState) {
20235                    writeInstallPermissions = true;
20236                } else {
20237                    writeRuntimePermissions = true;
20238                }
20239            }
20240
20241            // Below is only runtime permission handling.
20242            if (!bp.isRuntime()) {
20243                continue;
20244            }
20245
20246            // Never clobber system or policy.
20247            if ((oldFlags & policyOrSystemFlags) != 0) {
20248                continue;
20249            }
20250
20251            // If this permission was granted by default, make sure it is.
20252            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20253                if (permissionsState.grantRuntimePermission(bp, userId)
20254                        != PERMISSION_OPERATION_FAILURE) {
20255                    writeRuntimePermissions = true;
20256                }
20257            // If permission review is enabled the permissions for a legacy apps
20258            // are represented as constantly granted runtime ones, so don't revoke.
20259            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20260                // Otherwise, reset the permission.
20261                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20262                switch (revokeResult) {
20263                    case PERMISSION_OPERATION_SUCCESS:
20264                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20265                        writeRuntimePermissions = true;
20266                        final int appId = ps.appId;
20267                        mHandler.post(new Runnable() {
20268                            @Override
20269                            public void run() {
20270                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20271                            }
20272                        });
20273                    } break;
20274                }
20275            }
20276        }
20277
20278        // Synchronously write as we are taking permissions away.
20279        if (writeRuntimePermissions) {
20280            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20281        }
20282
20283        // Synchronously write as we are taking permissions away.
20284        if (writeInstallPermissions) {
20285            mSettings.writeLPr();
20286        }
20287    }
20288
20289    /**
20290     * Remove entries from the keystore daemon. Will only remove it if the
20291     * {@code appId} is valid.
20292     */
20293    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20294        if (appId < 0) {
20295            return;
20296        }
20297
20298        final KeyStore keyStore = KeyStore.getInstance();
20299        if (keyStore != null) {
20300            if (userId == UserHandle.USER_ALL) {
20301                for (final int individual : sUserManager.getUserIds()) {
20302                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20303                }
20304            } else {
20305                keyStore.clearUid(UserHandle.getUid(userId, appId));
20306            }
20307        } else {
20308            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20309        }
20310    }
20311
20312    @Override
20313    public void deleteApplicationCacheFiles(final String packageName,
20314            final IPackageDataObserver observer) {
20315        final int userId = UserHandle.getCallingUserId();
20316        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20317    }
20318
20319    @Override
20320    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20321            final IPackageDataObserver observer) {
20322        final int callingUid = Binder.getCallingUid();
20323        mContext.enforceCallingOrSelfPermission(
20324                android.Manifest.permission.DELETE_CACHE_FILES, null);
20325        enforceCrossUserPermission(callingUid, userId,
20326                /* requireFullPermission= */ true, /* checkShell= */ false,
20327                "delete application cache files");
20328        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20329                android.Manifest.permission.ACCESS_INSTANT_APPS);
20330
20331        final PackageParser.Package pkg;
20332        synchronized (mPackages) {
20333            pkg = mPackages.get(packageName);
20334        }
20335
20336        // Queue up an async operation since the package deletion may take a little while.
20337        mHandler.post(new Runnable() {
20338            public void run() {
20339                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20340                boolean doClearData = true;
20341                if (ps != null) {
20342                    final boolean targetIsInstantApp =
20343                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20344                    doClearData = !targetIsInstantApp
20345                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20346                }
20347                if (doClearData) {
20348                    synchronized (mInstallLock) {
20349                        final int flags = StorageManager.FLAG_STORAGE_DE
20350                                | StorageManager.FLAG_STORAGE_CE;
20351                        // We're only clearing cache files, so we don't care if the
20352                        // app is unfrozen and still able to run
20353                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20354                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20355                    }
20356                    clearExternalStorageDataSync(packageName, userId, false);
20357                }
20358                if (observer != null) {
20359                    try {
20360                        observer.onRemoveCompleted(packageName, true);
20361                    } catch (RemoteException e) {
20362                        Log.i(TAG, "Observer no longer exists.");
20363                    }
20364                }
20365            }
20366        });
20367    }
20368
20369    @Override
20370    public void getPackageSizeInfo(final String packageName, int userHandle,
20371            final IPackageStatsObserver observer) {
20372        throw new UnsupportedOperationException(
20373                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20374    }
20375
20376    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20377        final PackageSetting ps;
20378        synchronized (mPackages) {
20379            ps = mSettings.mPackages.get(packageName);
20380            if (ps == null) {
20381                Slog.w(TAG, "Failed to find settings for " + packageName);
20382                return false;
20383            }
20384        }
20385
20386        final String[] packageNames = { packageName };
20387        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20388        final String[] codePaths = { ps.codePathString };
20389
20390        try {
20391            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20392                    ps.appId, ceDataInodes, codePaths, stats);
20393
20394            // For now, ignore code size of packages on system partition
20395            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20396                stats.codeSize = 0;
20397            }
20398
20399            // External clients expect these to be tracked separately
20400            stats.dataSize -= stats.cacheSize;
20401
20402        } catch (InstallerException e) {
20403            Slog.w(TAG, String.valueOf(e));
20404            return false;
20405        }
20406
20407        return true;
20408    }
20409
20410    private int getUidTargetSdkVersionLockedLPr(int uid) {
20411        Object obj = mSettings.getUserIdLPr(uid);
20412        if (obj instanceof SharedUserSetting) {
20413            final SharedUserSetting sus = (SharedUserSetting) obj;
20414            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20415            final Iterator<PackageSetting> it = sus.packages.iterator();
20416            while (it.hasNext()) {
20417                final PackageSetting ps = it.next();
20418                if (ps.pkg != null) {
20419                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20420                    if (v < vers) vers = v;
20421                }
20422            }
20423            return vers;
20424        } else if (obj instanceof PackageSetting) {
20425            final PackageSetting ps = (PackageSetting) obj;
20426            if (ps.pkg != null) {
20427                return ps.pkg.applicationInfo.targetSdkVersion;
20428            }
20429        }
20430        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20431    }
20432
20433    @Override
20434    public void addPreferredActivity(IntentFilter filter, int match,
20435            ComponentName[] set, ComponentName activity, int userId) {
20436        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20437                "Adding preferred");
20438    }
20439
20440    private void addPreferredActivityInternal(IntentFilter filter, int match,
20441            ComponentName[] set, ComponentName activity, boolean always, int userId,
20442            String opname) {
20443        // writer
20444        int callingUid = Binder.getCallingUid();
20445        enforceCrossUserPermission(callingUid, userId,
20446                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20447        if (filter.countActions() == 0) {
20448            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20449            return;
20450        }
20451        synchronized (mPackages) {
20452            if (mContext.checkCallingOrSelfPermission(
20453                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20454                    != PackageManager.PERMISSION_GRANTED) {
20455                if (getUidTargetSdkVersionLockedLPr(callingUid)
20456                        < Build.VERSION_CODES.FROYO) {
20457                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20458                            + callingUid);
20459                    return;
20460                }
20461                mContext.enforceCallingOrSelfPermission(
20462                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20463            }
20464
20465            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20466            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20467                    + userId + ":");
20468            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20469            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20470            scheduleWritePackageRestrictionsLocked(userId);
20471            postPreferredActivityChangedBroadcast(userId);
20472        }
20473    }
20474
20475    private void postPreferredActivityChangedBroadcast(int userId) {
20476        mHandler.post(() -> {
20477            final IActivityManager am = ActivityManager.getService();
20478            if (am == null) {
20479                return;
20480            }
20481
20482            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20483            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20484            try {
20485                am.broadcastIntent(null, intent, null, null,
20486                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20487                        null, false, false, userId);
20488            } catch (RemoteException e) {
20489            }
20490        });
20491    }
20492
20493    @Override
20494    public void replacePreferredActivity(IntentFilter filter, int match,
20495            ComponentName[] set, ComponentName activity, int userId) {
20496        if (filter.countActions() != 1) {
20497            throw new IllegalArgumentException(
20498                    "replacePreferredActivity expects filter to have only 1 action.");
20499        }
20500        if (filter.countDataAuthorities() != 0
20501                || filter.countDataPaths() != 0
20502                || filter.countDataSchemes() > 1
20503                || filter.countDataTypes() != 0) {
20504            throw new IllegalArgumentException(
20505                    "replacePreferredActivity expects filter to have no data authorities, " +
20506                    "paths, or types; and at most one scheme.");
20507        }
20508
20509        final int callingUid = Binder.getCallingUid();
20510        enforceCrossUserPermission(callingUid, userId,
20511                true /* requireFullPermission */, false /* checkShell */,
20512                "replace preferred activity");
20513        synchronized (mPackages) {
20514            if (mContext.checkCallingOrSelfPermission(
20515                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20516                    != PackageManager.PERMISSION_GRANTED) {
20517                if (getUidTargetSdkVersionLockedLPr(callingUid)
20518                        < Build.VERSION_CODES.FROYO) {
20519                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20520                            + Binder.getCallingUid());
20521                    return;
20522                }
20523                mContext.enforceCallingOrSelfPermission(
20524                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20525            }
20526
20527            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20528            if (pir != null) {
20529                // Get all of the existing entries that exactly match this filter.
20530                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20531                if (existing != null && existing.size() == 1) {
20532                    PreferredActivity cur = existing.get(0);
20533                    if (DEBUG_PREFERRED) {
20534                        Slog.i(TAG, "Checking replace of preferred:");
20535                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20536                        if (!cur.mPref.mAlways) {
20537                            Slog.i(TAG, "  -- CUR; not mAlways!");
20538                        } else {
20539                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20540                            Slog.i(TAG, "  -- CUR: mSet="
20541                                    + Arrays.toString(cur.mPref.mSetComponents));
20542                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20543                            Slog.i(TAG, "  -- NEW: mMatch="
20544                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20545                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20546                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20547                        }
20548                    }
20549                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20550                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20551                            && cur.mPref.sameSet(set)) {
20552                        // Setting the preferred activity to what it happens to be already
20553                        if (DEBUG_PREFERRED) {
20554                            Slog.i(TAG, "Replacing with same preferred activity "
20555                                    + cur.mPref.mShortComponent + " for user "
20556                                    + userId + ":");
20557                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20558                        }
20559                        return;
20560                    }
20561                }
20562
20563                if (existing != null) {
20564                    if (DEBUG_PREFERRED) {
20565                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20566                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20567                    }
20568                    for (int i = 0; i < existing.size(); i++) {
20569                        PreferredActivity pa = existing.get(i);
20570                        if (DEBUG_PREFERRED) {
20571                            Slog.i(TAG, "Removing existing preferred activity "
20572                                    + pa.mPref.mComponent + ":");
20573                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20574                        }
20575                        pir.removeFilter(pa);
20576                    }
20577                }
20578            }
20579            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20580                    "Replacing preferred");
20581        }
20582    }
20583
20584    @Override
20585    public void clearPackagePreferredActivities(String packageName) {
20586        final int callingUid = Binder.getCallingUid();
20587        if (getInstantAppPackageName(callingUid) != null) {
20588            return;
20589        }
20590        // writer
20591        synchronized (mPackages) {
20592            PackageParser.Package pkg = mPackages.get(packageName);
20593            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20594                if (mContext.checkCallingOrSelfPermission(
20595                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20596                        != PackageManager.PERMISSION_GRANTED) {
20597                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20598                            < Build.VERSION_CODES.FROYO) {
20599                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20600                                + callingUid);
20601                        return;
20602                    }
20603                    mContext.enforceCallingOrSelfPermission(
20604                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20605                }
20606            }
20607            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20608            if (ps != null
20609                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20610                return;
20611            }
20612            int user = UserHandle.getCallingUserId();
20613            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20614                scheduleWritePackageRestrictionsLocked(user);
20615            }
20616        }
20617    }
20618
20619    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20620    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20621        ArrayList<PreferredActivity> removed = null;
20622        boolean changed = false;
20623        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20624            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20625            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20626            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20627                continue;
20628            }
20629            Iterator<PreferredActivity> it = pir.filterIterator();
20630            while (it.hasNext()) {
20631                PreferredActivity pa = it.next();
20632                // Mark entry for removal only if it matches the package name
20633                // and the entry is of type "always".
20634                if (packageName == null ||
20635                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20636                                && pa.mPref.mAlways)) {
20637                    if (removed == null) {
20638                        removed = new ArrayList<PreferredActivity>();
20639                    }
20640                    removed.add(pa);
20641                }
20642            }
20643            if (removed != null) {
20644                for (int j=0; j<removed.size(); j++) {
20645                    PreferredActivity pa = removed.get(j);
20646                    pir.removeFilter(pa);
20647                }
20648                changed = true;
20649            }
20650        }
20651        if (changed) {
20652            postPreferredActivityChangedBroadcast(userId);
20653        }
20654        return changed;
20655    }
20656
20657    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20658    private void clearIntentFilterVerificationsLPw(int userId) {
20659        final int packageCount = mPackages.size();
20660        for (int i = 0; i < packageCount; i++) {
20661            PackageParser.Package pkg = mPackages.valueAt(i);
20662            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20663        }
20664    }
20665
20666    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20667    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20668        if (userId == UserHandle.USER_ALL) {
20669            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20670                    sUserManager.getUserIds())) {
20671                for (int oneUserId : sUserManager.getUserIds()) {
20672                    scheduleWritePackageRestrictionsLocked(oneUserId);
20673                }
20674            }
20675        } else {
20676            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20677                scheduleWritePackageRestrictionsLocked(userId);
20678            }
20679        }
20680    }
20681
20682    /** Clears state for all users, and touches intent filter verification policy */
20683    void clearDefaultBrowserIfNeeded(String packageName) {
20684        for (int oneUserId : sUserManager.getUserIds()) {
20685            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20686        }
20687    }
20688
20689    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20690        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20691        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20692            if (packageName.equals(defaultBrowserPackageName)) {
20693                setDefaultBrowserPackageName(null, userId);
20694            }
20695        }
20696    }
20697
20698    @Override
20699    public void resetApplicationPreferences(int userId) {
20700        mContext.enforceCallingOrSelfPermission(
20701                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20702        final long identity = Binder.clearCallingIdentity();
20703        // writer
20704        try {
20705            synchronized (mPackages) {
20706                clearPackagePreferredActivitiesLPw(null, userId);
20707                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20708                // TODO: We have to reset the default SMS and Phone. This requires
20709                // significant refactoring to keep all default apps in the package
20710                // manager (cleaner but more work) or have the services provide
20711                // callbacks to the package manager to request a default app reset.
20712                applyFactoryDefaultBrowserLPw(userId);
20713                clearIntentFilterVerificationsLPw(userId);
20714                primeDomainVerificationsLPw(userId);
20715                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20716                scheduleWritePackageRestrictionsLocked(userId);
20717            }
20718            resetNetworkPolicies(userId);
20719        } finally {
20720            Binder.restoreCallingIdentity(identity);
20721        }
20722    }
20723
20724    @Override
20725    public int getPreferredActivities(List<IntentFilter> outFilters,
20726            List<ComponentName> outActivities, String packageName) {
20727        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20728            return 0;
20729        }
20730        int num = 0;
20731        final int userId = UserHandle.getCallingUserId();
20732        // reader
20733        synchronized (mPackages) {
20734            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20735            if (pir != null) {
20736                final Iterator<PreferredActivity> it = pir.filterIterator();
20737                while (it.hasNext()) {
20738                    final PreferredActivity pa = it.next();
20739                    if (packageName == null
20740                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20741                                    && pa.mPref.mAlways)) {
20742                        if (outFilters != null) {
20743                            outFilters.add(new IntentFilter(pa));
20744                        }
20745                        if (outActivities != null) {
20746                            outActivities.add(pa.mPref.mComponent);
20747                        }
20748                    }
20749                }
20750            }
20751        }
20752
20753        return num;
20754    }
20755
20756    @Override
20757    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20758            int userId) {
20759        int callingUid = Binder.getCallingUid();
20760        if (callingUid != Process.SYSTEM_UID) {
20761            throw new SecurityException(
20762                    "addPersistentPreferredActivity can only be run by the system");
20763        }
20764        if (filter.countActions() == 0) {
20765            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20766            return;
20767        }
20768        synchronized (mPackages) {
20769            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20770                    ":");
20771            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20772            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20773                    new PersistentPreferredActivity(filter, activity));
20774            scheduleWritePackageRestrictionsLocked(userId);
20775            postPreferredActivityChangedBroadcast(userId);
20776        }
20777    }
20778
20779    @Override
20780    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20781        int callingUid = Binder.getCallingUid();
20782        if (callingUid != Process.SYSTEM_UID) {
20783            throw new SecurityException(
20784                    "clearPackagePersistentPreferredActivities can only be run by the system");
20785        }
20786        ArrayList<PersistentPreferredActivity> removed = null;
20787        boolean changed = false;
20788        synchronized (mPackages) {
20789            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20790                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20791                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20792                        .valueAt(i);
20793                if (userId != thisUserId) {
20794                    continue;
20795                }
20796                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20797                while (it.hasNext()) {
20798                    PersistentPreferredActivity ppa = it.next();
20799                    // Mark entry for removal only if it matches the package name.
20800                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20801                        if (removed == null) {
20802                            removed = new ArrayList<PersistentPreferredActivity>();
20803                        }
20804                        removed.add(ppa);
20805                    }
20806                }
20807                if (removed != null) {
20808                    for (int j=0; j<removed.size(); j++) {
20809                        PersistentPreferredActivity ppa = removed.get(j);
20810                        ppir.removeFilter(ppa);
20811                    }
20812                    changed = true;
20813                }
20814            }
20815
20816            if (changed) {
20817                scheduleWritePackageRestrictionsLocked(userId);
20818                postPreferredActivityChangedBroadcast(userId);
20819            }
20820        }
20821    }
20822
20823    /**
20824     * Common machinery for picking apart a restored XML blob and passing
20825     * it to a caller-supplied functor to be applied to the running system.
20826     */
20827    private void restoreFromXml(XmlPullParser parser, int userId,
20828            String expectedStartTag, BlobXmlRestorer functor)
20829            throws IOException, XmlPullParserException {
20830        int type;
20831        while ((type = parser.next()) != XmlPullParser.START_TAG
20832                && type != XmlPullParser.END_DOCUMENT) {
20833        }
20834        if (type != XmlPullParser.START_TAG) {
20835            // oops didn't find a start tag?!
20836            if (DEBUG_BACKUP) {
20837                Slog.e(TAG, "Didn't find start tag during restore");
20838            }
20839            return;
20840        }
20841Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20842        // this is supposed to be TAG_PREFERRED_BACKUP
20843        if (!expectedStartTag.equals(parser.getName())) {
20844            if (DEBUG_BACKUP) {
20845                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20846            }
20847            return;
20848        }
20849
20850        // skip interfering stuff, then we're aligned with the backing implementation
20851        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20852Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20853        functor.apply(parser, userId);
20854    }
20855
20856    private interface BlobXmlRestorer {
20857        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20858    }
20859
20860    /**
20861     * Non-Binder method, support for the backup/restore mechanism: write the
20862     * full set of preferred activities in its canonical XML format.  Returns the
20863     * XML output as a byte array, or null if there is none.
20864     */
20865    @Override
20866    public byte[] getPreferredActivityBackup(int userId) {
20867        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20868            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20869        }
20870
20871        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20872        try {
20873            final XmlSerializer serializer = new FastXmlSerializer();
20874            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20875            serializer.startDocument(null, true);
20876            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20877
20878            synchronized (mPackages) {
20879                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20880            }
20881
20882            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20883            serializer.endDocument();
20884            serializer.flush();
20885        } catch (Exception e) {
20886            if (DEBUG_BACKUP) {
20887                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20888            }
20889            return null;
20890        }
20891
20892        return dataStream.toByteArray();
20893    }
20894
20895    @Override
20896    public void restorePreferredActivities(byte[] backup, int userId) {
20897        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20898            throw new SecurityException("Only the system may call restorePreferredActivities()");
20899        }
20900
20901        try {
20902            final XmlPullParser parser = Xml.newPullParser();
20903            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20904            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20905                    new BlobXmlRestorer() {
20906                        @Override
20907                        public void apply(XmlPullParser parser, int userId)
20908                                throws XmlPullParserException, IOException {
20909                            synchronized (mPackages) {
20910                                mSettings.readPreferredActivitiesLPw(parser, userId);
20911                            }
20912                        }
20913                    } );
20914        } catch (Exception e) {
20915            if (DEBUG_BACKUP) {
20916                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20917            }
20918        }
20919    }
20920
20921    /**
20922     * Non-Binder method, support for the backup/restore mechanism: write the
20923     * default browser (etc) settings in its canonical XML format.  Returns the default
20924     * browser XML representation as a byte array, or null if there is none.
20925     */
20926    @Override
20927    public byte[] getDefaultAppsBackup(int userId) {
20928        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20929            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20930        }
20931
20932        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20933        try {
20934            final XmlSerializer serializer = new FastXmlSerializer();
20935            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20936            serializer.startDocument(null, true);
20937            serializer.startTag(null, TAG_DEFAULT_APPS);
20938
20939            synchronized (mPackages) {
20940                mSettings.writeDefaultAppsLPr(serializer, userId);
20941            }
20942
20943            serializer.endTag(null, TAG_DEFAULT_APPS);
20944            serializer.endDocument();
20945            serializer.flush();
20946        } catch (Exception e) {
20947            if (DEBUG_BACKUP) {
20948                Slog.e(TAG, "Unable to write default apps for backup", e);
20949            }
20950            return null;
20951        }
20952
20953        return dataStream.toByteArray();
20954    }
20955
20956    @Override
20957    public void restoreDefaultApps(byte[] backup, int userId) {
20958        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20959            throw new SecurityException("Only the system may call restoreDefaultApps()");
20960        }
20961
20962        try {
20963            final XmlPullParser parser = Xml.newPullParser();
20964            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20965            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20966                    new BlobXmlRestorer() {
20967                        @Override
20968                        public void apply(XmlPullParser parser, int userId)
20969                                throws XmlPullParserException, IOException {
20970                            synchronized (mPackages) {
20971                                mSettings.readDefaultAppsLPw(parser, userId);
20972                            }
20973                        }
20974                    } );
20975        } catch (Exception e) {
20976            if (DEBUG_BACKUP) {
20977                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20978            }
20979        }
20980    }
20981
20982    @Override
20983    public byte[] getIntentFilterVerificationBackup(int userId) {
20984        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20985            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20986        }
20987
20988        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20989        try {
20990            final XmlSerializer serializer = new FastXmlSerializer();
20991            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20992            serializer.startDocument(null, true);
20993            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20994
20995            synchronized (mPackages) {
20996                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20997            }
20998
20999            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21000            serializer.endDocument();
21001            serializer.flush();
21002        } catch (Exception e) {
21003            if (DEBUG_BACKUP) {
21004                Slog.e(TAG, "Unable to write default apps for backup", e);
21005            }
21006            return null;
21007        }
21008
21009        return dataStream.toByteArray();
21010    }
21011
21012    @Override
21013    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21014        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21015            throw new SecurityException("Only the system may call restorePreferredActivities()");
21016        }
21017
21018        try {
21019            final XmlPullParser parser = Xml.newPullParser();
21020            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21021            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21022                    new BlobXmlRestorer() {
21023                        @Override
21024                        public void apply(XmlPullParser parser, int userId)
21025                                throws XmlPullParserException, IOException {
21026                            synchronized (mPackages) {
21027                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21028                                mSettings.writeLPr();
21029                            }
21030                        }
21031                    } );
21032        } catch (Exception e) {
21033            if (DEBUG_BACKUP) {
21034                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21035            }
21036        }
21037    }
21038
21039    @Override
21040    public byte[] getPermissionGrantBackup(int userId) {
21041        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21042            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21043        }
21044
21045        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21046        try {
21047            final XmlSerializer serializer = new FastXmlSerializer();
21048            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21049            serializer.startDocument(null, true);
21050            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21051
21052            synchronized (mPackages) {
21053                serializeRuntimePermissionGrantsLPr(serializer, userId);
21054            }
21055
21056            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21057            serializer.endDocument();
21058            serializer.flush();
21059        } catch (Exception e) {
21060            if (DEBUG_BACKUP) {
21061                Slog.e(TAG, "Unable to write default apps for backup", e);
21062            }
21063            return null;
21064        }
21065
21066        return dataStream.toByteArray();
21067    }
21068
21069    @Override
21070    public void restorePermissionGrants(byte[] backup, int userId) {
21071        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21072            throw new SecurityException("Only the system may call restorePermissionGrants()");
21073        }
21074
21075        try {
21076            final XmlPullParser parser = Xml.newPullParser();
21077            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21078            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21079                    new BlobXmlRestorer() {
21080                        @Override
21081                        public void apply(XmlPullParser parser, int userId)
21082                                throws XmlPullParserException, IOException {
21083                            synchronized (mPackages) {
21084                                processRestoredPermissionGrantsLPr(parser, userId);
21085                            }
21086                        }
21087                    } );
21088        } catch (Exception e) {
21089            if (DEBUG_BACKUP) {
21090                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21091            }
21092        }
21093    }
21094
21095    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21096            throws IOException {
21097        serializer.startTag(null, TAG_ALL_GRANTS);
21098
21099        final int N = mSettings.mPackages.size();
21100        for (int i = 0; i < N; i++) {
21101            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21102            boolean pkgGrantsKnown = false;
21103
21104            PermissionsState packagePerms = ps.getPermissionsState();
21105
21106            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21107                final int grantFlags = state.getFlags();
21108                // only look at grants that are not system/policy fixed
21109                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21110                    final boolean isGranted = state.isGranted();
21111                    // And only back up the user-twiddled state bits
21112                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21113                        final String packageName = mSettings.mPackages.keyAt(i);
21114                        if (!pkgGrantsKnown) {
21115                            serializer.startTag(null, TAG_GRANT);
21116                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21117                            pkgGrantsKnown = true;
21118                        }
21119
21120                        final boolean userSet =
21121                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21122                        final boolean userFixed =
21123                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21124                        final boolean revoke =
21125                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21126
21127                        serializer.startTag(null, TAG_PERMISSION);
21128                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21129                        if (isGranted) {
21130                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21131                        }
21132                        if (userSet) {
21133                            serializer.attribute(null, ATTR_USER_SET, "true");
21134                        }
21135                        if (userFixed) {
21136                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21137                        }
21138                        if (revoke) {
21139                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21140                        }
21141                        serializer.endTag(null, TAG_PERMISSION);
21142                    }
21143                }
21144            }
21145
21146            if (pkgGrantsKnown) {
21147                serializer.endTag(null, TAG_GRANT);
21148            }
21149        }
21150
21151        serializer.endTag(null, TAG_ALL_GRANTS);
21152    }
21153
21154    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21155            throws XmlPullParserException, IOException {
21156        String pkgName = null;
21157        int outerDepth = parser.getDepth();
21158        int type;
21159        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21160                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21161            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21162                continue;
21163            }
21164
21165            final String tagName = parser.getName();
21166            if (tagName.equals(TAG_GRANT)) {
21167                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21168                if (DEBUG_BACKUP) {
21169                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21170                }
21171            } else if (tagName.equals(TAG_PERMISSION)) {
21172
21173                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21174                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21175
21176                int newFlagSet = 0;
21177                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21178                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21179                }
21180                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21181                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21182                }
21183                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21184                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21185                }
21186                if (DEBUG_BACKUP) {
21187                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21188                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21189                }
21190                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21191                if (ps != null) {
21192                    // Already installed so we apply the grant immediately
21193                    if (DEBUG_BACKUP) {
21194                        Slog.v(TAG, "        + already installed; applying");
21195                    }
21196                    PermissionsState perms = ps.getPermissionsState();
21197                    BasePermission bp = mSettings.mPermissions.get(permName);
21198                    if (bp != null) {
21199                        if (isGranted) {
21200                            perms.grantRuntimePermission(bp, userId);
21201                        }
21202                        if (newFlagSet != 0) {
21203                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21204                        }
21205                    }
21206                } else {
21207                    // Need to wait for post-restore install to apply the grant
21208                    if (DEBUG_BACKUP) {
21209                        Slog.v(TAG, "        - not yet installed; saving for later");
21210                    }
21211                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21212                            isGranted, newFlagSet, userId);
21213                }
21214            } else {
21215                PackageManagerService.reportSettingsProblem(Log.WARN,
21216                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21217                XmlUtils.skipCurrentTag(parser);
21218            }
21219        }
21220
21221        scheduleWriteSettingsLocked();
21222        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21223    }
21224
21225    @Override
21226    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21227            int sourceUserId, int targetUserId, int flags) {
21228        mContext.enforceCallingOrSelfPermission(
21229                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21230        int callingUid = Binder.getCallingUid();
21231        enforceOwnerRights(ownerPackage, callingUid);
21232        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21233        if (intentFilter.countActions() == 0) {
21234            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21235            return;
21236        }
21237        synchronized (mPackages) {
21238            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21239                    ownerPackage, targetUserId, flags);
21240            CrossProfileIntentResolver resolver =
21241                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21242            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21243            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21244            if (existing != null) {
21245                int size = existing.size();
21246                for (int i = 0; i < size; i++) {
21247                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21248                        return;
21249                    }
21250                }
21251            }
21252            resolver.addFilter(newFilter);
21253            scheduleWritePackageRestrictionsLocked(sourceUserId);
21254        }
21255    }
21256
21257    @Override
21258    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21259        mContext.enforceCallingOrSelfPermission(
21260                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21261        final int callingUid = Binder.getCallingUid();
21262        enforceOwnerRights(ownerPackage, callingUid);
21263        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21264        synchronized (mPackages) {
21265            CrossProfileIntentResolver resolver =
21266                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21267            ArraySet<CrossProfileIntentFilter> set =
21268                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21269            for (CrossProfileIntentFilter filter : set) {
21270                if (filter.getOwnerPackage().equals(ownerPackage)) {
21271                    resolver.removeFilter(filter);
21272                }
21273            }
21274            scheduleWritePackageRestrictionsLocked(sourceUserId);
21275        }
21276    }
21277
21278    // Enforcing that callingUid is owning pkg on userId
21279    private void enforceOwnerRights(String pkg, int callingUid) {
21280        // The system owns everything.
21281        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21282            return;
21283        }
21284        final int callingUserId = UserHandle.getUserId(callingUid);
21285        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21286        if (pi == null) {
21287            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21288                    + callingUserId);
21289        }
21290        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21291            throw new SecurityException("Calling uid " + callingUid
21292                    + " does not own package " + pkg);
21293        }
21294    }
21295
21296    @Override
21297    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21298        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21299            return null;
21300        }
21301        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21302    }
21303
21304    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21305        UserManagerService ums = UserManagerService.getInstance();
21306        if (ums != null) {
21307            final UserInfo parent = ums.getProfileParent(userId);
21308            final int launcherUid = (parent != null) ? parent.id : userId;
21309            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21310            if (launcherComponent != null) {
21311                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21312                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21313                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21314                        .setPackage(launcherComponent.getPackageName());
21315                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21316            }
21317        }
21318    }
21319
21320    /**
21321     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21322     * then reports the most likely home activity or null if there are more than one.
21323     */
21324    private ComponentName getDefaultHomeActivity(int userId) {
21325        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21326        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21327        if (cn != null) {
21328            return cn;
21329        }
21330
21331        // Find the launcher with the highest priority and return that component if there are no
21332        // other home activity with the same priority.
21333        int lastPriority = Integer.MIN_VALUE;
21334        ComponentName lastComponent = null;
21335        final int size = allHomeCandidates.size();
21336        for (int i = 0; i < size; i++) {
21337            final ResolveInfo ri = allHomeCandidates.get(i);
21338            if (ri.priority > lastPriority) {
21339                lastComponent = ri.activityInfo.getComponentName();
21340                lastPriority = ri.priority;
21341            } else if (ri.priority == lastPriority) {
21342                // Two components found with same priority.
21343                lastComponent = null;
21344            }
21345        }
21346        return lastComponent;
21347    }
21348
21349    private Intent getHomeIntent() {
21350        Intent intent = new Intent(Intent.ACTION_MAIN);
21351        intent.addCategory(Intent.CATEGORY_HOME);
21352        intent.addCategory(Intent.CATEGORY_DEFAULT);
21353        return intent;
21354    }
21355
21356    private IntentFilter getHomeFilter() {
21357        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21358        filter.addCategory(Intent.CATEGORY_HOME);
21359        filter.addCategory(Intent.CATEGORY_DEFAULT);
21360        return filter;
21361    }
21362
21363    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21364            int userId) {
21365        Intent intent  = getHomeIntent();
21366        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21367                PackageManager.GET_META_DATA, userId);
21368        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21369                true, false, false, userId);
21370
21371        allHomeCandidates.clear();
21372        if (list != null) {
21373            for (ResolveInfo ri : list) {
21374                allHomeCandidates.add(ri);
21375            }
21376        }
21377        return (preferred == null || preferred.activityInfo == null)
21378                ? null
21379                : new ComponentName(preferred.activityInfo.packageName,
21380                        preferred.activityInfo.name);
21381    }
21382
21383    @Override
21384    public void setHomeActivity(ComponentName comp, int userId) {
21385        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21386            return;
21387        }
21388        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21389        getHomeActivitiesAsUser(homeActivities, userId);
21390
21391        boolean found = false;
21392
21393        final int size = homeActivities.size();
21394        final ComponentName[] set = new ComponentName[size];
21395        for (int i = 0; i < size; i++) {
21396            final ResolveInfo candidate = homeActivities.get(i);
21397            final ActivityInfo info = candidate.activityInfo;
21398            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21399            set[i] = activityName;
21400            if (!found && activityName.equals(comp)) {
21401                found = true;
21402            }
21403        }
21404        if (!found) {
21405            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21406                    + userId);
21407        }
21408        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21409                set, comp, userId);
21410    }
21411
21412    private @Nullable String getSetupWizardPackageName() {
21413        final Intent intent = new Intent(Intent.ACTION_MAIN);
21414        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21415
21416        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21417                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21418                        | MATCH_DISABLED_COMPONENTS,
21419                UserHandle.myUserId());
21420        if (matches.size() == 1) {
21421            return matches.get(0).getComponentInfo().packageName;
21422        } else {
21423            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21424                    + ": matches=" + matches);
21425            return null;
21426        }
21427    }
21428
21429    private @Nullable String getStorageManagerPackageName() {
21430        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21431
21432        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21433                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21434                        | MATCH_DISABLED_COMPONENTS,
21435                UserHandle.myUserId());
21436        if (matches.size() == 1) {
21437            return matches.get(0).getComponentInfo().packageName;
21438        } else {
21439            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21440                    + matches.size() + ": matches=" + matches);
21441            return null;
21442        }
21443    }
21444
21445    @Override
21446    public void setApplicationEnabledSetting(String appPackageName,
21447            int newState, int flags, int userId, String callingPackage) {
21448        if (!sUserManager.exists(userId)) return;
21449        if (callingPackage == null) {
21450            callingPackage = Integer.toString(Binder.getCallingUid());
21451        }
21452        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21453    }
21454
21455    @Override
21456    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21457        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21458        synchronized (mPackages) {
21459            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21460            if (pkgSetting != null) {
21461                pkgSetting.setUpdateAvailable(updateAvailable);
21462            }
21463        }
21464    }
21465
21466    @Override
21467    public void setComponentEnabledSetting(ComponentName componentName,
21468            int newState, int flags, int userId) {
21469        if (!sUserManager.exists(userId)) return;
21470        setEnabledSetting(componentName.getPackageName(),
21471                componentName.getClassName(), newState, flags, userId, null);
21472    }
21473
21474    private void setEnabledSetting(final String packageName, String className, int newState,
21475            final int flags, int userId, String callingPackage) {
21476        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21477              || newState == COMPONENT_ENABLED_STATE_ENABLED
21478              || newState == COMPONENT_ENABLED_STATE_DISABLED
21479              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21480              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21481            throw new IllegalArgumentException("Invalid new component state: "
21482                    + newState);
21483        }
21484        PackageSetting pkgSetting;
21485        final int callingUid = Binder.getCallingUid();
21486        final int permission;
21487        if (callingUid == Process.SYSTEM_UID) {
21488            permission = PackageManager.PERMISSION_GRANTED;
21489        } else {
21490            permission = mContext.checkCallingOrSelfPermission(
21491                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21492        }
21493        enforceCrossUserPermission(callingUid, userId,
21494                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21495        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21496        boolean sendNow = false;
21497        boolean isApp = (className == null);
21498        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21499        String componentName = isApp ? packageName : className;
21500        int packageUid = -1;
21501        ArrayList<String> components;
21502
21503        // reader
21504        synchronized (mPackages) {
21505            pkgSetting = mSettings.mPackages.get(packageName);
21506            if (pkgSetting == null) {
21507                if (!isCallerInstantApp) {
21508                    if (className == null) {
21509                        throw new IllegalArgumentException("Unknown package: " + packageName);
21510                    }
21511                    throw new IllegalArgumentException(
21512                            "Unknown component: " + packageName + "/" + className);
21513                } else {
21514                    // throw SecurityException to prevent leaking package information
21515                    throw new SecurityException(
21516                            "Attempt to change component state; "
21517                            + "pid=" + Binder.getCallingPid()
21518                            + ", uid=" + callingUid
21519                            + (className == null
21520                                    ? ", package=" + packageName
21521                                    : ", component=" + packageName + "/" + className));
21522                }
21523            }
21524        }
21525
21526        // Limit who can change which apps
21527        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21528            // Don't allow apps that don't have permission to modify other apps
21529            if (!allowedByPermission
21530                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21531                throw new SecurityException(
21532                        "Attempt to change component state; "
21533                        + "pid=" + Binder.getCallingPid()
21534                        + ", uid=" + callingUid
21535                        + (className == null
21536                                ? ", package=" + packageName
21537                                : ", component=" + packageName + "/" + className));
21538            }
21539            // Don't allow changing protected packages.
21540            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21541                throw new SecurityException("Cannot disable a protected package: " + packageName);
21542            }
21543        }
21544
21545        synchronized (mPackages) {
21546            if (callingUid == Process.SHELL_UID
21547                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21548                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21549                // unless it is a test package.
21550                int oldState = pkgSetting.getEnabled(userId);
21551                if (className == null
21552                        &&
21553                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21554                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21555                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21556                        &&
21557                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21558                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21559                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21560                    // ok
21561                } else {
21562                    throw new SecurityException(
21563                            "Shell cannot change component state for " + packageName + "/"
21564                                    + className + " to " + newState);
21565                }
21566            }
21567        }
21568        if (className == null) {
21569            // We're dealing with an application/package level state change
21570            synchronized (mPackages) {
21571                if (pkgSetting.getEnabled(userId) == newState) {
21572                    // Nothing to do
21573                    return;
21574                }
21575            }
21576            // If we're enabling a system stub, there's a little more work to do.
21577            // Prior to enabling the package, we need to decompress the APK(s) to the
21578            // data partition and then replace the version on the system partition.
21579            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21580            final boolean isSystemStub = deletedPkg.isStub
21581                    && deletedPkg.isSystemApp();
21582            if (isSystemStub
21583                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21584                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21585                final File codePath = decompressPackage(deletedPkg);
21586                if (codePath == null) {
21587                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21588                    return;
21589                }
21590                // TODO remove direct parsing of the package object during internal cleanup
21591                // of scan package
21592                // We need to call parse directly here for no other reason than we need
21593                // the new package in order to disable the old one [we use the information
21594                // for some internal optimization to optionally create a new package setting
21595                // object on replace]. However, we can't get the package from the scan
21596                // because the scan modifies live structures and we need to remove the
21597                // old [system] package from the system before a scan can be attempted.
21598                // Once scan is indempotent we can remove this parse and use the package
21599                // object we scanned, prior to adding it to package settings.
21600                final PackageParser pp = new PackageParser();
21601                pp.setSeparateProcesses(mSeparateProcesses);
21602                pp.setDisplayMetrics(mMetrics);
21603                pp.setCallback(mPackageParserCallback);
21604                final PackageParser.Package tmpPkg;
21605                try {
21606                    final int parseFlags = mDefParseFlags
21607                            | PackageParser.PARSE_MUST_BE_APK
21608                            | PackageParser.PARSE_IS_SYSTEM
21609                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21610                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21611                } catch (PackageParserException e) {
21612                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21613                    return;
21614                }
21615                synchronized (mInstallLock) {
21616                    // Disable the stub and remove any package entries
21617                    removePackageLI(deletedPkg, true);
21618                    synchronized (mPackages) {
21619                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21620                    }
21621                    final PackageParser.Package newPkg;
21622                    try (PackageFreezer freezer =
21623                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21624                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21625                                | PackageParser.PARSE_ENFORCE_CODE;
21626                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21627                                0 /*currentTime*/, null /*user*/);
21628                        prepareAppDataAfterInstallLIF(newPkg);
21629                        synchronized (mPackages) {
21630                            try {
21631                                updateSharedLibrariesLPr(newPkg, null);
21632                            } catch (PackageManagerException e) {
21633                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21634                            }
21635                            updatePermissionsLPw(newPkg.packageName, newPkg,
21636                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21637                            mSettings.writeLPr();
21638                        }
21639                    } catch (PackageManagerException e) {
21640                        // Whoops! Something went wrong; try to roll back to the stub
21641                        Slog.w(TAG, "Failed to install compressed system package:"
21642                                + pkgSetting.name, e);
21643                        // Remove the failed install
21644                        removeCodePathLI(codePath);
21645
21646                        // Install the system package
21647                        try (PackageFreezer freezer =
21648                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21649                            synchronized (mPackages) {
21650                                // NOTE: The system package always needs to be enabled; even
21651                                // if it's for a compressed stub. If we don't, installing the
21652                                // system package fails during scan [scanning checks the disabled
21653                                // packages]. We will reverse this later, after we've "installed"
21654                                // the stub.
21655                                // This leaves us in a fragile state; the stub should never be
21656                                // enabled, so, cross your fingers and hope nothing goes wrong
21657                                // until we can disable the package later.
21658                                enableSystemPackageLPw(deletedPkg);
21659                            }
21660                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
21661                                    false /*isPrivileged*/, null /*allUserHandles*/,
21662                                    null /*origUserHandles*/, null /*origPermissionsState*/,
21663                                    true /*writeSettings*/);
21664                        } catch (PackageManagerException pme) {
21665                            Slog.w(TAG, "Failed to restore system package:"
21666                                    + deletedPkg.packageName, pme);
21667                        } finally {
21668                            synchronized (mPackages) {
21669                                mSettings.disableSystemPackageLPw(
21670                                        deletedPkg.packageName, true /*replaced*/);
21671                                mSettings.writeLPr();
21672                            }
21673                        }
21674                        return;
21675                    }
21676                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
21677                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21678                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
21679                    mDexManager.notifyPackageUpdated(newPkg.packageName,
21680                            newPkg.baseCodePath, newPkg.splitCodePaths);
21681                }
21682            }
21683            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21684                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21685                // Don't care about who enables an app.
21686                callingPackage = null;
21687            }
21688            synchronized (mPackages) {
21689                pkgSetting.setEnabled(newState, userId, callingPackage);
21690            }
21691        } else {
21692            synchronized (mPackages) {
21693                // We're dealing with a component level state change
21694                // First, verify that this is a valid class name.
21695                PackageParser.Package pkg = pkgSetting.pkg;
21696                if (pkg == null || !pkg.hasComponentClassName(className)) {
21697                    if (pkg != null &&
21698                            pkg.applicationInfo.targetSdkVersion >=
21699                                    Build.VERSION_CODES.JELLY_BEAN) {
21700                        throw new IllegalArgumentException("Component class " + className
21701                                + " does not exist in " + packageName);
21702                    } else {
21703                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21704                                + className + " does not exist in " + packageName);
21705                    }
21706                }
21707                switch (newState) {
21708                    case COMPONENT_ENABLED_STATE_ENABLED:
21709                        if (!pkgSetting.enableComponentLPw(className, userId)) {
21710                            return;
21711                        }
21712                        break;
21713                    case COMPONENT_ENABLED_STATE_DISABLED:
21714                        if (!pkgSetting.disableComponentLPw(className, userId)) {
21715                            return;
21716                        }
21717                        break;
21718                    case COMPONENT_ENABLED_STATE_DEFAULT:
21719                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
21720                            return;
21721                        }
21722                        break;
21723                    default:
21724                        Slog.e(TAG, "Invalid new component state: " + newState);
21725                        return;
21726                }
21727            }
21728        }
21729        synchronized (mPackages) {
21730            scheduleWritePackageRestrictionsLocked(userId);
21731            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21732            final long callingId = Binder.clearCallingIdentity();
21733            try {
21734                updateInstantAppInstallerLocked(packageName);
21735            } finally {
21736                Binder.restoreCallingIdentity(callingId);
21737            }
21738            components = mPendingBroadcasts.get(userId, packageName);
21739            final boolean newPackage = components == null;
21740            if (newPackage) {
21741                components = new ArrayList<String>();
21742            }
21743            if (!components.contains(componentName)) {
21744                components.add(componentName);
21745            }
21746            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21747                sendNow = true;
21748                // Purge entry from pending broadcast list if another one exists already
21749                // since we are sending one right away.
21750                mPendingBroadcasts.remove(userId, packageName);
21751            } else {
21752                if (newPackage) {
21753                    mPendingBroadcasts.put(userId, packageName, components);
21754                }
21755                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21756                    // Schedule a message
21757                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21758                }
21759            }
21760        }
21761
21762        long callingId = Binder.clearCallingIdentity();
21763        try {
21764            if (sendNow) {
21765                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21766                sendPackageChangedBroadcast(packageName,
21767                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21768            }
21769        } finally {
21770            Binder.restoreCallingIdentity(callingId);
21771        }
21772    }
21773
21774    @Override
21775    public void flushPackageRestrictionsAsUser(int userId) {
21776        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21777            return;
21778        }
21779        if (!sUserManager.exists(userId)) {
21780            return;
21781        }
21782        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21783                false /* checkShell */, "flushPackageRestrictions");
21784        synchronized (mPackages) {
21785            mSettings.writePackageRestrictionsLPr(userId);
21786            mDirtyUsers.remove(userId);
21787            if (mDirtyUsers.isEmpty()) {
21788                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21789            }
21790        }
21791    }
21792
21793    private void sendPackageChangedBroadcast(String packageName,
21794            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21795        if (DEBUG_INSTALL)
21796            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21797                    + componentNames);
21798        Bundle extras = new Bundle(4);
21799        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21800        String nameList[] = new String[componentNames.size()];
21801        componentNames.toArray(nameList);
21802        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21803        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21804        extras.putInt(Intent.EXTRA_UID, packageUid);
21805        // If this is not reporting a change of the overall package, then only send it
21806        // to registered receivers.  We don't want to launch a swath of apps for every
21807        // little component state change.
21808        final int flags = !componentNames.contains(packageName)
21809                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21810        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21811                new int[] {UserHandle.getUserId(packageUid)});
21812    }
21813
21814    @Override
21815    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21816        if (!sUserManager.exists(userId)) return;
21817        final int callingUid = Binder.getCallingUid();
21818        if (getInstantAppPackageName(callingUid) != null) {
21819            return;
21820        }
21821        final int permission = mContext.checkCallingOrSelfPermission(
21822                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21823        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21824        enforceCrossUserPermission(callingUid, userId,
21825                true /* requireFullPermission */, true /* checkShell */, "stop package");
21826        // writer
21827        synchronized (mPackages) {
21828            final PackageSetting ps = mSettings.mPackages.get(packageName);
21829            if (!filterAppAccessLPr(ps, callingUid, userId)
21830                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21831                            allowedByPermission, callingUid, userId)) {
21832                scheduleWritePackageRestrictionsLocked(userId);
21833            }
21834        }
21835    }
21836
21837    @Override
21838    public String getInstallerPackageName(String packageName) {
21839        final int callingUid = Binder.getCallingUid();
21840        if (getInstantAppPackageName(callingUid) != null) {
21841            return null;
21842        }
21843        // reader
21844        synchronized (mPackages) {
21845            final PackageSetting ps = mSettings.mPackages.get(packageName);
21846            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21847                return null;
21848            }
21849            return mSettings.getInstallerPackageNameLPr(packageName);
21850        }
21851    }
21852
21853    public boolean isOrphaned(String packageName) {
21854        // reader
21855        synchronized (mPackages) {
21856            return mSettings.isOrphaned(packageName);
21857        }
21858    }
21859
21860    @Override
21861    public int getApplicationEnabledSetting(String packageName, int userId) {
21862        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21863        int callingUid = Binder.getCallingUid();
21864        enforceCrossUserPermission(callingUid, userId,
21865                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21866        // reader
21867        synchronized (mPackages) {
21868            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21869                return COMPONENT_ENABLED_STATE_DISABLED;
21870            }
21871            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21872        }
21873    }
21874
21875    @Override
21876    public int getComponentEnabledSetting(ComponentName component, int userId) {
21877        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21878        int callingUid = Binder.getCallingUid();
21879        enforceCrossUserPermission(callingUid, userId,
21880                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21881        synchronized (mPackages) {
21882            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21883                    component, TYPE_UNKNOWN, userId)) {
21884                return COMPONENT_ENABLED_STATE_DISABLED;
21885            }
21886            return mSettings.getComponentEnabledSettingLPr(component, userId);
21887        }
21888    }
21889
21890    @Override
21891    public void enterSafeMode() {
21892        enforceSystemOrRoot("Only the system can request entering safe mode");
21893
21894        if (!mSystemReady) {
21895            mSafeMode = true;
21896        }
21897    }
21898
21899    @Override
21900    public void systemReady() {
21901        enforceSystemOrRoot("Only the system can claim the system is ready");
21902
21903        mSystemReady = true;
21904        final ContentResolver resolver = mContext.getContentResolver();
21905        ContentObserver co = new ContentObserver(mHandler) {
21906            @Override
21907            public void onChange(boolean selfChange) {
21908                mEphemeralAppsDisabled =
21909                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21910                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21911            }
21912        };
21913        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21914                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21915                false, co, UserHandle.USER_SYSTEM);
21916        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21917                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21918        co.onChange(true);
21919
21920        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21921        // disabled after already being started.
21922        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21923                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21924
21925        // Read the compatibilty setting when the system is ready.
21926        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21927                mContext.getContentResolver(),
21928                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21929        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21930        if (DEBUG_SETTINGS) {
21931            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21932        }
21933
21934        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21935
21936        synchronized (mPackages) {
21937            // Verify that all of the preferred activity components actually
21938            // exist.  It is possible for applications to be updated and at
21939            // that point remove a previously declared activity component that
21940            // had been set as a preferred activity.  We try to clean this up
21941            // the next time we encounter that preferred activity, but it is
21942            // possible for the user flow to never be able to return to that
21943            // situation so here we do a sanity check to make sure we haven't
21944            // left any junk around.
21945            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21946            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21947                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21948                removed.clear();
21949                for (PreferredActivity pa : pir.filterSet()) {
21950                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21951                        removed.add(pa);
21952                    }
21953                }
21954                if (removed.size() > 0) {
21955                    for (int r=0; r<removed.size(); r++) {
21956                        PreferredActivity pa = removed.get(r);
21957                        Slog.w(TAG, "Removing dangling preferred activity: "
21958                                + pa.mPref.mComponent);
21959                        pir.removeFilter(pa);
21960                    }
21961                    mSettings.writePackageRestrictionsLPr(
21962                            mSettings.mPreferredActivities.keyAt(i));
21963                }
21964            }
21965
21966            for (int userId : UserManagerService.getInstance().getUserIds()) {
21967                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21968                    grantPermissionsUserIds = ArrayUtils.appendInt(
21969                            grantPermissionsUserIds, userId);
21970                }
21971            }
21972        }
21973        sUserManager.systemReady();
21974
21975        // If we upgraded grant all default permissions before kicking off.
21976        for (int userId : grantPermissionsUserIds) {
21977            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21978        }
21979
21980        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21981            // If we did not grant default permissions, we preload from this the
21982            // default permission exceptions lazily to ensure we don't hit the
21983            // disk on a new user creation.
21984            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21985        }
21986
21987        // Now that we've scanned all packages, and granted any default
21988        // permissions, ensure permissions are updated. Beware of dragons if you
21989        // try optimizing this.
21990        synchronized (mPackages) {
21991            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
21992                    UPDATE_PERMISSIONS_ALL);
21993        }
21994
21995        // Kick off any messages waiting for system ready
21996        if (mPostSystemReadyMessages != null) {
21997            for (Message msg : mPostSystemReadyMessages) {
21998                msg.sendToTarget();
21999            }
22000            mPostSystemReadyMessages = null;
22001        }
22002
22003        // Watch for external volumes that come and go over time
22004        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22005        storage.registerListener(mStorageListener);
22006
22007        mInstallerService.systemReady();
22008        mPackageDexOptimizer.systemReady();
22009
22010        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22011                StorageManagerInternal.class);
22012        StorageManagerInternal.addExternalStoragePolicy(
22013                new StorageManagerInternal.ExternalStorageMountPolicy() {
22014            @Override
22015            public int getMountMode(int uid, String packageName) {
22016                if (Process.isIsolated(uid)) {
22017                    return Zygote.MOUNT_EXTERNAL_NONE;
22018                }
22019                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22020                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22021                }
22022                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22023                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22024                }
22025                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22026                    return Zygote.MOUNT_EXTERNAL_READ;
22027                }
22028                return Zygote.MOUNT_EXTERNAL_WRITE;
22029            }
22030
22031            @Override
22032            public boolean hasExternalStorage(int uid, String packageName) {
22033                return true;
22034            }
22035        });
22036
22037        // Now that we're mostly running, clean up stale users and apps
22038        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22039        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22040
22041        if (mPrivappPermissionsViolations != null) {
22042            Slog.wtf(TAG,"Signature|privileged permissions not in "
22043                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22044            mPrivappPermissionsViolations = null;
22045        }
22046    }
22047
22048    public void waitForAppDataPrepared() {
22049        if (mPrepareAppDataFuture == null) {
22050            return;
22051        }
22052        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22053        mPrepareAppDataFuture = null;
22054    }
22055
22056    @Override
22057    public boolean isSafeMode() {
22058        // allow instant applications
22059        return mSafeMode;
22060    }
22061
22062    @Override
22063    public boolean hasSystemUidErrors() {
22064        // allow instant applications
22065        return mHasSystemUidErrors;
22066    }
22067
22068    static String arrayToString(int[] array) {
22069        StringBuffer buf = new StringBuffer(128);
22070        buf.append('[');
22071        if (array != null) {
22072            for (int i=0; i<array.length; i++) {
22073                if (i > 0) buf.append(", ");
22074                buf.append(array[i]);
22075            }
22076        }
22077        buf.append(']');
22078        return buf.toString();
22079    }
22080
22081    static class DumpState {
22082        public static final int DUMP_LIBS = 1 << 0;
22083        public static final int DUMP_FEATURES = 1 << 1;
22084        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22085        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22086        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22087        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22088        public static final int DUMP_PERMISSIONS = 1 << 6;
22089        public static final int DUMP_PACKAGES = 1 << 7;
22090        public static final int DUMP_SHARED_USERS = 1 << 8;
22091        public static final int DUMP_MESSAGES = 1 << 9;
22092        public static final int DUMP_PROVIDERS = 1 << 10;
22093        public static final int DUMP_VERIFIERS = 1 << 11;
22094        public static final int DUMP_PREFERRED = 1 << 12;
22095        public static final int DUMP_PREFERRED_XML = 1 << 13;
22096        public static final int DUMP_KEYSETS = 1 << 14;
22097        public static final int DUMP_VERSION = 1 << 15;
22098        public static final int DUMP_INSTALLS = 1 << 16;
22099        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22100        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22101        public static final int DUMP_FROZEN = 1 << 19;
22102        public static final int DUMP_DEXOPT = 1 << 20;
22103        public static final int DUMP_COMPILER_STATS = 1 << 21;
22104        public static final int DUMP_CHANGES = 1 << 22;
22105        public static final int DUMP_VOLUMES = 1 << 23;
22106
22107        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22108
22109        private int mTypes;
22110
22111        private int mOptions;
22112
22113        private boolean mTitlePrinted;
22114
22115        private SharedUserSetting mSharedUser;
22116
22117        public boolean isDumping(int type) {
22118            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22119                return true;
22120            }
22121
22122            return (mTypes & type) != 0;
22123        }
22124
22125        public void setDump(int type) {
22126            mTypes |= type;
22127        }
22128
22129        public boolean isOptionEnabled(int option) {
22130            return (mOptions & option) != 0;
22131        }
22132
22133        public void setOptionEnabled(int option) {
22134            mOptions |= option;
22135        }
22136
22137        public boolean onTitlePrinted() {
22138            final boolean printed = mTitlePrinted;
22139            mTitlePrinted = true;
22140            return printed;
22141        }
22142
22143        public boolean getTitlePrinted() {
22144            return mTitlePrinted;
22145        }
22146
22147        public void setTitlePrinted(boolean enabled) {
22148            mTitlePrinted = enabled;
22149        }
22150
22151        public SharedUserSetting getSharedUser() {
22152            return mSharedUser;
22153        }
22154
22155        public void setSharedUser(SharedUserSetting user) {
22156            mSharedUser = user;
22157        }
22158    }
22159
22160    @Override
22161    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22162            FileDescriptor err, String[] args, ShellCallback callback,
22163            ResultReceiver resultReceiver) {
22164        (new PackageManagerShellCommand(this)).exec(
22165                this, in, out, err, args, callback, resultReceiver);
22166    }
22167
22168    @Override
22169    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22170        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22171
22172        DumpState dumpState = new DumpState();
22173        boolean fullPreferred = false;
22174        boolean checkin = false;
22175
22176        String packageName = null;
22177        ArraySet<String> permissionNames = null;
22178
22179        int opti = 0;
22180        while (opti < args.length) {
22181            String opt = args[opti];
22182            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22183                break;
22184            }
22185            opti++;
22186
22187            if ("-a".equals(opt)) {
22188                // Right now we only know how to print all.
22189            } else if ("-h".equals(opt)) {
22190                pw.println("Package manager dump options:");
22191                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22192                pw.println("    --checkin: dump for a checkin");
22193                pw.println("    -f: print details of intent filters");
22194                pw.println("    -h: print this help");
22195                pw.println("  cmd may be one of:");
22196                pw.println("    l[ibraries]: list known shared libraries");
22197                pw.println("    f[eatures]: list device features");
22198                pw.println("    k[eysets]: print known keysets");
22199                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22200                pw.println("    perm[issions]: dump permissions");
22201                pw.println("    permission [name ...]: dump declaration and use of given permission");
22202                pw.println("    pref[erred]: print preferred package settings");
22203                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22204                pw.println("    prov[iders]: dump content providers");
22205                pw.println("    p[ackages]: dump installed packages");
22206                pw.println("    s[hared-users]: dump shared user IDs");
22207                pw.println("    m[essages]: print collected runtime messages");
22208                pw.println("    v[erifiers]: print package verifier info");
22209                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22210                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22211                pw.println("    version: print database version info");
22212                pw.println("    write: write current settings now");
22213                pw.println("    installs: details about install sessions");
22214                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22215                pw.println("    dexopt: dump dexopt state");
22216                pw.println("    compiler-stats: dump compiler statistics");
22217                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22218                pw.println("    <package.name>: info about given package");
22219                return;
22220            } else if ("--checkin".equals(opt)) {
22221                checkin = true;
22222            } else if ("-f".equals(opt)) {
22223                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22224            } else if ("--proto".equals(opt)) {
22225                dumpProto(fd);
22226                return;
22227            } else {
22228                pw.println("Unknown argument: " + opt + "; use -h for help");
22229            }
22230        }
22231
22232        // Is the caller requesting to dump a particular piece of data?
22233        if (opti < args.length) {
22234            String cmd = args[opti];
22235            opti++;
22236            // Is this a package name?
22237            if ("android".equals(cmd) || cmd.contains(".")) {
22238                packageName = cmd;
22239                // When dumping a single package, we always dump all of its
22240                // filter information since the amount of data will be reasonable.
22241                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22242            } else if ("check-permission".equals(cmd)) {
22243                if (opti >= args.length) {
22244                    pw.println("Error: check-permission missing permission argument");
22245                    return;
22246                }
22247                String perm = args[opti];
22248                opti++;
22249                if (opti >= args.length) {
22250                    pw.println("Error: check-permission missing package argument");
22251                    return;
22252                }
22253
22254                String pkg = args[opti];
22255                opti++;
22256                int user = UserHandle.getUserId(Binder.getCallingUid());
22257                if (opti < args.length) {
22258                    try {
22259                        user = Integer.parseInt(args[opti]);
22260                    } catch (NumberFormatException e) {
22261                        pw.println("Error: check-permission user argument is not a number: "
22262                                + args[opti]);
22263                        return;
22264                    }
22265                }
22266
22267                // Normalize package name to handle renamed packages and static libs
22268                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22269
22270                pw.println(checkPermission(perm, pkg, user));
22271                return;
22272            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22273                dumpState.setDump(DumpState.DUMP_LIBS);
22274            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22275                dumpState.setDump(DumpState.DUMP_FEATURES);
22276            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22277                if (opti >= args.length) {
22278                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22279                            | DumpState.DUMP_SERVICE_RESOLVERS
22280                            | DumpState.DUMP_RECEIVER_RESOLVERS
22281                            | DumpState.DUMP_CONTENT_RESOLVERS);
22282                } else {
22283                    while (opti < args.length) {
22284                        String name = args[opti];
22285                        if ("a".equals(name) || "activity".equals(name)) {
22286                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22287                        } else if ("s".equals(name) || "service".equals(name)) {
22288                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22289                        } else if ("r".equals(name) || "receiver".equals(name)) {
22290                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22291                        } else if ("c".equals(name) || "content".equals(name)) {
22292                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22293                        } else {
22294                            pw.println("Error: unknown resolver table type: " + name);
22295                            return;
22296                        }
22297                        opti++;
22298                    }
22299                }
22300            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22301                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22302            } else if ("permission".equals(cmd)) {
22303                if (opti >= args.length) {
22304                    pw.println("Error: permission requires permission name");
22305                    return;
22306                }
22307                permissionNames = new ArraySet<>();
22308                while (opti < args.length) {
22309                    permissionNames.add(args[opti]);
22310                    opti++;
22311                }
22312                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22313                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22314            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22315                dumpState.setDump(DumpState.DUMP_PREFERRED);
22316            } else if ("preferred-xml".equals(cmd)) {
22317                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22318                if (opti < args.length && "--full".equals(args[opti])) {
22319                    fullPreferred = true;
22320                    opti++;
22321                }
22322            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22323                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22324            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22325                dumpState.setDump(DumpState.DUMP_PACKAGES);
22326            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22327                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22328            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22329                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22330            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22331                dumpState.setDump(DumpState.DUMP_MESSAGES);
22332            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22333                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22334            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22335                    || "intent-filter-verifiers".equals(cmd)) {
22336                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22337            } else if ("version".equals(cmd)) {
22338                dumpState.setDump(DumpState.DUMP_VERSION);
22339            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22340                dumpState.setDump(DumpState.DUMP_KEYSETS);
22341            } else if ("installs".equals(cmd)) {
22342                dumpState.setDump(DumpState.DUMP_INSTALLS);
22343            } else if ("frozen".equals(cmd)) {
22344                dumpState.setDump(DumpState.DUMP_FROZEN);
22345            } else if ("volumes".equals(cmd)) {
22346                dumpState.setDump(DumpState.DUMP_VOLUMES);
22347            } else if ("dexopt".equals(cmd)) {
22348                dumpState.setDump(DumpState.DUMP_DEXOPT);
22349            } else if ("compiler-stats".equals(cmd)) {
22350                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22351            } else if ("changes".equals(cmd)) {
22352                dumpState.setDump(DumpState.DUMP_CHANGES);
22353            } else if ("write".equals(cmd)) {
22354                synchronized (mPackages) {
22355                    mSettings.writeLPr();
22356                    pw.println("Settings written.");
22357                    return;
22358                }
22359            }
22360        }
22361
22362        if (checkin) {
22363            pw.println("vers,1");
22364        }
22365
22366        // reader
22367        synchronized (mPackages) {
22368            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22369                if (!checkin) {
22370                    if (dumpState.onTitlePrinted())
22371                        pw.println();
22372                    pw.println("Database versions:");
22373                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22374                }
22375            }
22376
22377            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22378                if (!checkin) {
22379                    if (dumpState.onTitlePrinted())
22380                        pw.println();
22381                    pw.println("Verifiers:");
22382                    pw.print("  Required: ");
22383                    pw.print(mRequiredVerifierPackage);
22384                    pw.print(" (uid=");
22385                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22386                            UserHandle.USER_SYSTEM));
22387                    pw.println(")");
22388                } else if (mRequiredVerifierPackage != null) {
22389                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22390                    pw.print(",");
22391                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22392                            UserHandle.USER_SYSTEM));
22393                }
22394            }
22395
22396            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22397                    packageName == null) {
22398                if (mIntentFilterVerifierComponent != null) {
22399                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22400                    if (!checkin) {
22401                        if (dumpState.onTitlePrinted())
22402                            pw.println();
22403                        pw.println("Intent Filter Verifier:");
22404                        pw.print("  Using: ");
22405                        pw.print(verifierPackageName);
22406                        pw.print(" (uid=");
22407                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22408                                UserHandle.USER_SYSTEM));
22409                        pw.println(")");
22410                    } else if (verifierPackageName != null) {
22411                        pw.print("ifv,"); pw.print(verifierPackageName);
22412                        pw.print(",");
22413                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22414                                UserHandle.USER_SYSTEM));
22415                    }
22416                } else {
22417                    pw.println();
22418                    pw.println("No Intent Filter Verifier available!");
22419                }
22420            }
22421
22422            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22423                boolean printedHeader = false;
22424                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22425                while (it.hasNext()) {
22426                    String libName = it.next();
22427                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22428                    if (versionedLib == null) {
22429                        continue;
22430                    }
22431                    final int versionCount = versionedLib.size();
22432                    for (int i = 0; i < versionCount; i++) {
22433                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22434                        if (!checkin) {
22435                            if (!printedHeader) {
22436                                if (dumpState.onTitlePrinted())
22437                                    pw.println();
22438                                pw.println("Libraries:");
22439                                printedHeader = true;
22440                            }
22441                            pw.print("  ");
22442                        } else {
22443                            pw.print("lib,");
22444                        }
22445                        pw.print(libEntry.info.getName());
22446                        if (libEntry.info.isStatic()) {
22447                            pw.print(" version=" + libEntry.info.getVersion());
22448                        }
22449                        if (!checkin) {
22450                            pw.print(" -> ");
22451                        }
22452                        if (libEntry.path != null) {
22453                            pw.print(" (jar) ");
22454                            pw.print(libEntry.path);
22455                        } else {
22456                            pw.print(" (apk) ");
22457                            pw.print(libEntry.apk);
22458                        }
22459                        pw.println();
22460                    }
22461                }
22462            }
22463
22464            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22465                if (dumpState.onTitlePrinted())
22466                    pw.println();
22467                if (!checkin) {
22468                    pw.println("Features:");
22469                }
22470
22471                synchronized (mAvailableFeatures) {
22472                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22473                        if (checkin) {
22474                            pw.print("feat,");
22475                            pw.print(feat.name);
22476                            pw.print(",");
22477                            pw.println(feat.version);
22478                        } else {
22479                            pw.print("  ");
22480                            pw.print(feat.name);
22481                            if (feat.version > 0) {
22482                                pw.print(" version=");
22483                                pw.print(feat.version);
22484                            }
22485                            pw.println();
22486                        }
22487                    }
22488                }
22489            }
22490
22491            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22492                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22493                        : "Activity Resolver Table:", "  ", packageName,
22494                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22495                    dumpState.setTitlePrinted(true);
22496                }
22497            }
22498            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22499                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22500                        : "Receiver Resolver Table:", "  ", packageName,
22501                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22502                    dumpState.setTitlePrinted(true);
22503                }
22504            }
22505            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22506                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22507                        : "Service Resolver Table:", "  ", packageName,
22508                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22509                    dumpState.setTitlePrinted(true);
22510                }
22511            }
22512            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22513                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22514                        : "Provider Resolver Table:", "  ", packageName,
22515                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22516                    dumpState.setTitlePrinted(true);
22517                }
22518            }
22519
22520            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22521                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22522                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22523                    int user = mSettings.mPreferredActivities.keyAt(i);
22524                    if (pir.dump(pw,
22525                            dumpState.getTitlePrinted()
22526                                ? "\nPreferred Activities User " + user + ":"
22527                                : "Preferred Activities User " + user + ":", "  ",
22528                            packageName, true, false)) {
22529                        dumpState.setTitlePrinted(true);
22530                    }
22531                }
22532            }
22533
22534            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22535                pw.flush();
22536                FileOutputStream fout = new FileOutputStream(fd);
22537                BufferedOutputStream str = new BufferedOutputStream(fout);
22538                XmlSerializer serializer = new FastXmlSerializer();
22539                try {
22540                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22541                    serializer.startDocument(null, true);
22542                    serializer.setFeature(
22543                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22544                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22545                    serializer.endDocument();
22546                    serializer.flush();
22547                } catch (IllegalArgumentException e) {
22548                    pw.println("Failed writing: " + e);
22549                } catch (IllegalStateException e) {
22550                    pw.println("Failed writing: " + e);
22551                } catch (IOException e) {
22552                    pw.println("Failed writing: " + e);
22553                }
22554            }
22555
22556            if (!checkin
22557                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22558                    && packageName == null) {
22559                pw.println();
22560                int count = mSettings.mPackages.size();
22561                if (count == 0) {
22562                    pw.println("No applications!");
22563                    pw.println();
22564                } else {
22565                    final String prefix = "  ";
22566                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22567                    if (allPackageSettings.size() == 0) {
22568                        pw.println("No domain preferred apps!");
22569                        pw.println();
22570                    } else {
22571                        pw.println("App verification status:");
22572                        pw.println();
22573                        count = 0;
22574                        for (PackageSetting ps : allPackageSettings) {
22575                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22576                            if (ivi == null || ivi.getPackageName() == null) continue;
22577                            pw.println(prefix + "Package: " + ivi.getPackageName());
22578                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22579                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22580                            pw.println();
22581                            count++;
22582                        }
22583                        if (count == 0) {
22584                            pw.println(prefix + "No app verification established.");
22585                            pw.println();
22586                        }
22587                        for (int userId : sUserManager.getUserIds()) {
22588                            pw.println("App linkages for user " + userId + ":");
22589                            pw.println();
22590                            count = 0;
22591                            for (PackageSetting ps : allPackageSettings) {
22592                                final long status = ps.getDomainVerificationStatusForUser(userId);
22593                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22594                                        && !DEBUG_DOMAIN_VERIFICATION) {
22595                                    continue;
22596                                }
22597                                pw.println(prefix + "Package: " + ps.name);
22598                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22599                                String statusStr = IntentFilterVerificationInfo.
22600                                        getStatusStringFromValue(status);
22601                                pw.println(prefix + "Status:  " + statusStr);
22602                                pw.println();
22603                                count++;
22604                            }
22605                            if (count == 0) {
22606                                pw.println(prefix + "No configured app linkages.");
22607                                pw.println();
22608                            }
22609                        }
22610                    }
22611                }
22612            }
22613
22614            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22615                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22616                if (packageName == null && permissionNames == null) {
22617                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22618                        if (iperm == 0) {
22619                            if (dumpState.onTitlePrinted())
22620                                pw.println();
22621                            pw.println("AppOp Permissions:");
22622                        }
22623                        pw.print("  AppOp Permission ");
22624                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22625                        pw.println(":");
22626                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22627                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22628                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22629                        }
22630                    }
22631                }
22632            }
22633
22634            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22635                boolean printedSomething = false;
22636                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22637                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22638                        continue;
22639                    }
22640                    if (!printedSomething) {
22641                        if (dumpState.onTitlePrinted())
22642                            pw.println();
22643                        pw.println("Registered ContentProviders:");
22644                        printedSomething = true;
22645                    }
22646                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22647                    pw.print("    "); pw.println(p.toString());
22648                }
22649                printedSomething = false;
22650                for (Map.Entry<String, PackageParser.Provider> entry :
22651                        mProvidersByAuthority.entrySet()) {
22652                    PackageParser.Provider p = entry.getValue();
22653                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22654                        continue;
22655                    }
22656                    if (!printedSomething) {
22657                        if (dumpState.onTitlePrinted())
22658                            pw.println();
22659                        pw.println("ContentProvider Authorities:");
22660                        printedSomething = true;
22661                    }
22662                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22663                    pw.print("    "); pw.println(p.toString());
22664                    if (p.info != null && p.info.applicationInfo != null) {
22665                        final String appInfo = p.info.applicationInfo.toString();
22666                        pw.print("      applicationInfo="); pw.println(appInfo);
22667                    }
22668                }
22669            }
22670
22671            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22672                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22673            }
22674
22675            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22676                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22677            }
22678
22679            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22680                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22681            }
22682
22683            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22684                if (dumpState.onTitlePrinted()) pw.println();
22685                pw.println("Package Changes:");
22686                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22687                final int K = mChangedPackages.size();
22688                for (int i = 0; i < K; i++) {
22689                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22690                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22691                    final int N = changes.size();
22692                    if (N == 0) {
22693                        pw.print("    "); pw.println("No packages changed");
22694                    } else {
22695                        for (int j = 0; j < N; j++) {
22696                            final String pkgName = changes.valueAt(j);
22697                            final int sequenceNumber = changes.keyAt(j);
22698                            pw.print("    ");
22699                            pw.print("seq=");
22700                            pw.print(sequenceNumber);
22701                            pw.print(", package=");
22702                            pw.println(pkgName);
22703                        }
22704                    }
22705                }
22706            }
22707
22708            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22709                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22710            }
22711
22712            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22713                // XXX should handle packageName != null by dumping only install data that
22714                // the given package is involved with.
22715                if (dumpState.onTitlePrinted()) pw.println();
22716
22717                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22718                ipw.println();
22719                ipw.println("Frozen packages:");
22720                ipw.increaseIndent();
22721                if (mFrozenPackages.size() == 0) {
22722                    ipw.println("(none)");
22723                } else {
22724                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22725                        ipw.println(mFrozenPackages.valueAt(i));
22726                    }
22727                }
22728                ipw.decreaseIndent();
22729            }
22730
22731            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22732                if (dumpState.onTitlePrinted()) pw.println();
22733
22734                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22735                ipw.println();
22736                ipw.println("Loaded volumes:");
22737                ipw.increaseIndent();
22738                if (mLoadedVolumes.size() == 0) {
22739                    ipw.println("(none)");
22740                } else {
22741                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22742                        ipw.println(mLoadedVolumes.valueAt(i));
22743                    }
22744                }
22745                ipw.decreaseIndent();
22746            }
22747
22748            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22749                if (dumpState.onTitlePrinted()) pw.println();
22750                dumpDexoptStateLPr(pw, packageName);
22751            }
22752
22753            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22754                if (dumpState.onTitlePrinted()) pw.println();
22755                dumpCompilerStatsLPr(pw, packageName);
22756            }
22757
22758            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22759                if (dumpState.onTitlePrinted()) pw.println();
22760                mSettings.dumpReadMessagesLPr(pw, dumpState);
22761
22762                pw.println();
22763                pw.println("Package warning messages:");
22764                BufferedReader in = null;
22765                String line = null;
22766                try {
22767                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22768                    while ((line = in.readLine()) != null) {
22769                        if (line.contains("ignored: updated version")) continue;
22770                        pw.println(line);
22771                    }
22772                } catch (IOException ignored) {
22773                } finally {
22774                    IoUtils.closeQuietly(in);
22775                }
22776            }
22777
22778            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22779                BufferedReader in = null;
22780                String line = null;
22781                try {
22782                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22783                    while ((line = in.readLine()) != null) {
22784                        if (line.contains("ignored: updated version")) continue;
22785                        pw.print("msg,");
22786                        pw.println(line);
22787                    }
22788                } catch (IOException ignored) {
22789                } finally {
22790                    IoUtils.closeQuietly(in);
22791                }
22792            }
22793        }
22794
22795        // PackageInstaller should be called outside of mPackages lock
22796        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22797            // XXX should handle packageName != null by dumping only install data that
22798            // the given package is involved with.
22799            if (dumpState.onTitlePrinted()) pw.println();
22800            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22801        }
22802    }
22803
22804    private void dumpProto(FileDescriptor fd) {
22805        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22806
22807        synchronized (mPackages) {
22808            final long requiredVerifierPackageToken =
22809                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22810            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22811            proto.write(
22812                    PackageServiceDumpProto.PackageShortProto.UID,
22813                    getPackageUid(
22814                            mRequiredVerifierPackage,
22815                            MATCH_DEBUG_TRIAGED_MISSING,
22816                            UserHandle.USER_SYSTEM));
22817            proto.end(requiredVerifierPackageToken);
22818
22819            if (mIntentFilterVerifierComponent != null) {
22820                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22821                final long verifierPackageToken =
22822                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22823                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22824                proto.write(
22825                        PackageServiceDumpProto.PackageShortProto.UID,
22826                        getPackageUid(
22827                                verifierPackageName,
22828                                MATCH_DEBUG_TRIAGED_MISSING,
22829                                UserHandle.USER_SYSTEM));
22830                proto.end(verifierPackageToken);
22831            }
22832
22833            dumpSharedLibrariesProto(proto);
22834            dumpFeaturesProto(proto);
22835            mSettings.dumpPackagesProto(proto);
22836            mSettings.dumpSharedUsersProto(proto);
22837            dumpMessagesProto(proto);
22838        }
22839        proto.flush();
22840    }
22841
22842    private void dumpMessagesProto(ProtoOutputStream proto) {
22843        BufferedReader in = null;
22844        String line = null;
22845        try {
22846            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22847            while ((line = in.readLine()) != null) {
22848                if (line.contains("ignored: updated version")) continue;
22849                proto.write(PackageServiceDumpProto.MESSAGES, line);
22850            }
22851        } catch (IOException ignored) {
22852        } finally {
22853            IoUtils.closeQuietly(in);
22854        }
22855    }
22856
22857    private void dumpFeaturesProto(ProtoOutputStream proto) {
22858        synchronized (mAvailableFeatures) {
22859            final int count = mAvailableFeatures.size();
22860            for (int i = 0; i < count; i++) {
22861                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22862                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22863                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22864                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22865                proto.end(featureToken);
22866            }
22867        }
22868    }
22869
22870    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22871        final int count = mSharedLibraries.size();
22872        for (int i = 0; i < count; i++) {
22873            final String libName = mSharedLibraries.keyAt(i);
22874            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22875            if (versionedLib == null) {
22876                continue;
22877            }
22878            final int versionCount = versionedLib.size();
22879            for (int j = 0; j < versionCount; j++) {
22880                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22881                final long sharedLibraryToken =
22882                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22883                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22884                final boolean isJar = (libEntry.path != null);
22885                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22886                if (isJar) {
22887                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22888                } else {
22889                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22890                }
22891                proto.end(sharedLibraryToken);
22892            }
22893        }
22894    }
22895
22896    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22897        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22898        ipw.println();
22899        ipw.println("Dexopt state:");
22900        ipw.increaseIndent();
22901        Collection<PackageParser.Package> packages = null;
22902        if (packageName != null) {
22903            PackageParser.Package targetPackage = mPackages.get(packageName);
22904            if (targetPackage != null) {
22905                packages = Collections.singletonList(targetPackage);
22906            } else {
22907                ipw.println("Unable to find package: " + packageName);
22908                return;
22909            }
22910        } else {
22911            packages = mPackages.values();
22912        }
22913
22914        for (PackageParser.Package pkg : packages) {
22915            ipw.println("[" + pkg.packageName + "]");
22916            ipw.increaseIndent();
22917            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22918                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22919            ipw.decreaseIndent();
22920        }
22921    }
22922
22923    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22924        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22925        ipw.println();
22926        ipw.println("Compiler stats:");
22927        ipw.increaseIndent();
22928        Collection<PackageParser.Package> packages = null;
22929        if (packageName != null) {
22930            PackageParser.Package targetPackage = mPackages.get(packageName);
22931            if (targetPackage != null) {
22932                packages = Collections.singletonList(targetPackage);
22933            } else {
22934                ipw.println("Unable to find package: " + packageName);
22935                return;
22936            }
22937        } else {
22938            packages = mPackages.values();
22939        }
22940
22941        for (PackageParser.Package pkg : packages) {
22942            ipw.println("[" + pkg.packageName + "]");
22943            ipw.increaseIndent();
22944
22945            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22946            if (stats == null) {
22947                ipw.println("(No recorded stats)");
22948            } else {
22949                stats.dump(ipw);
22950            }
22951            ipw.decreaseIndent();
22952        }
22953    }
22954
22955    private String dumpDomainString(String packageName) {
22956        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22957                .getList();
22958        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22959
22960        ArraySet<String> result = new ArraySet<>();
22961        if (iviList.size() > 0) {
22962            for (IntentFilterVerificationInfo ivi : iviList) {
22963                for (String host : ivi.getDomains()) {
22964                    result.add(host);
22965                }
22966            }
22967        }
22968        if (filters != null && filters.size() > 0) {
22969            for (IntentFilter filter : filters) {
22970                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22971                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22972                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22973                    result.addAll(filter.getHostsList());
22974                }
22975            }
22976        }
22977
22978        StringBuilder sb = new StringBuilder(result.size() * 16);
22979        for (String domain : result) {
22980            if (sb.length() > 0) sb.append(" ");
22981            sb.append(domain);
22982        }
22983        return sb.toString();
22984    }
22985
22986    // ------- apps on sdcard specific code -------
22987    static final boolean DEBUG_SD_INSTALL = false;
22988
22989    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22990
22991    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22992
22993    private boolean mMediaMounted = false;
22994
22995    static String getEncryptKey() {
22996        try {
22997            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22998                    SD_ENCRYPTION_KEYSTORE_NAME);
22999            if (sdEncKey == null) {
23000                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23001                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23002                if (sdEncKey == null) {
23003                    Slog.e(TAG, "Failed to create encryption keys");
23004                    return null;
23005                }
23006            }
23007            return sdEncKey;
23008        } catch (NoSuchAlgorithmException nsae) {
23009            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23010            return null;
23011        } catch (IOException ioe) {
23012            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23013            return null;
23014        }
23015    }
23016
23017    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23018            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23019        final int size = infos.size();
23020        final String[] packageNames = new String[size];
23021        final int[] packageUids = new int[size];
23022        for (int i = 0; i < size; i++) {
23023            final ApplicationInfo info = infos.get(i);
23024            packageNames[i] = info.packageName;
23025            packageUids[i] = info.uid;
23026        }
23027        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23028                finishedReceiver);
23029    }
23030
23031    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23032            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23033        sendResourcesChangedBroadcast(mediaStatus, replacing,
23034                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23035    }
23036
23037    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23038            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23039        int size = pkgList.length;
23040        if (size > 0) {
23041            // Send broadcasts here
23042            Bundle extras = new Bundle();
23043            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23044            if (uidArr != null) {
23045                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23046            }
23047            if (replacing) {
23048                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23049            }
23050            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23051                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23052            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23053        }
23054    }
23055
23056    private void loadPrivatePackages(final VolumeInfo vol) {
23057        mHandler.post(new Runnable() {
23058            @Override
23059            public void run() {
23060                loadPrivatePackagesInner(vol);
23061            }
23062        });
23063    }
23064
23065    private void loadPrivatePackagesInner(VolumeInfo vol) {
23066        final String volumeUuid = vol.fsUuid;
23067        if (TextUtils.isEmpty(volumeUuid)) {
23068            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23069            return;
23070        }
23071
23072        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23073        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23074        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23075
23076        final VersionInfo ver;
23077        final List<PackageSetting> packages;
23078        synchronized (mPackages) {
23079            ver = mSettings.findOrCreateVersion(volumeUuid);
23080            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23081        }
23082
23083        for (PackageSetting ps : packages) {
23084            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23085            synchronized (mInstallLock) {
23086                final PackageParser.Package pkg;
23087                try {
23088                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23089                    loaded.add(pkg.applicationInfo);
23090
23091                } catch (PackageManagerException e) {
23092                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23093                }
23094
23095                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23096                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23097                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23098                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23099                }
23100            }
23101        }
23102
23103        // Reconcile app data for all started/unlocked users
23104        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23105        final UserManager um = mContext.getSystemService(UserManager.class);
23106        UserManagerInternal umInternal = getUserManagerInternal();
23107        for (UserInfo user : um.getUsers()) {
23108            final int flags;
23109            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23110                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23111            } else if (umInternal.isUserRunning(user.id)) {
23112                flags = StorageManager.FLAG_STORAGE_DE;
23113            } else {
23114                continue;
23115            }
23116
23117            try {
23118                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23119                synchronized (mInstallLock) {
23120                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23121                }
23122            } catch (IllegalStateException e) {
23123                // Device was probably ejected, and we'll process that event momentarily
23124                Slog.w(TAG, "Failed to prepare storage: " + e);
23125            }
23126        }
23127
23128        synchronized (mPackages) {
23129            int updateFlags = UPDATE_PERMISSIONS_ALL;
23130            if (ver.sdkVersion != mSdkVersion) {
23131                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23132                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23133                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23134            }
23135            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23136
23137            // Yay, everything is now upgraded
23138            ver.forceCurrent();
23139
23140            mSettings.writeLPr();
23141        }
23142
23143        for (PackageFreezer freezer : freezers) {
23144            freezer.close();
23145        }
23146
23147        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23148        sendResourcesChangedBroadcast(true, false, loaded, null);
23149        mLoadedVolumes.add(vol.getId());
23150    }
23151
23152    private void unloadPrivatePackages(final VolumeInfo vol) {
23153        mHandler.post(new Runnable() {
23154            @Override
23155            public void run() {
23156                unloadPrivatePackagesInner(vol);
23157            }
23158        });
23159    }
23160
23161    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23162        final String volumeUuid = vol.fsUuid;
23163        if (TextUtils.isEmpty(volumeUuid)) {
23164            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23165            return;
23166        }
23167
23168        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23169        synchronized (mInstallLock) {
23170        synchronized (mPackages) {
23171            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23172            for (PackageSetting ps : packages) {
23173                if (ps.pkg == null) continue;
23174
23175                final ApplicationInfo info = ps.pkg.applicationInfo;
23176                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23177                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23178
23179                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23180                        "unloadPrivatePackagesInner")) {
23181                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23182                            false, null)) {
23183                        unloaded.add(info);
23184                    } else {
23185                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23186                    }
23187                }
23188
23189                // Try very hard to release any references to this package
23190                // so we don't risk the system server being killed due to
23191                // open FDs
23192                AttributeCache.instance().removePackage(ps.name);
23193            }
23194
23195            mSettings.writeLPr();
23196        }
23197        }
23198
23199        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23200        sendResourcesChangedBroadcast(false, false, unloaded, null);
23201        mLoadedVolumes.remove(vol.getId());
23202
23203        // Try very hard to release any references to this path so we don't risk
23204        // the system server being killed due to open FDs
23205        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23206
23207        for (int i = 0; i < 3; i++) {
23208            System.gc();
23209            System.runFinalization();
23210        }
23211    }
23212
23213    private void assertPackageKnown(String volumeUuid, String packageName)
23214            throws PackageManagerException {
23215        synchronized (mPackages) {
23216            // Normalize package name to handle renamed packages
23217            packageName = normalizePackageNameLPr(packageName);
23218
23219            final PackageSetting ps = mSettings.mPackages.get(packageName);
23220            if (ps == null) {
23221                throw new PackageManagerException("Package " + packageName + " is unknown");
23222            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23223                throw new PackageManagerException(
23224                        "Package " + packageName + " found on unknown volume " + volumeUuid
23225                                + "; expected volume " + ps.volumeUuid);
23226            }
23227        }
23228    }
23229
23230    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23231            throws PackageManagerException {
23232        synchronized (mPackages) {
23233            // Normalize package name to handle renamed packages
23234            packageName = normalizePackageNameLPr(packageName);
23235
23236            final PackageSetting ps = mSettings.mPackages.get(packageName);
23237            if (ps == null) {
23238                throw new PackageManagerException("Package " + packageName + " is unknown");
23239            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23240                throw new PackageManagerException(
23241                        "Package " + packageName + " found on unknown volume " + volumeUuid
23242                                + "; expected volume " + ps.volumeUuid);
23243            } else if (!ps.getInstalled(userId)) {
23244                throw new PackageManagerException(
23245                        "Package " + packageName + " not installed for user " + userId);
23246            }
23247        }
23248    }
23249
23250    private List<String> collectAbsoluteCodePaths() {
23251        synchronized (mPackages) {
23252            List<String> codePaths = new ArrayList<>();
23253            final int packageCount = mSettings.mPackages.size();
23254            for (int i = 0; i < packageCount; i++) {
23255                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23256                codePaths.add(ps.codePath.getAbsolutePath());
23257            }
23258            return codePaths;
23259        }
23260    }
23261
23262    /**
23263     * Examine all apps present on given mounted volume, and destroy apps that
23264     * aren't expected, either due to uninstallation or reinstallation on
23265     * another volume.
23266     */
23267    private void reconcileApps(String volumeUuid) {
23268        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23269        List<File> filesToDelete = null;
23270
23271        final File[] files = FileUtils.listFilesOrEmpty(
23272                Environment.getDataAppDirectory(volumeUuid));
23273        for (File file : files) {
23274            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23275                    && !PackageInstallerService.isStageName(file.getName());
23276            if (!isPackage) {
23277                // Ignore entries which are not packages
23278                continue;
23279            }
23280
23281            String absolutePath = file.getAbsolutePath();
23282
23283            boolean pathValid = false;
23284            final int absoluteCodePathCount = absoluteCodePaths.size();
23285            for (int i = 0; i < absoluteCodePathCount; i++) {
23286                String absoluteCodePath = absoluteCodePaths.get(i);
23287                if (absolutePath.startsWith(absoluteCodePath)) {
23288                    pathValid = true;
23289                    break;
23290                }
23291            }
23292
23293            if (!pathValid) {
23294                if (filesToDelete == null) {
23295                    filesToDelete = new ArrayList<>();
23296                }
23297                filesToDelete.add(file);
23298            }
23299        }
23300
23301        if (filesToDelete != null) {
23302            final int fileToDeleteCount = filesToDelete.size();
23303            for (int i = 0; i < fileToDeleteCount; i++) {
23304                File fileToDelete = filesToDelete.get(i);
23305                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23306                synchronized (mInstallLock) {
23307                    removeCodePathLI(fileToDelete);
23308                }
23309            }
23310        }
23311    }
23312
23313    /**
23314     * Reconcile all app data for the given user.
23315     * <p>
23316     * Verifies that directories exist and that ownership and labeling is
23317     * correct for all installed apps on all mounted volumes.
23318     */
23319    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23320        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23321        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23322            final String volumeUuid = vol.getFsUuid();
23323            synchronized (mInstallLock) {
23324                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23325            }
23326        }
23327    }
23328
23329    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23330            boolean migrateAppData) {
23331        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23332    }
23333
23334    /**
23335     * Reconcile all app data on given mounted volume.
23336     * <p>
23337     * Destroys app data that isn't expected, either due to uninstallation or
23338     * reinstallation on another volume.
23339     * <p>
23340     * Verifies that directories exist and that ownership and labeling is
23341     * correct for all installed apps.
23342     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23343     */
23344    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23345            boolean migrateAppData, boolean onlyCoreApps) {
23346        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23347                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23348        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23349
23350        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23351        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23352
23353        // First look for stale data that doesn't belong, and check if things
23354        // have changed since we did our last restorecon
23355        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23356            if (StorageManager.isFileEncryptedNativeOrEmulated()
23357                    && !StorageManager.isUserKeyUnlocked(userId)) {
23358                throw new RuntimeException(
23359                        "Yikes, someone asked us to reconcile CE storage while " + userId
23360                                + " was still locked; this would have caused massive data loss!");
23361            }
23362
23363            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23364            for (File file : files) {
23365                final String packageName = file.getName();
23366                try {
23367                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23368                } catch (PackageManagerException e) {
23369                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23370                    try {
23371                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23372                                StorageManager.FLAG_STORAGE_CE, 0);
23373                    } catch (InstallerException e2) {
23374                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23375                    }
23376                }
23377            }
23378        }
23379        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23380            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23381            for (File file : files) {
23382                final String packageName = file.getName();
23383                try {
23384                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23385                } catch (PackageManagerException e) {
23386                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23387                    try {
23388                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23389                                StorageManager.FLAG_STORAGE_DE, 0);
23390                    } catch (InstallerException e2) {
23391                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23392                    }
23393                }
23394            }
23395        }
23396
23397        // Ensure that data directories are ready to roll for all packages
23398        // installed for this volume and user
23399        final List<PackageSetting> packages;
23400        synchronized (mPackages) {
23401            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23402        }
23403        int preparedCount = 0;
23404        for (PackageSetting ps : packages) {
23405            final String packageName = ps.name;
23406            if (ps.pkg == null) {
23407                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23408                // TODO: might be due to legacy ASEC apps; we should circle back
23409                // and reconcile again once they're scanned
23410                continue;
23411            }
23412            // Skip non-core apps if requested
23413            if (onlyCoreApps && !ps.pkg.coreApp) {
23414                result.add(packageName);
23415                continue;
23416            }
23417
23418            if (ps.getInstalled(userId)) {
23419                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23420                preparedCount++;
23421            }
23422        }
23423
23424        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23425        return result;
23426    }
23427
23428    /**
23429     * Prepare app data for the given app just after it was installed or
23430     * upgraded. This method carefully only touches users that it's installed
23431     * for, and it forces a restorecon to handle any seinfo changes.
23432     * <p>
23433     * Verifies that directories exist and that ownership and labeling is
23434     * correct for all installed apps. If there is an ownership mismatch, it
23435     * will try recovering system apps by wiping data; third-party app data is
23436     * left intact.
23437     * <p>
23438     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23439     */
23440    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23441        final PackageSetting ps;
23442        synchronized (mPackages) {
23443            ps = mSettings.mPackages.get(pkg.packageName);
23444            mSettings.writeKernelMappingLPr(ps);
23445        }
23446
23447        final UserManager um = mContext.getSystemService(UserManager.class);
23448        UserManagerInternal umInternal = getUserManagerInternal();
23449        for (UserInfo user : um.getUsers()) {
23450            final int flags;
23451            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23452                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23453            } else if (umInternal.isUserRunning(user.id)) {
23454                flags = StorageManager.FLAG_STORAGE_DE;
23455            } else {
23456                continue;
23457            }
23458
23459            if (ps.getInstalled(user.id)) {
23460                // TODO: when user data is locked, mark that we're still dirty
23461                prepareAppDataLIF(pkg, user.id, flags);
23462            }
23463        }
23464    }
23465
23466    /**
23467     * Prepare app data for the given app.
23468     * <p>
23469     * Verifies that directories exist and that ownership and labeling is
23470     * correct for all installed apps. If there is an ownership mismatch, this
23471     * will try recovering system apps by wiping data; third-party app data is
23472     * left intact.
23473     */
23474    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23475        if (pkg == null) {
23476            Slog.wtf(TAG, "Package was null!", new Throwable());
23477            return;
23478        }
23479        prepareAppDataLeafLIF(pkg, userId, flags);
23480        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23481        for (int i = 0; i < childCount; i++) {
23482            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23483        }
23484    }
23485
23486    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23487            boolean maybeMigrateAppData) {
23488        prepareAppDataLIF(pkg, userId, flags);
23489
23490        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23491            // We may have just shuffled around app data directories, so
23492            // prepare them one more time
23493            prepareAppDataLIF(pkg, userId, flags);
23494        }
23495    }
23496
23497    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23498        if (DEBUG_APP_DATA) {
23499            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23500                    + Integer.toHexString(flags));
23501        }
23502
23503        final String volumeUuid = pkg.volumeUuid;
23504        final String packageName = pkg.packageName;
23505        final ApplicationInfo app = pkg.applicationInfo;
23506        final int appId = UserHandle.getAppId(app.uid);
23507
23508        Preconditions.checkNotNull(app.seInfo);
23509
23510        long ceDataInode = -1;
23511        try {
23512            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23513                    appId, app.seInfo, app.targetSdkVersion);
23514        } catch (InstallerException e) {
23515            if (app.isSystemApp()) {
23516                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23517                        + ", but trying to recover: " + e);
23518                destroyAppDataLeafLIF(pkg, userId, flags);
23519                try {
23520                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23521                            appId, app.seInfo, app.targetSdkVersion);
23522                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23523                } catch (InstallerException e2) {
23524                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23525                }
23526            } else {
23527                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23528            }
23529        }
23530
23531        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23532            // TODO: mark this structure as dirty so we persist it!
23533            synchronized (mPackages) {
23534                final PackageSetting ps = mSettings.mPackages.get(packageName);
23535                if (ps != null) {
23536                    ps.setCeDataInode(ceDataInode, userId);
23537                }
23538            }
23539        }
23540
23541        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23542    }
23543
23544    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23545        if (pkg == null) {
23546            Slog.wtf(TAG, "Package was null!", new Throwable());
23547            return;
23548        }
23549        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23550        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23551        for (int i = 0; i < childCount; i++) {
23552            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23553        }
23554    }
23555
23556    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23557        final String volumeUuid = pkg.volumeUuid;
23558        final String packageName = pkg.packageName;
23559        final ApplicationInfo app = pkg.applicationInfo;
23560
23561        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23562            // Create a native library symlink only if we have native libraries
23563            // and if the native libraries are 32 bit libraries. We do not provide
23564            // this symlink for 64 bit libraries.
23565            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23566                final String nativeLibPath = app.nativeLibraryDir;
23567                try {
23568                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23569                            nativeLibPath, userId);
23570                } catch (InstallerException e) {
23571                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23572                }
23573            }
23574        }
23575    }
23576
23577    /**
23578     * For system apps on non-FBE devices, this method migrates any existing
23579     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23580     * requested by the app.
23581     */
23582    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23583        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23584                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23585            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23586                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23587            try {
23588                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23589                        storageTarget);
23590            } catch (InstallerException e) {
23591                logCriticalInfo(Log.WARN,
23592                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23593            }
23594            return true;
23595        } else {
23596            return false;
23597        }
23598    }
23599
23600    public PackageFreezer freezePackage(String packageName, String killReason) {
23601        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23602    }
23603
23604    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23605        return new PackageFreezer(packageName, userId, killReason);
23606    }
23607
23608    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23609            String killReason) {
23610        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23611    }
23612
23613    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23614            String killReason) {
23615        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23616            return new PackageFreezer();
23617        } else {
23618            return freezePackage(packageName, userId, killReason);
23619        }
23620    }
23621
23622    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23623            String killReason) {
23624        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23625    }
23626
23627    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23628            String killReason) {
23629        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23630            return new PackageFreezer();
23631        } else {
23632            return freezePackage(packageName, userId, killReason);
23633        }
23634    }
23635
23636    /**
23637     * Class that freezes and kills the given package upon creation, and
23638     * unfreezes it upon closing. This is typically used when doing surgery on
23639     * app code/data to prevent the app from running while you're working.
23640     */
23641    private class PackageFreezer implements AutoCloseable {
23642        private final String mPackageName;
23643        private final PackageFreezer[] mChildren;
23644
23645        private final boolean mWeFroze;
23646
23647        private final AtomicBoolean mClosed = new AtomicBoolean();
23648        private final CloseGuard mCloseGuard = CloseGuard.get();
23649
23650        /**
23651         * Create and return a stub freezer that doesn't actually do anything,
23652         * typically used when someone requested
23653         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23654         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23655         */
23656        public PackageFreezer() {
23657            mPackageName = null;
23658            mChildren = null;
23659            mWeFroze = false;
23660            mCloseGuard.open("close");
23661        }
23662
23663        public PackageFreezer(String packageName, int userId, String killReason) {
23664            synchronized (mPackages) {
23665                mPackageName = packageName;
23666                mWeFroze = mFrozenPackages.add(mPackageName);
23667
23668                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23669                if (ps != null) {
23670                    killApplication(ps.name, ps.appId, userId, killReason);
23671                }
23672
23673                final PackageParser.Package p = mPackages.get(packageName);
23674                if (p != null && p.childPackages != null) {
23675                    final int N = p.childPackages.size();
23676                    mChildren = new PackageFreezer[N];
23677                    for (int i = 0; i < N; i++) {
23678                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23679                                userId, killReason);
23680                    }
23681                } else {
23682                    mChildren = null;
23683                }
23684            }
23685            mCloseGuard.open("close");
23686        }
23687
23688        @Override
23689        protected void finalize() throws Throwable {
23690            try {
23691                if (mCloseGuard != null) {
23692                    mCloseGuard.warnIfOpen();
23693                }
23694
23695                close();
23696            } finally {
23697                super.finalize();
23698            }
23699        }
23700
23701        @Override
23702        public void close() {
23703            mCloseGuard.close();
23704            if (mClosed.compareAndSet(false, true)) {
23705                synchronized (mPackages) {
23706                    if (mWeFroze) {
23707                        mFrozenPackages.remove(mPackageName);
23708                    }
23709
23710                    if (mChildren != null) {
23711                        for (PackageFreezer freezer : mChildren) {
23712                            freezer.close();
23713                        }
23714                    }
23715                }
23716            }
23717        }
23718    }
23719
23720    /**
23721     * Verify that given package is currently frozen.
23722     */
23723    private void checkPackageFrozen(String packageName) {
23724        synchronized (mPackages) {
23725            if (!mFrozenPackages.contains(packageName)) {
23726                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23727            }
23728        }
23729    }
23730
23731    @Override
23732    public int movePackage(final String packageName, final String volumeUuid) {
23733        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23734
23735        final int callingUid = Binder.getCallingUid();
23736        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23737        final int moveId = mNextMoveId.getAndIncrement();
23738        mHandler.post(new Runnable() {
23739            @Override
23740            public void run() {
23741                try {
23742                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23743                } catch (PackageManagerException e) {
23744                    Slog.w(TAG, "Failed to move " + packageName, e);
23745                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23746                }
23747            }
23748        });
23749        return moveId;
23750    }
23751
23752    private void movePackageInternal(final String packageName, final String volumeUuid,
23753            final int moveId, final int callingUid, UserHandle user)
23754                    throws PackageManagerException {
23755        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23756        final PackageManager pm = mContext.getPackageManager();
23757
23758        final boolean currentAsec;
23759        final String currentVolumeUuid;
23760        final File codeFile;
23761        final String installerPackageName;
23762        final String packageAbiOverride;
23763        final int appId;
23764        final String seinfo;
23765        final String label;
23766        final int targetSdkVersion;
23767        final PackageFreezer freezer;
23768        final int[] installedUserIds;
23769
23770        // reader
23771        synchronized (mPackages) {
23772            final PackageParser.Package pkg = mPackages.get(packageName);
23773            final PackageSetting ps = mSettings.mPackages.get(packageName);
23774            if (pkg == null
23775                    || ps == null
23776                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23777                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23778            }
23779            if (pkg.applicationInfo.isSystemApp()) {
23780                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23781                        "Cannot move system application");
23782            }
23783
23784            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23785            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23786                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23787            if (isInternalStorage && !allow3rdPartyOnInternal) {
23788                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23789                        "3rd party apps are not allowed on internal storage");
23790            }
23791
23792            if (pkg.applicationInfo.isExternalAsec()) {
23793                currentAsec = true;
23794                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23795            } else if (pkg.applicationInfo.isForwardLocked()) {
23796                currentAsec = true;
23797                currentVolumeUuid = "forward_locked";
23798            } else {
23799                currentAsec = false;
23800                currentVolumeUuid = ps.volumeUuid;
23801
23802                final File probe = new File(pkg.codePath);
23803                final File probeOat = new File(probe, "oat");
23804                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23805                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23806                            "Move only supported for modern cluster style installs");
23807                }
23808            }
23809
23810            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23811                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23812                        "Package already moved to " + volumeUuid);
23813            }
23814            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23815                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23816                        "Device admin cannot be moved");
23817            }
23818
23819            if (mFrozenPackages.contains(packageName)) {
23820                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23821                        "Failed to move already frozen package");
23822            }
23823
23824            codeFile = new File(pkg.codePath);
23825            installerPackageName = ps.installerPackageName;
23826            packageAbiOverride = ps.cpuAbiOverrideString;
23827            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23828            seinfo = pkg.applicationInfo.seInfo;
23829            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23830            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23831            freezer = freezePackage(packageName, "movePackageInternal");
23832            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23833        }
23834
23835        final Bundle extras = new Bundle();
23836        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23837        extras.putString(Intent.EXTRA_TITLE, label);
23838        mMoveCallbacks.notifyCreated(moveId, extras);
23839
23840        int installFlags;
23841        final boolean moveCompleteApp;
23842        final File measurePath;
23843
23844        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23845            installFlags = INSTALL_INTERNAL;
23846            moveCompleteApp = !currentAsec;
23847            measurePath = Environment.getDataAppDirectory(volumeUuid);
23848        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23849            installFlags = INSTALL_EXTERNAL;
23850            moveCompleteApp = false;
23851            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23852        } else {
23853            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23854            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23855                    || !volume.isMountedWritable()) {
23856                freezer.close();
23857                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23858                        "Move location not mounted private volume");
23859            }
23860
23861            Preconditions.checkState(!currentAsec);
23862
23863            installFlags = INSTALL_INTERNAL;
23864            moveCompleteApp = true;
23865            measurePath = Environment.getDataAppDirectory(volumeUuid);
23866        }
23867
23868        // If we're moving app data around, we need all the users unlocked
23869        if (moveCompleteApp) {
23870            for (int userId : installedUserIds) {
23871                if (StorageManager.isFileEncryptedNativeOrEmulated()
23872                        && !StorageManager.isUserKeyUnlocked(userId)) {
23873                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23874                            "User " + userId + " must be unlocked");
23875                }
23876            }
23877        }
23878
23879        final PackageStats stats = new PackageStats(null, -1);
23880        synchronized (mInstaller) {
23881            for (int userId : installedUserIds) {
23882                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23883                    freezer.close();
23884                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23885                            "Failed to measure package size");
23886                }
23887            }
23888        }
23889
23890        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23891                + stats.dataSize);
23892
23893        final long startFreeBytes = measurePath.getUsableSpace();
23894        final long sizeBytes;
23895        if (moveCompleteApp) {
23896            sizeBytes = stats.codeSize + stats.dataSize;
23897        } else {
23898            sizeBytes = stats.codeSize;
23899        }
23900
23901        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23902            freezer.close();
23903            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23904                    "Not enough free space to move");
23905        }
23906
23907        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23908
23909        final CountDownLatch installedLatch = new CountDownLatch(1);
23910        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23911            @Override
23912            public void onUserActionRequired(Intent intent) throws RemoteException {
23913                throw new IllegalStateException();
23914            }
23915
23916            @Override
23917            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23918                    Bundle extras) throws RemoteException {
23919                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23920                        + PackageManager.installStatusToString(returnCode, msg));
23921
23922                installedLatch.countDown();
23923                freezer.close();
23924
23925                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23926                switch (status) {
23927                    case PackageInstaller.STATUS_SUCCESS:
23928                        mMoveCallbacks.notifyStatusChanged(moveId,
23929                                PackageManager.MOVE_SUCCEEDED);
23930                        break;
23931                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23932                        mMoveCallbacks.notifyStatusChanged(moveId,
23933                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23934                        break;
23935                    default:
23936                        mMoveCallbacks.notifyStatusChanged(moveId,
23937                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23938                        break;
23939                }
23940            }
23941        };
23942
23943        final MoveInfo move;
23944        if (moveCompleteApp) {
23945            // Kick off a thread to report progress estimates
23946            new Thread() {
23947                @Override
23948                public void run() {
23949                    while (true) {
23950                        try {
23951                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23952                                break;
23953                            }
23954                        } catch (InterruptedException ignored) {
23955                        }
23956
23957                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23958                        final int progress = 10 + (int) MathUtils.constrain(
23959                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23960                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23961                    }
23962                }
23963            }.start();
23964
23965            final String dataAppName = codeFile.getName();
23966            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23967                    dataAppName, appId, seinfo, targetSdkVersion);
23968        } else {
23969            move = null;
23970        }
23971
23972        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23973
23974        final Message msg = mHandler.obtainMessage(INIT_COPY);
23975        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23976        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23977                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23978                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23979                PackageManager.INSTALL_REASON_UNKNOWN);
23980        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23981        msg.obj = params;
23982
23983        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23984                System.identityHashCode(msg.obj));
23985        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23986                System.identityHashCode(msg.obj));
23987
23988        mHandler.sendMessage(msg);
23989    }
23990
23991    @Override
23992    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23993        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23994
23995        final int realMoveId = mNextMoveId.getAndIncrement();
23996        final Bundle extras = new Bundle();
23997        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23998        mMoveCallbacks.notifyCreated(realMoveId, extras);
23999
24000        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24001            @Override
24002            public void onCreated(int moveId, Bundle extras) {
24003                // Ignored
24004            }
24005
24006            @Override
24007            public void onStatusChanged(int moveId, int status, long estMillis) {
24008                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24009            }
24010        };
24011
24012        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24013        storage.setPrimaryStorageUuid(volumeUuid, callback);
24014        return realMoveId;
24015    }
24016
24017    @Override
24018    public int getMoveStatus(int moveId) {
24019        mContext.enforceCallingOrSelfPermission(
24020                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24021        return mMoveCallbacks.mLastStatus.get(moveId);
24022    }
24023
24024    @Override
24025    public void registerMoveCallback(IPackageMoveObserver callback) {
24026        mContext.enforceCallingOrSelfPermission(
24027                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24028        mMoveCallbacks.register(callback);
24029    }
24030
24031    @Override
24032    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24033        mContext.enforceCallingOrSelfPermission(
24034                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24035        mMoveCallbacks.unregister(callback);
24036    }
24037
24038    @Override
24039    public boolean setInstallLocation(int loc) {
24040        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24041                null);
24042        if (getInstallLocation() == loc) {
24043            return true;
24044        }
24045        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24046                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24047            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24048                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24049            return true;
24050        }
24051        return false;
24052   }
24053
24054    @Override
24055    public int getInstallLocation() {
24056        // allow instant app access
24057        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24058                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24059                PackageHelper.APP_INSTALL_AUTO);
24060    }
24061
24062    /** Called by UserManagerService */
24063    void cleanUpUser(UserManagerService userManager, int userHandle) {
24064        synchronized (mPackages) {
24065            mDirtyUsers.remove(userHandle);
24066            mUserNeedsBadging.delete(userHandle);
24067            mSettings.removeUserLPw(userHandle);
24068            mPendingBroadcasts.remove(userHandle);
24069            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24070            removeUnusedPackagesLPw(userManager, userHandle);
24071        }
24072    }
24073
24074    /**
24075     * We're removing userHandle and would like to remove any downloaded packages
24076     * that are no longer in use by any other user.
24077     * @param userHandle the user being removed
24078     */
24079    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24080        final boolean DEBUG_CLEAN_APKS = false;
24081        int [] users = userManager.getUserIds();
24082        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24083        while (psit.hasNext()) {
24084            PackageSetting ps = psit.next();
24085            if (ps.pkg == null) {
24086                continue;
24087            }
24088            final String packageName = ps.pkg.packageName;
24089            // Skip over if system app
24090            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24091                continue;
24092            }
24093            if (DEBUG_CLEAN_APKS) {
24094                Slog.i(TAG, "Checking package " + packageName);
24095            }
24096            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24097            if (keep) {
24098                if (DEBUG_CLEAN_APKS) {
24099                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24100                }
24101            } else {
24102                for (int i = 0; i < users.length; i++) {
24103                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24104                        keep = true;
24105                        if (DEBUG_CLEAN_APKS) {
24106                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24107                                    + users[i]);
24108                        }
24109                        break;
24110                    }
24111                }
24112            }
24113            if (!keep) {
24114                if (DEBUG_CLEAN_APKS) {
24115                    Slog.i(TAG, "  Removing package " + packageName);
24116                }
24117                mHandler.post(new Runnable() {
24118                    public void run() {
24119                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24120                                userHandle, 0);
24121                    } //end run
24122                });
24123            }
24124        }
24125    }
24126
24127    /** Called by UserManagerService */
24128    void createNewUser(int userId, String[] disallowedPackages) {
24129        synchronized (mInstallLock) {
24130            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24131        }
24132        synchronized (mPackages) {
24133            scheduleWritePackageRestrictionsLocked(userId);
24134            scheduleWritePackageListLocked(userId);
24135            applyFactoryDefaultBrowserLPw(userId);
24136            primeDomainVerificationsLPw(userId);
24137        }
24138    }
24139
24140    void onNewUserCreated(final int userId) {
24141        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24142        // If permission review for legacy apps is required, we represent
24143        // dagerous permissions for such apps as always granted runtime
24144        // permissions to keep per user flag state whether review is needed.
24145        // Hence, if a new user is added we have to propagate dangerous
24146        // permission grants for these legacy apps.
24147        if (mPermissionReviewRequired) {
24148            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24149                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24150        }
24151    }
24152
24153    @Override
24154    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24155        mContext.enforceCallingOrSelfPermission(
24156                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24157                "Only package verification agents can read the verifier device identity");
24158
24159        synchronized (mPackages) {
24160            return mSettings.getVerifierDeviceIdentityLPw();
24161        }
24162    }
24163
24164    @Override
24165    public void setPermissionEnforced(String permission, boolean enforced) {
24166        // TODO: Now that we no longer change GID for storage, this should to away.
24167        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24168                "setPermissionEnforced");
24169        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24170            synchronized (mPackages) {
24171                if (mSettings.mReadExternalStorageEnforced == null
24172                        || mSettings.mReadExternalStorageEnforced != enforced) {
24173                    mSettings.mReadExternalStorageEnforced = enforced;
24174                    mSettings.writeLPr();
24175                }
24176            }
24177            // kill any non-foreground processes so we restart them and
24178            // grant/revoke the GID.
24179            final IActivityManager am = ActivityManager.getService();
24180            if (am != null) {
24181                final long token = Binder.clearCallingIdentity();
24182                try {
24183                    am.killProcessesBelowForeground("setPermissionEnforcement");
24184                } catch (RemoteException e) {
24185                } finally {
24186                    Binder.restoreCallingIdentity(token);
24187                }
24188            }
24189        } else {
24190            throw new IllegalArgumentException("No selective enforcement for " + permission);
24191        }
24192    }
24193
24194    @Override
24195    @Deprecated
24196    public boolean isPermissionEnforced(String permission) {
24197        // allow instant applications
24198        return true;
24199    }
24200
24201    @Override
24202    public boolean isStorageLow() {
24203        // allow instant applications
24204        final long token = Binder.clearCallingIdentity();
24205        try {
24206            final DeviceStorageMonitorInternal
24207                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24208            if (dsm != null) {
24209                return dsm.isMemoryLow();
24210            } else {
24211                return false;
24212            }
24213        } finally {
24214            Binder.restoreCallingIdentity(token);
24215        }
24216    }
24217
24218    @Override
24219    public IPackageInstaller getPackageInstaller() {
24220        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24221            return null;
24222        }
24223        return mInstallerService;
24224    }
24225
24226    private boolean userNeedsBadging(int userId) {
24227        int index = mUserNeedsBadging.indexOfKey(userId);
24228        if (index < 0) {
24229            final UserInfo userInfo;
24230            final long token = Binder.clearCallingIdentity();
24231            try {
24232                userInfo = sUserManager.getUserInfo(userId);
24233            } finally {
24234                Binder.restoreCallingIdentity(token);
24235            }
24236            final boolean b;
24237            if (userInfo != null && userInfo.isManagedProfile()) {
24238                b = true;
24239            } else {
24240                b = false;
24241            }
24242            mUserNeedsBadging.put(userId, b);
24243            return b;
24244        }
24245        return mUserNeedsBadging.valueAt(index);
24246    }
24247
24248    @Override
24249    public KeySet getKeySetByAlias(String packageName, String alias) {
24250        if (packageName == null || alias == null) {
24251            return null;
24252        }
24253        synchronized(mPackages) {
24254            final PackageParser.Package pkg = mPackages.get(packageName);
24255            if (pkg == null) {
24256                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24257                throw new IllegalArgumentException("Unknown package: " + packageName);
24258            }
24259            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24260            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24261                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24262                throw new IllegalArgumentException("Unknown package: " + packageName);
24263            }
24264            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24265            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24266        }
24267    }
24268
24269    @Override
24270    public KeySet getSigningKeySet(String packageName) {
24271        if (packageName == null) {
24272            return null;
24273        }
24274        synchronized(mPackages) {
24275            final int callingUid = Binder.getCallingUid();
24276            final int callingUserId = UserHandle.getUserId(callingUid);
24277            final PackageParser.Package pkg = mPackages.get(packageName);
24278            if (pkg == null) {
24279                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24280                throw new IllegalArgumentException("Unknown package: " + packageName);
24281            }
24282            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24283            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24284                // filter and pretend the package doesn't exist
24285                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24286                        + ", uid:" + callingUid);
24287                throw new IllegalArgumentException("Unknown package: " + packageName);
24288            }
24289            if (pkg.applicationInfo.uid != callingUid
24290                    && Process.SYSTEM_UID != callingUid) {
24291                throw new SecurityException("May not access signing KeySet of other apps.");
24292            }
24293            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24294            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24295        }
24296    }
24297
24298    @Override
24299    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24300        final int callingUid = Binder.getCallingUid();
24301        if (getInstantAppPackageName(callingUid) != null) {
24302            return false;
24303        }
24304        if (packageName == null || ks == null) {
24305            return false;
24306        }
24307        synchronized(mPackages) {
24308            final PackageParser.Package pkg = mPackages.get(packageName);
24309            if (pkg == null
24310                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24311                            UserHandle.getUserId(callingUid))) {
24312                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24313                throw new IllegalArgumentException("Unknown package: " + packageName);
24314            }
24315            IBinder ksh = ks.getToken();
24316            if (ksh instanceof KeySetHandle) {
24317                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24318                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24319            }
24320            return false;
24321        }
24322    }
24323
24324    @Override
24325    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24326        final int callingUid = Binder.getCallingUid();
24327        if (getInstantAppPackageName(callingUid) != null) {
24328            return false;
24329        }
24330        if (packageName == null || ks == null) {
24331            return false;
24332        }
24333        synchronized(mPackages) {
24334            final PackageParser.Package pkg = mPackages.get(packageName);
24335            if (pkg == null
24336                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24337                            UserHandle.getUserId(callingUid))) {
24338                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24339                throw new IllegalArgumentException("Unknown package: " + packageName);
24340            }
24341            IBinder ksh = ks.getToken();
24342            if (ksh instanceof KeySetHandle) {
24343                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24344                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24345            }
24346            return false;
24347        }
24348    }
24349
24350    private void deletePackageIfUnusedLPr(final String packageName) {
24351        PackageSetting ps = mSettings.mPackages.get(packageName);
24352        if (ps == null) {
24353            return;
24354        }
24355        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24356            // TODO Implement atomic delete if package is unused
24357            // It is currently possible that the package will be deleted even if it is installed
24358            // after this method returns.
24359            mHandler.post(new Runnable() {
24360                public void run() {
24361                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24362                            0, PackageManager.DELETE_ALL_USERS);
24363                }
24364            });
24365        }
24366    }
24367
24368    /**
24369     * Check and throw if the given before/after packages would be considered a
24370     * downgrade.
24371     */
24372    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24373            throws PackageManagerException {
24374        if (after.versionCode < before.mVersionCode) {
24375            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24376                    "Update version code " + after.versionCode + " is older than current "
24377                    + before.mVersionCode);
24378        } else if (after.versionCode == before.mVersionCode) {
24379            if (after.baseRevisionCode < before.baseRevisionCode) {
24380                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24381                        "Update base revision code " + after.baseRevisionCode
24382                        + " is older than current " + before.baseRevisionCode);
24383            }
24384
24385            if (!ArrayUtils.isEmpty(after.splitNames)) {
24386                for (int i = 0; i < after.splitNames.length; i++) {
24387                    final String splitName = after.splitNames[i];
24388                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24389                    if (j != -1) {
24390                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24391                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24392                                    "Update split " + splitName + " revision code "
24393                                    + after.splitRevisionCodes[i] + " is older than current "
24394                                    + before.splitRevisionCodes[j]);
24395                        }
24396                    }
24397                }
24398            }
24399        }
24400    }
24401
24402    private static class MoveCallbacks extends Handler {
24403        private static final int MSG_CREATED = 1;
24404        private static final int MSG_STATUS_CHANGED = 2;
24405
24406        private final RemoteCallbackList<IPackageMoveObserver>
24407                mCallbacks = new RemoteCallbackList<>();
24408
24409        private final SparseIntArray mLastStatus = new SparseIntArray();
24410
24411        public MoveCallbacks(Looper looper) {
24412            super(looper);
24413        }
24414
24415        public void register(IPackageMoveObserver callback) {
24416            mCallbacks.register(callback);
24417        }
24418
24419        public void unregister(IPackageMoveObserver callback) {
24420            mCallbacks.unregister(callback);
24421        }
24422
24423        @Override
24424        public void handleMessage(Message msg) {
24425            final SomeArgs args = (SomeArgs) msg.obj;
24426            final int n = mCallbacks.beginBroadcast();
24427            for (int i = 0; i < n; i++) {
24428                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24429                try {
24430                    invokeCallback(callback, msg.what, args);
24431                } catch (RemoteException ignored) {
24432                }
24433            }
24434            mCallbacks.finishBroadcast();
24435            args.recycle();
24436        }
24437
24438        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24439                throws RemoteException {
24440            switch (what) {
24441                case MSG_CREATED: {
24442                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24443                    break;
24444                }
24445                case MSG_STATUS_CHANGED: {
24446                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24447                    break;
24448                }
24449            }
24450        }
24451
24452        private void notifyCreated(int moveId, Bundle extras) {
24453            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24454
24455            final SomeArgs args = SomeArgs.obtain();
24456            args.argi1 = moveId;
24457            args.arg2 = extras;
24458            obtainMessage(MSG_CREATED, args).sendToTarget();
24459        }
24460
24461        private void notifyStatusChanged(int moveId, int status) {
24462            notifyStatusChanged(moveId, status, -1);
24463        }
24464
24465        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24466            Slog.v(TAG, "Move " + moveId + " status " + status);
24467
24468            final SomeArgs args = SomeArgs.obtain();
24469            args.argi1 = moveId;
24470            args.argi2 = status;
24471            args.arg3 = estMillis;
24472            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24473
24474            synchronized (mLastStatus) {
24475                mLastStatus.put(moveId, status);
24476            }
24477        }
24478    }
24479
24480    private final static class OnPermissionChangeListeners extends Handler {
24481        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24482
24483        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24484                new RemoteCallbackList<>();
24485
24486        public OnPermissionChangeListeners(Looper looper) {
24487            super(looper);
24488        }
24489
24490        @Override
24491        public void handleMessage(Message msg) {
24492            switch (msg.what) {
24493                case MSG_ON_PERMISSIONS_CHANGED: {
24494                    final int uid = msg.arg1;
24495                    handleOnPermissionsChanged(uid);
24496                } break;
24497            }
24498        }
24499
24500        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24501            mPermissionListeners.register(listener);
24502
24503        }
24504
24505        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24506            mPermissionListeners.unregister(listener);
24507        }
24508
24509        public void onPermissionsChanged(int uid) {
24510            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24511                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24512            }
24513        }
24514
24515        private void handleOnPermissionsChanged(int uid) {
24516            final int count = mPermissionListeners.beginBroadcast();
24517            try {
24518                for (int i = 0; i < count; i++) {
24519                    IOnPermissionsChangeListener callback = mPermissionListeners
24520                            .getBroadcastItem(i);
24521                    try {
24522                        callback.onPermissionsChanged(uid);
24523                    } catch (RemoteException e) {
24524                        Log.e(TAG, "Permission listener is dead", e);
24525                    }
24526                }
24527            } finally {
24528                mPermissionListeners.finishBroadcast();
24529            }
24530        }
24531    }
24532
24533    private class PackageManagerNative extends IPackageManagerNative.Stub {
24534        @Override
24535        public String[] getNamesForUids(int[] uids) throws RemoteException {
24536            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24537            // massage results so they can be parsed by the native binder
24538            for (int i = results.length - 1; i >= 0; --i) {
24539                if (results[i] == null) {
24540                    results[i] = "";
24541                }
24542            }
24543            return results;
24544        }
24545
24546        // NB: this differentiates between preloads and sideloads
24547        @Override
24548        public String getInstallerForPackage(String packageName) throws RemoteException {
24549            final String installerName = getInstallerPackageName(packageName);
24550            if (!TextUtils.isEmpty(installerName)) {
24551                return installerName;
24552            }
24553            // differentiate between preload and sideload
24554            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24555            ApplicationInfo appInfo = getApplicationInfo(packageName,
24556                                    /*flags*/ 0,
24557                                    /*userId*/ callingUser);
24558            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24559                return "preload";
24560            }
24561            return "";
24562        }
24563
24564        @Override
24565        public int getVersionCodeForPackage(String packageName) throws RemoteException {
24566            try {
24567                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24568                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
24569                if (pInfo != null) {
24570                    return pInfo.versionCode;
24571                }
24572            } catch (Exception e) {
24573            }
24574            return 0;
24575        }
24576    }
24577
24578    private class PackageManagerInternalImpl extends PackageManagerInternal {
24579        @Override
24580        public void setLocationPackagesProvider(PackagesProvider provider) {
24581            synchronized (mPackages) {
24582                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24583            }
24584        }
24585
24586        @Override
24587        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24588            synchronized (mPackages) {
24589                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24590            }
24591        }
24592
24593        @Override
24594        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24595            synchronized (mPackages) {
24596                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24597            }
24598        }
24599
24600        @Override
24601        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24602            synchronized (mPackages) {
24603                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24604            }
24605        }
24606
24607        @Override
24608        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24609            synchronized (mPackages) {
24610                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24611            }
24612        }
24613
24614        @Override
24615        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24616            synchronized (mPackages) {
24617                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24618            }
24619        }
24620
24621        @Override
24622        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24623            synchronized (mPackages) {
24624                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24625                        packageName, userId);
24626            }
24627        }
24628
24629        @Override
24630        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24631            synchronized (mPackages) {
24632                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24633                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24634                        packageName, userId);
24635            }
24636        }
24637
24638        @Override
24639        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24640            synchronized (mPackages) {
24641                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24642                        packageName, userId);
24643            }
24644        }
24645
24646        @Override
24647        public void setKeepUninstalledPackages(final List<String> packageList) {
24648            Preconditions.checkNotNull(packageList);
24649            List<String> removedFromList = null;
24650            synchronized (mPackages) {
24651                if (mKeepUninstalledPackages != null) {
24652                    final int packagesCount = mKeepUninstalledPackages.size();
24653                    for (int i = 0; i < packagesCount; i++) {
24654                        String oldPackage = mKeepUninstalledPackages.get(i);
24655                        if (packageList != null && packageList.contains(oldPackage)) {
24656                            continue;
24657                        }
24658                        if (removedFromList == null) {
24659                            removedFromList = new ArrayList<>();
24660                        }
24661                        removedFromList.add(oldPackage);
24662                    }
24663                }
24664                mKeepUninstalledPackages = new ArrayList<>(packageList);
24665                if (removedFromList != null) {
24666                    final int removedCount = removedFromList.size();
24667                    for (int i = 0; i < removedCount; i++) {
24668                        deletePackageIfUnusedLPr(removedFromList.get(i));
24669                    }
24670                }
24671            }
24672        }
24673
24674        @Override
24675        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24676            synchronized (mPackages) {
24677                // If we do not support permission review, done.
24678                if (!mPermissionReviewRequired) {
24679                    return false;
24680                }
24681
24682                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24683                if (packageSetting == null) {
24684                    return false;
24685                }
24686
24687                // Permission review applies only to apps not supporting the new permission model.
24688                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24689                    return false;
24690                }
24691
24692                // Legacy apps have the permission and get user consent on launch.
24693                PermissionsState permissionsState = packageSetting.getPermissionsState();
24694                return permissionsState.isPermissionReviewRequired(userId);
24695            }
24696        }
24697
24698        @Override
24699        public PackageInfo getPackageInfo(
24700                String packageName, int flags, int filterCallingUid, int userId) {
24701            return PackageManagerService.this
24702                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24703                            flags, filterCallingUid, userId);
24704        }
24705
24706        @Override
24707        public ApplicationInfo getApplicationInfo(
24708                String packageName, int flags, int filterCallingUid, int userId) {
24709            return PackageManagerService.this
24710                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24711        }
24712
24713        @Override
24714        public ActivityInfo getActivityInfo(
24715                ComponentName component, int flags, int filterCallingUid, int userId) {
24716            return PackageManagerService.this
24717                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24718        }
24719
24720        @Override
24721        public List<ResolveInfo> queryIntentActivities(
24722                Intent intent, int flags, int filterCallingUid, int userId) {
24723            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24724            return PackageManagerService.this
24725                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24726                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
24727        }
24728
24729        @Override
24730        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24731                int userId) {
24732            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24733        }
24734
24735        @Override
24736        public void setDeviceAndProfileOwnerPackages(
24737                int deviceOwnerUserId, String deviceOwnerPackage,
24738                SparseArray<String> profileOwnerPackages) {
24739            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24740                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24741        }
24742
24743        @Override
24744        public boolean isPackageDataProtected(int userId, String packageName) {
24745            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24746        }
24747
24748        @Override
24749        public boolean isPackageEphemeral(int userId, String packageName) {
24750            synchronized (mPackages) {
24751                final PackageSetting ps = mSettings.mPackages.get(packageName);
24752                return ps != null ? ps.getInstantApp(userId) : false;
24753            }
24754        }
24755
24756        @Override
24757        public boolean wasPackageEverLaunched(String packageName, int userId) {
24758            synchronized (mPackages) {
24759                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24760            }
24761        }
24762
24763        @Override
24764        public void grantRuntimePermission(String packageName, String name, int userId,
24765                boolean overridePolicy) {
24766            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24767                    overridePolicy);
24768        }
24769
24770        @Override
24771        public void revokeRuntimePermission(String packageName, String name, int userId,
24772                boolean overridePolicy) {
24773            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24774                    overridePolicy);
24775        }
24776
24777        @Override
24778        public String getNameForUid(int uid) {
24779            return PackageManagerService.this.getNameForUid(uid);
24780        }
24781
24782        @Override
24783        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24784                Intent origIntent, String resolvedType, String callingPackage,
24785                Bundle verificationBundle, int userId) {
24786            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24787                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24788                    userId);
24789        }
24790
24791        @Override
24792        public void grantEphemeralAccess(int userId, Intent intent,
24793                int targetAppId, int ephemeralAppId) {
24794            synchronized (mPackages) {
24795                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24796                        targetAppId, ephemeralAppId);
24797            }
24798        }
24799
24800        @Override
24801        public boolean isInstantAppInstallerComponent(ComponentName component) {
24802            synchronized (mPackages) {
24803                return mInstantAppInstallerActivity != null
24804                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24805            }
24806        }
24807
24808        @Override
24809        public void pruneInstantApps() {
24810            mInstantAppRegistry.pruneInstantApps();
24811        }
24812
24813        @Override
24814        public String getSetupWizardPackageName() {
24815            return mSetupWizardPackage;
24816        }
24817
24818        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24819            if (policy != null) {
24820                mExternalSourcesPolicy = policy;
24821            }
24822        }
24823
24824        @Override
24825        public boolean isPackagePersistent(String packageName) {
24826            synchronized (mPackages) {
24827                PackageParser.Package pkg = mPackages.get(packageName);
24828                return pkg != null
24829                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24830                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24831                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24832                        : false;
24833            }
24834        }
24835
24836        @Override
24837        public List<PackageInfo> getOverlayPackages(int userId) {
24838            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24839            synchronized (mPackages) {
24840                for (PackageParser.Package p : mPackages.values()) {
24841                    if (p.mOverlayTarget != null) {
24842                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24843                        if (pkg != null) {
24844                            overlayPackages.add(pkg);
24845                        }
24846                    }
24847                }
24848            }
24849            return overlayPackages;
24850        }
24851
24852        @Override
24853        public List<String> getTargetPackageNames(int userId) {
24854            List<String> targetPackages = new ArrayList<>();
24855            synchronized (mPackages) {
24856                for (PackageParser.Package p : mPackages.values()) {
24857                    if (p.mOverlayTarget == null) {
24858                        targetPackages.add(p.packageName);
24859                    }
24860                }
24861            }
24862            return targetPackages;
24863        }
24864
24865        @Override
24866        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24867                @Nullable List<String> overlayPackageNames) {
24868            synchronized (mPackages) {
24869                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24870                    Slog.e(TAG, "failed to find package " + targetPackageName);
24871                    return false;
24872                }
24873                ArrayList<String> overlayPaths = null;
24874                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24875                    final int N = overlayPackageNames.size();
24876                    overlayPaths = new ArrayList<>(N);
24877                    for (int i = 0; i < N; i++) {
24878                        final String packageName = overlayPackageNames.get(i);
24879                        final PackageParser.Package pkg = mPackages.get(packageName);
24880                        if (pkg == null) {
24881                            Slog.e(TAG, "failed to find package " + packageName);
24882                            return false;
24883                        }
24884                        overlayPaths.add(pkg.baseCodePath);
24885                    }
24886                }
24887
24888                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24889                ps.setOverlayPaths(overlayPaths, userId);
24890                return true;
24891            }
24892        }
24893
24894        @Override
24895        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24896                int flags, int userId) {
24897            return resolveIntentInternal(
24898                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24899        }
24900
24901        @Override
24902        public ResolveInfo resolveService(Intent intent, String resolvedType,
24903                int flags, int userId, int callingUid) {
24904            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24905        }
24906
24907        @Override
24908        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24909            synchronized (mPackages) {
24910                mIsolatedOwners.put(isolatedUid, ownerUid);
24911            }
24912        }
24913
24914        @Override
24915        public void removeIsolatedUid(int isolatedUid) {
24916            synchronized (mPackages) {
24917                mIsolatedOwners.delete(isolatedUid);
24918            }
24919        }
24920
24921        @Override
24922        public int getUidTargetSdkVersion(int uid) {
24923            synchronized (mPackages) {
24924                return getUidTargetSdkVersionLockedLPr(uid);
24925            }
24926        }
24927
24928        @Override
24929        public boolean canAccessInstantApps(int callingUid, int userId) {
24930            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24931        }
24932
24933        @Override
24934        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24935            synchronized (mPackages) {
24936                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24937            }
24938        }
24939
24940        @Override
24941        public void notifyPackageUse(String packageName, int reason) {
24942            synchronized (mPackages) {
24943                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24944            }
24945        }
24946    }
24947
24948    @Override
24949    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24950        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24951        synchronized (mPackages) {
24952            final long identity = Binder.clearCallingIdentity();
24953            try {
24954                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24955                        packageNames, userId);
24956            } finally {
24957                Binder.restoreCallingIdentity(identity);
24958            }
24959        }
24960    }
24961
24962    @Override
24963    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24964        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24965        synchronized (mPackages) {
24966            final long identity = Binder.clearCallingIdentity();
24967            try {
24968                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24969                        packageNames, userId);
24970            } finally {
24971                Binder.restoreCallingIdentity(identity);
24972            }
24973        }
24974    }
24975
24976    private static void enforceSystemOrPhoneCaller(String tag) {
24977        int callingUid = Binder.getCallingUid();
24978        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24979            throw new SecurityException(
24980                    "Cannot call " + tag + " from UID " + callingUid);
24981        }
24982    }
24983
24984    boolean isHistoricalPackageUsageAvailable() {
24985        return mPackageUsage.isHistoricalPackageUsageAvailable();
24986    }
24987
24988    /**
24989     * Return a <b>copy</b> of the collection of packages known to the package manager.
24990     * @return A copy of the values of mPackages.
24991     */
24992    Collection<PackageParser.Package> getPackages() {
24993        synchronized (mPackages) {
24994            return new ArrayList<>(mPackages.values());
24995        }
24996    }
24997
24998    /**
24999     * Logs process start information (including base APK hash) to the security log.
25000     * @hide
25001     */
25002    @Override
25003    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25004            String apkFile, int pid) {
25005        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25006            return;
25007        }
25008        if (!SecurityLog.isLoggingEnabled()) {
25009            return;
25010        }
25011        Bundle data = new Bundle();
25012        data.putLong("startTimestamp", System.currentTimeMillis());
25013        data.putString("processName", processName);
25014        data.putInt("uid", uid);
25015        data.putString("seinfo", seinfo);
25016        data.putString("apkFile", apkFile);
25017        data.putInt("pid", pid);
25018        Message msg = mProcessLoggingHandler.obtainMessage(
25019                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25020        msg.setData(data);
25021        mProcessLoggingHandler.sendMessage(msg);
25022    }
25023
25024    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25025        return mCompilerStats.getPackageStats(pkgName);
25026    }
25027
25028    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25029        return getOrCreateCompilerPackageStats(pkg.packageName);
25030    }
25031
25032    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25033        return mCompilerStats.getOrCreatePackageStats(pkgName);
25034    }
25035
25036    public void deleteCompilerPackageStats(String pkgName) {
25037        mCompilerStats.deletePackageStats(pkgName);
25038    }
25039
25040    @Override
25041    public int getInstallReason(String packageName, int userId) {
25042        final int callingUid = Binder.getCallingUid();
25043        enforceCrossUserPermission(callingUid, userId,
25044                true /* requireFullPermission */, false /* checkShell */,
25045                "get install reason");
25046        synchronized (mPackages) {
25047            final PackageSetting ps = mSettings.mPackages.get(packageName);
25048            if (filterAppAccessLPr(ps, callingUid, userId)) {
25049                return PackageManager.INSTALL_REASON_UNKNOWN;
25050            }
25051            if (ps != null) {
25052                return ps.getInstallReason(userId);
25053            }
25054        }
25055        return PackageManager.INSTALL_REASON_UNKNOWN;
25056    }
25057
25058    @Override
25059    public boolean canRequestPackageInstalls(String packageName, int userId) {
25060        return canRequestPackageInstallsInternal(packageName, 0, userId,
25061                true /* throwIfPermNotDeclared*/);
25062    }
25063
25064    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25065            boolean throwIfPermNotDeclared) {
25066        int callingUid = Binder.getCallingUid();
25067        int uid = getPackageUid(packageName, 0, userId);
25068        if (callingUid != uid && callingUid != Process.ROOT_UID
25069                && callingUid != Process.SYSTEM_UID) {
25070            throw new SecurityException(
25071                    "Caller uid " + callingUid + " does not own package " + packageName);
25072        }
25073        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25074        if (info == null) {
25075            return false;
25076        }
25077        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25078            return false;
25079        }
25080        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25081        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25082        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25083            if (throwIfPermNotDeclared) {
25084                throw new SecurityException("Need to declare " + appOpPermission
25085                        + " to call this api");
25086            } else {
25087                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25088                return false;
25089            }
25090        }
25091        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25092            return false;
25093        }
25094        if (mExternalSourcesPolicy != null) {
25095            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25096            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25097                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25098            }
25099        }
25100        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25101    }
25102
25103    @Override
25104    public ComponentName getInstantAppResolverSettingsComponent() {
25105        return mInstantAppResolverSettingsComponent;
25106    }
25107
25108    @Override
25109    public ComponentName getInstantAppInstallerComponent() {
25110        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25111            return null;
25112        }
25113        return mInstantAppInstallerActivity == null
25114                ? null : mInstantAppInstallerActivity.getComponentName();
25115    }
25116
25117    @Override
25118    public String getInstantAppAndroidId(String packageName, int userId) {
25119        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25120                "getInstantAppAndroidId");
25121        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25122                true /* requireFullPermission */, false /* checkShell */,
25123                "getInstantAppAndroidId");
25124        // Make sure the target is an Instant App.
25125        if (!isInstantApp(packageName, userId)) {
25126            return null;
25127        }
25128        synchronized (mPackages) {
25129            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25130        }
25131    }
25132
25133    boolean canHaveOatDir(String packageName) {
25134        synchronized (mPackages) {
25135            PackageParser.Package p = mPackages.get(packageName);
25136            if (p == null) {
25137                return false;
25138            }
25139            return p.canHaveOatDir();
25140        }
25141    }
25142
25143    private String getOatDir(PackageParser.Package pkg) {
25144        if (!pkg.canHaveOatDir()) {
25145            return null;
25146        }
25147        File codePath = new File(pkg.codePath);
25148        if (codePath.isDirectory()) {
25149            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25150        }
25151        return null;
25152    }
25153
25154    void deleteOatArtifactsOfPackage(String packageName) {
25155        final String[] instructionSets;
25156        final List<String> codePaths;
25157        final String oatDir;
25158        final PackageParser.Package pkg;
25159        synchronized (mPackages) {
25160            pkg = mPackages.get(packageName);
25161        }
25162        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25163        codePaths = pkg.getAllCodePaths();
25164        oatDir = getOatDir(pkg);
25165
25166        for (String codePath : codePaths) {
25167            for (String isa : instructionSets) {
25168                try {
25169                    mInstaller.deleteOdex(codePath, isa, oatDir);
25170                } catch (InstallerException e) {
25171                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25172                }
25173            }
25174        }
25175    }
25176
25177    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25178        Set<String> unusedPackages = new HashSet<>();
25179        long currentTimeInMillis = System.currentTimeMillis();
25180        synchronized (mPackages) {
25181            for (PackageParser.Package pkg : mPackages.values()) {
25182                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25183                if (ps == null) {
25184                    continue;
25185                }
25186                PackageDexUsage.PackageUseInfo packageUseInfo =
25187                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25188                if (PackageManagerServiceUtils
25189                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25190                                downgradeTimeThresholdMillis, packageUseInfo,
25191                                pkg.getLatestPackageUseTimeInMills(),
25192                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25193                    unusedPackages.add(pkg.packageName);
25194                }
25195            }
25196        }
25197        return unusedPackages;
25198    }
25199}
25200
25201interface PackageSender {
25202    void sendPackageBroadcast(final String action, final String pkg,
25203        final Bundle extras, final int flags, final String targetPkg,
25204        final IIntentReceiver finishedReceiver, final int[] userIds);
25205    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25206        boolean includeStopped, int appId, int... userIds);
25207}
25208