PackageManagerService.java revision f53201f8c796e8500b76b72e4fad6269d8547369
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108
109import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
110
111import android.Manifest;
112import android.annotation.IntDef;
113import android.annotation.NonNull;
114import android.annotation.Nullable;
115import android.app.ActivityManager;
116import android.app.AppOpsManager;
117import android.app.IActivityManager;
118import android.app.ResourcesManager;
119import android.app.admin.IDevicePolicyManager;
120import android.app.admin.SecurityLog;
121import android.app.backup.IBackupManager;
122import android.content.BroadcastReceiver;
123import android.content.ComponentName;
124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.IIntentReceiver;
127import android.content.Intent;
128import android.content.IntentFilter;
129import android.content.IntentSender;
130import android.content.IntentSender.SendIntentException;
131import android.content.ServiceConnection;
132import android.content.pm.ActivityInfo;
133import android.content.pm.ApplicationInfo;
134import android.content.pm.AppsQueryHelper;
135import android.content.pm.AuxiliaryResolveInfo;
136import android.content.pm.ChangedPackages;
137import android.content.pm.ComponentInfo;
138import android.content.pm.FallbackCategoryProvider;
139import android.content.pm.FeatureInfo;
140import android.content.pm.IDexModuleRegisterCallback;
141import android.content.pm.IOnPermissionsChangeListener;
142import android.content.pm.IPackageDataObserver;
143import android.content.pm.IPackageDeleteObserver;
144import android.content.pm.IPackageDeleteObserver2;
145import android.content.pm.IPackageInstallObserver2;
146import android.content.pm.IPackageInstaller;
147import android.content.pm.IPackageManager;
148import android.content.pm.IPackageManagerNative;
149import android.content.pm.IPackageMoveObserver;
150import android.content.pm.IPackageStatsObserver;
151import android.content.pm.InstantAppInfo;
152import android.content.pm.InstantAppRequest;
153import android.content.pm.InstantAppResolveInfo;
154import android.content.pm.InstrumentationInfo;
155import android.content.pm.IntentFilterVerificationInfo;
156import android.content.pm.KeySet;
157import android.content.pm.PackageCleanItem;
158import android.content.pm.PackageInfo;
159import android.content.pm.PackageInfoLite;
160import android.content.pm.PackageInstaller;
161import android.content.pm.PackageManager;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageManagerInternal;
164import android.content.pm.PackageParser;
165import android.content.pm.PackageParser.ActivityIntentInfo;
166import android.content.pm.PackageParser.PackageLite;
167import android.content.pm.PackageParser.PackageParserException;
168import android.content.pm.PackageStats;
169import android.content.pm.PackageUserState;
170import android.content.pm.ParceledListSlice;
171import android.content.pm.PermissionGroupInfo;
172import android.content.pm.PermissionInfo;
173import android.content.pm.ProviderInfo;
174import android.content.pm.ResolveInfo;
175import android.content.pm.ServiceInfo;
176import android.content.pm.SharedLibraryInfo;
177import android.content.pm.Signature;
178import android.content.pm.UserInfo;
179import android.content.pm.VerifierDeviceIdentity;
180import android.content.pm.VerifierInfo;
181import android.content.pm.VersionedPackage;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.TimingsTraceLog;
233import android.util.DisplayMetrics;
234import android.util.EventLog;
235import android.util.ExceptionUtils;
236import android.util.Log;
237import android.util.LogPrinter;
238import android.util.MathUtils;
239import android.util.PackageUtils;
240import android.util.Pair;
241import android.util.PrintStreamPrinter;
242import android.util.Slog;
243import android.util.SparseArray;
244import android.util.SparseBooleanArray;
245import android.util.SparseIntArray;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.PermissionsState.PermissionState;
286import com.android.server.pm.Settings.DatabaseVersion;
287import com.android.server.pm.Settings.VersionInfo;
288import com.android.server.pm.dex.DexManager;
289import com.android.server.pm.dex.DexoptOptions;
290import com.android.server.pm.dex.PackageDexUsage;
291import com.android.server.storage.DeviceStorageMonitorInternal;
292
293import dalvik.system.CloseGuard;
294import dalvik.system.DexFile;
295import dalvik.system.VMRuntime;
296
297import libcore.io.IoUtils;
298import libcore.io.Streams;
299import libcore.util.EmptyArray;
300
301import org.xmlpull.v1.XmlPullParser;
302import org.xmlpull.v1.XmlPullParserException;
303import org.xmlpull.v1.XmlSerializer;
304
305import java.io.BufferedOutputStream;
306import java.io.BufferedReader;
307import java.io.ByteArrayInputStream;
308import java.io.ByteArrayOutputStream;
309import java.io.File;
310import java.io.FileDescriptor;
311import java.io.FileInputStream;
312import java.io.FileOutputStream;
313import java.io.FileReader;
314import java.io.FilenameFilter;
315import java.io.IOException;
316import java.io.InputStream;
317import java.io.OutputStream;
318import java.io.PrintWriter;
319import java.lang.annotation.Retention;
320import java.lang.annotation.RetentionPolicy;
321import java.nio.charset.StandardCharsets;
322import java.security.DigestInputStream;
323import java.security.MessageDigest;
324import java.security.NoSuchAlgorithmException;
325import java.security.PublicKey;
326import java.security.SecureRandom;
327import java.security.cert.Certificate;
328import java.security.cert.CertificateEncodingException;
329import java.security.cert.CertificateException;
330import java.text.SimpleDateFormat;
331import java.util.ArrayList;
332import java.util.Arrays;
333import java.util.Collection;
334import java.util.Collections;
335import java.util.Comparator;
336import java.util.Date;
337import java.util.HashMap;
338import java.util.HashSet;
339import java.util.Iterator;
340import java.util.List;
341import java.util.Map;
342import java.util.Objects;
343import java.util.Set;
344import java.util.concurrent.CountDownLatch;
345import java.util.concurrent.Future;
346import java.util.concurrent.TimeUnit;
347import java.util.concurrent.atomic.AtomicBoolean;
348import java.util.concurrent.atomic.AtomicInteger;
349import java.util.zip.GZIPInputStream;
350
351/**
352 * Keep track of all those APKs everywhere.
353 * <p>
354 * Internally there are two important locks:
355 * <ul>
356 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
357 * and other related state. It is a fine-grained lock that should only be held
358 * momentarily, as it's one of the most contended locks in the system.
359 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
360 * operations typically involve heavy lifting of application data on disk. Since
361 * {@code installd} is single-threaded, and it's operations can often be slow,
362 * this lock should never be acquired while already holding {@link #mPackages}.
363 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
364 * holding {@link #mInstallLock}.
365 * </ul>
366 * Many internal methods rely on the caller to hold the appropriate locks, and
367 * this contract is expressed through method name suffixes:
368 * <ul>
369 * <li>fooLI(): the caller must hold {@link #mInstallLock}
370 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
371 * being modified must be frozen
372 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
373 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
374 * </ul>
375 * <p>
376 * Because this class is very central to the platform's security; please run all
377 * CTS and unit tests whenever making modifications:
378 *
379 * <pre>
380 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
381 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
382 * </pre>
383 */
384public class PackageManagerService extends IPackageManager.Stub
385        implements PackageSender {
386    static final String TAG = "PackageManager";
387    static final boolean DEBUG_SETTINGS = false;
388    static final boolean DEBUG_PREFERRED = false;
389    static final boolean DEBUG_UPGRADE = false;
390    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
391    private static final boolean DEBUG_BACKUP = false;
392    private static final boolean DEBUG_INSTALL = false;
393    private static final boolean DEBUG_REMOVE = false;
394    private static final boolean DEBUG_BROADCASTS = false;
395    private static final boolean DEBUG_SHOW_INFO = false;
396    private static final boolean DEBUG_PACKAGE_INFO = false;
397    private static final boolean DEBUG_INTENT_MATCHING = false;
398    private static final boolean DEBUG_PACKAGE_SCANNING = false;
399    private static final boolean DEBUG_VERIFY = false;
400    private static final boolean DEBUG_FILTERS = false;
401    private static final boolean DEBUG_PERMISSIONS = false;
402    private static final boolean DEBUG_SHARED_LIBRARIES = false;
403    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
404
405    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
406    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
407    // user, but by default initialize to this.
408    public static final boolean DEBUG_DEXOPT = false;
409
410    private static final boolean DEBUG_ABI_SELECTION = false;
411    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
412    private static final boolean DEBUG_TRIAGED_MISSING = false;
413    private static final boolean DEBUG_APP_DATA = false;
414
415    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
416    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
417
418    private static final boolean HIDE_EPHEMERAL_APIS = false;
419
420    private static final boolean ENABLE_FREE_CACHE_V2 =
421            SystemProperties.getBoolean("fw.free_cache_v2", true);
422
423    private static final int RADIO_UID = Process.PHONE_UID;
424    private static final int LOG_UID = Process.LOG_UID;
425    private static final int NFC_UID = Process.NFC_UID;
426    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
427    private static final int SHELL_UID = Process.SHELL_UID;
428
429    // Cap the size of permission trees that 3rd party apps can define
430    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
431
432    // Suffix used during package installation when copying/moving
433    // package apks to install directory.
434    private static final String INSTALL_PACKAGE_SUFFIX = "-";
435
436    static final int SCAN_NO_DEX = 1<<1;
437    static final int SCAN_FORCE_DEX = 1<<2;
438    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
439    static final int SCAN_NEW_INSTALL = 1<<4;
440    static final int SCAN_UPDATE_TIME = 1<<5;
441    static final int SCAN_BOOTING = 1<<6;
442    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
443    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
444    static final int SCAN_REPLACING = 1<<9;
445    static final int SCAN_REQUIRE_KNOWN = 1<<10;
446    static final int SCAN_MOVE = 1<<11;
447    static final int SCAN_INITIAL = 1<<12;
448    static final int SCAN_CHECK_ONLY = 1<<13;
449    static final int SCAN_DONT_KILL_APP = 1<<14;
450    static final int SCAN_IGNORE_FROZEN = 1<<15;
451    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
452    static final int SCAN_AS_INSTANT_APP = 1<<17;
453    static final int SCAN_AS_FULL_APP = 1<<18;
454    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
455    /** Should not be with the scan flags */
456    static final int FLAGS_REMOVE_CHATTY = 1<<31;
457
458    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
459    /** Extension of the compressed packages */
460    private final static String COMPRESSED_EXTENSION = ".gz";
461    /** Suffix of stub packages on the system partition */
462    private final static String STUB_SUFFIX = "-Stub";
463
464    private static final int[] EMPTY_INT_ARRAY = new int[0];
465
466    private static final int TYPE_UNKNOWN = 0;
467    private static final int TYPE_ACTIVITY = 1;
468    private static final int TYPE_RECEIVER = 2;
469    private static final int TYPE_SERVICE = 3;
470    private static final int TYPE_PROVIDER = 4;
471    @IntDef(prefix = { "TYPE_" }, value = {
472            TYPE_UNKNOWN,
473            TYPE_ACTIVITY,
474            TYPE_RECEIVER,
475            TYPE_SERVICE,
476            TYPE_PROVIDER,
477    })
478    @Retention(RetentionPolicy.SOURCE)
479    public @interface ComponentType {}
480
481    /**
482     * Timeout (in milliseconds) after which the watchdog should declare that
483     * our handler thread is wedged.  The usual default for such things is one
484     * minute but we sometimes do very lengthy I/O operations on this thread,
485     * such as installing multi-gigabyte applications, so ours needs to be longer.
486     */
487    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
488
489    /**
490     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
491     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
492     * settings entry if available, otherwise we use the hardcoded default.  If it's been
493     * more than this long since the last fstrim, we force one during the boot sequence.
494     *
495     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
496     * one gets run at the next available charging+idle time.  This final mandatory
497     * no-fstrim check kicks in only of the other scheduling criteria is never met.
498     */
499    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
500
501    /**
502     * Whether verification is enabled by default.
503     */
504    private static final boolean DEFAULT_VERIFY_ENABLE = true;
505
506    /**
507     * The default maximum time to wait for the verification agent to return in
508     * milliseconds.
509     */
510    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
511
512    /**
513     * The default response for package verification timeout.
514     *
515     * This can be either PackageManager.VERIFICATION_ALLOW or
516     * PackageManager.VERIFICATION_REJECT.
517     */
518    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
519
520    static final String PLATFORM_PACKAGE_NAME = "android";
521
522    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
523
524    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
525            DEFAULT_CONTAINER_PACKAGE,
526            "com.android.defcontainer.DefaultContainerService");
527
528    private static final String KILL_APP_REASON_GIDS_CHANGED =
529            "permission grant or revoke changed gids";
530
531    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
532            "permissions revoked";
533
534    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
535
536    private static final String PACKAGE_SCHEME = "package";
537
538    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
539
540    /** Permission grant: not grant the permission. */
541    private static final int GRANT_DENIED = 1;
542
543    /** Permission grant: grant the permission as an install permission. */
544    private static final int GRANT_INSTALL = 2;
545
546    /** Permission grant: grant the permission as a runtime one. */
547    private static final int GRANT_RUNTIME = 3;
548
549    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
550    private static final int GRANT_UPGRADE = 4;
551
552    /** Canonical intent used to identify what counts as a "web browser" app */
553    private static final Intent sBrowserIntent;
554    static {
555        sBrowserIntent = new Intent();
556        sBrowserIntent.setAction(Intent.ACTION_VIEW);
557        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
558        sBrowserIntent.setData(Uri.parse("http:"));
559    }
560
561    /**
562     * The set of all protected actions [i.e. those actions for which a high priority
563     * intent filter is disallowed].
564     */
565    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
566    static {
567        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
568        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
569        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
570        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
571    }
572
573    // Compilation reasons.
574    public static final int REASON_FIRST_BOOT = 0;
575    public static final int REASON_BOOT = 1;
576    public static final int REASON_INSTALL = 2;
577    public static final int REASON_BACKGROUND_DEXOPT = 3;
578    public static final int REASON_AB_OTA = 4;
579    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
580    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    /** The location for ASEC container files on internal storage. */
658    final String mAsecInternalPath;
659
660    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
661    // LOCK HELD.  Can be called with mInstallLock held.
662    @GuardedBy("mInstallLock")
663    final Installer mInstaller;
664
665    /** Directory where installed third-party apps stored */
666    final File mAppInstallDir;
667
668    /**
669     * Directory to which applications installed internally have their
670     * 32 bit native libraries copied.
671     */
672    private File mAppLib32InstallDir;
673
674    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
675    // apps.
676    final File mDrmAppPrivateInstallDir;
677
678    // ----------------------------------------------------------------
679
680    // Lock for state used when installing and doing other long running
681    // operations.  Methods that must be called with this lock held have
682    // the suffix "LI".
683    final Object mInstallLock = new Object();
684
685    // ----------------------------------------------------------------
686
687    // Keys are String (package name), values are Package.  This also serves
688    // as the lock for the global state.  Methods that must be called with
689    // this lock held have the prefix "LP".
690    @GuardedBy("mPackages")
691    final ArrayMap<String, PackageParser.Package> mPackages =
692            new ArrayMap<String, PackageParser.Package>();
693
694    final ArrayMap<String, Set<String>> mKnownCodebase =
695            new ArrayMap<String, Set<String>>();
696
697    // Keys are isolated uids and values are the uid of the application
698    // that created the isolated proccess.
699    @GuardedBy("mPackages")
700    final SparseIntArray mIsolatedOwners = new SparseIntArray();
701
702    /**
703     * Tracks new system packages [received in an OTA] that we expect to
704     * find updated user-installed versions. Keys are package name, values
705     * are package location.
706     */
707    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
708    /**
709     * Tracks high priority intent filters for protected actions. During boot, certain
710     * filter actions are protected and should never be allowed to have a high priority
711     * intent filter for them. However, there is one, and only one exception -- the
712     * setup wizard. It must be able to define a high priority intent filter for these
713     * actions to ensure there are no escapes from the wizard. We need to delay processing
714     * of these during boot as we need to look at all of the system packages in order
715     * to know which component is the setup wizard.
716     */
717    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
718    /**
719     * Whether or not processing protected filters should be deferred.
720     */
721    private boolean mDeferProtectedFilters = true;
722
723    /**
724     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
725     */
726    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
727    /**
728     * Whether or not system app permissions should be promoted from install to runtime.
729     */
730    boolean mPromoteSystemApps;
731
732    @GuardedBy("mPackages")
733    final Settings mSettings;
734
735    /**
736     * Set of package names that are currently "frozen", which means active
737     * surgery is being done on the code/data for that package. The platform
738     * will refuse to launch frozen packages to avoid race conditions.
739     *
740     * @see PackageFreezer
741     */
742    @GuardedBy("mPackages")
743    final ArraySet<String> mFrozenPackages = new ArraySet<>();
744
745    final ProtectedPackages mProtectedPackages;
746
747    @GuardedBy("mLoadedVolumes")
748    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
749
750    boolean mFirstBoot;
751
752    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
753
754    // System configuration read by SystemConfig.
755    final int[] mGlobalGids;
756    final SparseArray<ArraySet<String>> mSystemPermissions;
757    @GuardedBy("mAvailableFeatures")
758    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
759
760    // If mac_permissions.xml was found for seinfo labeling.
761    boolean mFoundPolicyFile;
762
763    private final InstantAppRegistry mInstantAppRegistry;
764
765    @GuardedBy("mPackages")
766    int mChangedPackagesSequenceNumber;
767    /**
768     * List of changed [installed, removed or updated] packages.
769     * mapping from user id -> sequence number -> package name
770     */
771    @GuardedBy("mPackages")
772    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
773    /**
774     * The sequence number of the last change to a package.
775     * mapping from user id -> package name -> sequence number
776     */
777    @GuardedBy("mPackages")
778    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
779
780    class PackageParserCallback implements PackageParser.Callback {
781        @Override public final boolean hasFeature(String feature) {
782            return PackageManagerService.this.hasSystemFeature(feature, 0);
783        }
784
785        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
786                Collection<PackageParser.Package> allPackages, String targetPackageName) {
787            List<PackageParser.Package> overlayPackages = null;
788            for (PackageParser.Package p : allPackages) {
789                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
790                    if (overlayPackages == null) {
791                        overlayPackages = new ArrayList<PackageParser.Package>();
792                    }
793                    overlayPackages.add(p);
794                }
795            }
796            if (overlayPackages != null) {
797                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
798                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
799                        return p1.mOverlayPriority - p2.mOverlayPriority;
800                    }
801                };
802                Collections.sort(overlayPackages, cmp);
803            }
804            return overlayPackages;
805        }
806
807        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
808                String targetPackageName, String targetPath) {
809            if ("android".equals(targetPackageName)) {
810                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
811                // native AssetManager.
812                return null;
813            }
814            List<PackageParser.Package> overlayPackages =
815                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
816            if (overlayPackages == null || overlayPackages.isEmpty()) {
817                return null;
818            }
819            List<String> overlayPathList = null;
820            for (PackageParser.Package overlayPackage : overlayPackages) {
821                if (targetPath == null) {
822                    if (overlayPathList == null) {
823                        overlayPathList = new ArrayList<String>();
824                    }
825                    overlayPathList.add(overlayPackage.baseCodePath);
826                    continue;
827                }
828
829                try {
830                    // Creates idmaps for system to parse correctly the Android manifest of the
831                    // target package.
832                    //
833                    // OverlayManagerService will update each of them with a correct gid from its
834                    // target package app id.
835                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
836                            UserHandle.getSharedAppGid(
837                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
838                    if (overlayPathList == null) {
839                        overlayPathList = new ArrayList<String>();
840                    }
841                    overlayPathList.add(overlayPackage.baseCodePath);
842                } catch (InstallerException e) {
843                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
844                            overlayPackage.baseCodePath);
845                }
846            }
847            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
848        }
849
850        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
851            synchronized (mPackages) {
852                return getStaticOverlayPathsLocked(
853                        mPackages.values(), targetPackageName, targetPath);
854            }
855        }
856
857        @Override public final String[] getOverlayApks(String targetPackageName) {
858            return getStaticOverlayPaths(targetPackageName, null);
859        }
860
861        @Override public final String[] getOverlayPaths(String targetPackageName,
862                String targetPath) {
863            return getStaticOverlayPaths(targetPackageName, targetPath);
864        }
865    };
866
867    class ParallelPackageParserCallback extends PackageParserCallback {
868        List<PackageParser.Package> mOverlayPackages = null;
869
870        void findStaticOverlayPackages() {
871            synchronized (mPackages) {
872                for (PackageParser.Package p : mPackages.values()) {
873                    if (p.mIsStaticOverlay) {
874                        if (mOverlayPackages == null) {
875                            mOverlayPackages = new ArrayList<PackageParser.Package>();
876                        }
877                        mOverlayPackages.add(p);
878                    }
879                }
880            }
881        }
882
883        @Override
884        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
885            // We can trust mOverlayPackages without holding mPackages because package uninstall
886            // can't happen while running parallel parsing.
887            // Moreover holding mPackages on each parsing thread causes dead-lock.
888            return mOverlayPackages == null ? null :
889                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
890        }
891    }
892
893    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
894    final ParallelPackageParserCallback mParallelPackageParserCallback =
895            new ParallelPackageParserCallback();
896
897    public static final class SharedLibraryEntry {
898        public final @Nullable String path;
899        public final @Nullable String apk;
900        public final @NonNull SharedLibraryInfo info;
901
902        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
903                String declaringPackageName, int declaringPackageVersionCode) {
904            path = _path;
905            apk = _apk;
906            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
907                    declaringPackageName, declaringPackageVersionCode), null);
908        }
909    }
910
911    // Currently known shared libraries.
912    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
913    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
914            new ArrayMap<>();
915
916    // All available activities, for your resolving pleasure.
917    final ActivityIntentResolver mActivities =
918            new ActivityIntentResolver();
919
920    // All available receivers, for your resolving pleasure.
921    final ActivityIntentResolver mReceivers =
922            new ActivityIntentResolver();
923
924    // All available services, for your resolving pleasure.
925    final ServiceIntentResolver mServices = new ServiceIntentResolver();
926
927    // All available providers, for your resolving pleasure.
928    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
929
930    // Mapping from provider base names (first directory in content URI codePath)
931    // to the provider information.
932    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
933            new ArrayMap<String, PackageParser.Provider>();
934
935    // Mapping from instrumentation class names to info about them.
936    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
937            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
938
939    // Mapping from permission names to info about them.
940    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
941            new ArrayMap<String, PackageParser.PermissionGroup>();
942
943    // Packages whose data we have transfered into another package, thus
944    // should no longer exist.
945    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
946
947    // Broadcast actions that are only available to the system.
948    @GuardedBy("mProtectedBroadcasts")
949    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
950
951    /** List of packages waiting for verification. */
952    final SparseArray<PackageVerificationState> mPendingVerification
953            = new SparseArray<PackageVerificationState>();
954
955    /** Set of packages associated with each app op permission. */
956    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
957
958    final PackageInstallerService mInstallerService;
959
960    private final PackageDexOptimizer mPackageDexOptimizer;
961    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
962    // is used by other apps).
963    private final DexManager mDexManager;
964
965    private AtomicInteger mNextMoveId = new AtomicInteger();
966    private final MoveCallbacks mMoveCallbacks;
967
968    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
969
970    // Cache of users who need badging.
971    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
972
973    /** Token for keys in mPendingVerification. */
974    private int mPendingVerificationToken = 0;
975
976    volatile boolean mSystemReady;
977    volatile boolean mSafeMode;
978    volatile boolean mHasSystemUidErrors;
979    private volatile boolean mEphemeralAppsDisabled;
980
981    ApplicationInfo mAndroidApplication;
982    final ActivityInfo mResolveActivity = new ActivityInfo();
983    final ResolveInfo mResolveInfo = new ResolveInfo();
984    ComponentName mResolveComponentName;
985    PackageParser.Package mPlatformPackage;
986    ComponentName mCustomResolverComponentName;
987
988    boolean mResolverReplaced = false;
989
990    private final @Nullable ComponentName mIntentFilterVerifierComponent;
991    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
992
993    private int mIntentFilterVerificationToken = 0;
994
995    /** The service connection to the ephemeral resolver */
996    final EphemeralResolverConnection mInstantAppResolverConnection;
997    /** Component used to show resolver settings for Instant Apps */
998    final ComponentName mInstantAppResolverSettingsComponent;
999
1000    /** Activity used to install instant applications */
1001    ActivityInfo mInstantAppInstallerActivity;
1002    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1003
1004    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1005            = new SparseArray<IntentFilterVerificationState>();
1006
1007    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1008
1009    // List of packages names to keep cached, even if they are uninstalled for all users
1010    private List<String> mKeepUninstalledPackages;
1011
1012    private UserManagerInternal mUserManagerInternal;
1013
1014    private DeviceIdleController.LocalService mDeviceIdleController;
1015
1016    private File mCacheDir;
1017
1018    private ArraySet<String> mPrivappPermissionsViolations;
1019
1020    private Future<?> mPrepareAppDataFuture;
1021
1022    private static class IFVerificationParams {
1023        PackageParser.Package pkg;
1024        boolean replacing;
1025        int userId;
1026        int verifierUid;
1027
1028        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1029                int _userId, int _verifierUid) {
1030            pkg = _pkg;
1031            replacing = _replacing;
1032            userId = _userId;
1033            replacing = _replacing;
1034            verifierUid = _verifierUid;
1035        }
1036    }
1037
1038    private interface IntentFilterVerifier<T extends IntentFilter> {
1039        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1040                                               T filter, String packageName);
1041        void startVerifications(int userId);
1042        void receiveVerificationResponse(int verificationId);
1043    }
1044
1045    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1046        private Context mContext;
1047        private ComponentName mIntentFilterVerifierComponent;
1048        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1049
1050        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1051            mContext = context;
1052            mIntentFilterVerifierComponent = verifierComponent;
1053        }
1054
1055        private String getDefaultScheme() {
1056            return IntentFilter.SCHEME_HTTPS;
1057        }
1058
1059        @Override
1060        public void startVerifications(int userId) {
1061            // Launch verifications requests
1062            int count = mCurrentIntentFilterVerifications.size();
1063            for (int n=0; n<count; n++) {
1064                int verificationId = mCurrentIntentFilterVerifications.get(n);
1065                final IntentFilterVerificationState ivs =
1066                        mIntentFilterVerificationStates.get(verificationId);
1067
1068                String packageName = ivs.getPackageName();
1069
1070                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1071                final int filterCount = filters.size();
1072                ArraySet<String> domainsSet = new ArraySet<>();
1073                for (int m=0; m<filterCount; m++) {
1074                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1075                    domainsSet.addAll(filter.getHostsList());
1076                }
1077                synchronized (mPackages) {
1078                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1079                            packageName, domainsSet) != null) {
1080                        scheduleWriteSettingsLocked();
1081                    }
1082                }
1083                sendVerificationRequest(verificationId, ivs);
1084            }
1085            mCurrentIntentFilterVerifications.clear();
1086        }
1087
1088        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1089            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1092                    verificationId);
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1095                    getDefaultScheme());
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1098                    ivs.getHostsString());
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1101                    ivs.getPackageName());
1102            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1103            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1104
1105            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1106            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1107                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1108                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1109
1110            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1111            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1112                    "Sending IntentFilter verification broadcast");
1113        }
1114
1115        public void receiveVerificationResponse(int verificationId) {
1116            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1117
1118            final boolean verified = ivs.isVerified();
1119
1120            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1121            final int count = filters.size();
1122            if (DEBUG_DOMAIN_VERIFICATION) {
1123                Slog.i(TAG, "Received verification response " + verificationId
1124                        + " for " + count + " filters, verified=" + verified);
1125            }
1126            for (int n=0; n<count; n++) {
1127                PackageParser.ActivityIntentInfo filter = filters.get(n);
1128                filter.setVerified(verified);
1129
1130                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1131                        + " verified with result:" + verified + " and hosts:"
1132                        + ivs.getHostsString());
1133            }
1134
1135            mIntentFilterVerificationStates.remove(verificationId);
1136
1137            final String packageName = ivs.getPackageName();
1138            IntentFilterVerificationInfo ivi = null;
1139
1140            synchronized (mPackages) {
1141                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1142            }
1143            if (ivi == null) {
1144                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1145                        + verificationId + " packageName:" + packageName);
1146                return;
1147            }
1148            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1149                    "Updating IntentFilterVerificationInfo for package " + packageName
1150                            +" verificationId:" + verificationId);
1151
1152            synchronized (mPackages) {
1153                if (verified) {
1154                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1155                } else {
1156                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1157                }
1158                scheduleWriteSettingsLocked();
1159
1160                final int userId = ivs.getUserId();
1161                if (userId != UserHandle.USER_ALL) {
1162                    final int userStatus =
1163                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1164
1165                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1166                    boolean needUpdate = false;
1167
1168                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1169                    // already been set by the User thru the Disambiguation dialog
1170                    switch (userStatus) {
1171                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1172                            if (verified) {
1173                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1174                            } else {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1176                            }
1177                            needUpdate = true;
1178                            break;
1179
1180                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1181                            if (verified) {
1182                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1183                                needUpdate = true;
1184                            }
1185                            break;
1186
1187                        default:
1188                            // Nothing to do
1189                    }
1190
1191                    if (needUpdate) {
1192                        mSettings.updateIntentFilterVerificationStatusLPw(
1193                                packageName, updatedStatus, userId);
1194                        scheduleWritePackageRestrictionsLocked(userId);
1195                    }
1196                }
1197            }
1198        }
1199
1200        @Override
1201        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1202                    ActivityIntentInfo filter, String packageName) {
1203            if (!hasValidDomains(filter)) {
1204                return false;
1205            }
1206            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1207            if (ivs == null) {
1208                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1209                        packageName);
1210            }
1211            if (DEBUG_DOMAIN_VERIFICATION) {
1212                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1213            }
1214            ivs.addFilter(filter);
1215            return true;
1216        }
1217
1218        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1219                int userId, int verificationId, String packageName) {
1220            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1221                    verifierUid, userId, packageName);
1222            ivs.setPendingState();
1223            synchronized (mPackages) {
1224                mIntentFilterVerificationStates.append(verificationId, ivs);
1225                mCurrentIntentFilterVerifications.add(verificationId);
1226            }
1227            return ivs;
1228        }
1229    }
1230
1231    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1232        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1233                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1234                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1235    }
1236
1237    // Set of pending broadcasts for aggregating enable/disable of components.
1238    static class PendingPackageBroadcasts {
1239        // for each user id, a map of <package name -> components within that package>
1240        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1241
1242        public PendingPackageBroadcasts() {
1243            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1244        }
1245
1246        public ArrayList<String> get(int userId, String packageName) {
1247            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1248            return packages.get(packageName);
1249        }
1250
1251        public void put(int userId, String packageName, ArrayList<String> components) {
1252            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253            packages.put(packageName, components);
1254        }
1255
1256        public void remove(int userId, String packageName) {
1257            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1258            if (packages != null) {
1259                packages.remove(packageName);
1260            }
1261        }
1262
1263        public void remove(int userId) {
1264            mUidMap.remove(userId);
1265        }
1266
1267        public int userIdCount() {
1268            return mUidMap.size();
1269        }
1270
1271        public int userIdAt(int n) {
1272            return mUidMap.keyAt(n);
1273        }
1274
1275        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1276            return mUidMap.get(userId);
1277        }
1278
1279        public int size() {
1280            // total number of pending broadcast entries across all userIds
1281            int num = 0;
1282            for (int i = 0; i< mUidMap.size(); i++) {
1283                num += mUidMap.valueAt(i).size();
1284            }
1285            return num;
1286        }
1287
1288        public void clear() {
1289            mUidMap.clear();
1290        }
1291
1292        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1293            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1294            if (map == null) {
1295                map = new ArrayMap<String, ArrayList<String>>();
1296                mUidMap.put(userId, map);
1297            }
1298            return map;
1299        }
1300    }
1301    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1302
1303    // Service Connection to remote media container service to copy
1304    // package uri's from external media onto secure containers
1305    // or internal storage.
1306    private IMediaContainerService mContainerService = null;
1307
1308    static final int SEND_PENDING_BROADCAST = 1;
1309    static final int MCS_BOUND = 3;
1310    static final int END_COPY = 4;
1311    static final int INIT_COPY = 5;
1312    static final int MCS_UNBIND = 6;
1313    static final int START_CLEANING_PACKAGE = 7;
1314    static final int FIND_INSTALL_LOC = 8;
1315    static final int POST_INSTALL = 9;
1316    static final int MCS_RECONNECT = 10;
1317    static final int MCS_GIVE_UP = 11;
1318    static final int UPDATED_MEDIA_STATUS = 12;
1319    static final int WRITE_SETTINGS = 13;
1320    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1321    static final int PACKAGE_VERIFIED = 15;
1322    static final int CHECK_PENDING_VERIFICATION = 16;
1323    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1324    static final int INTENT_FILTER_VERIFIED = 18;
1325    static final int WRITE_PACKAGE_LIST = 19;
1326    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1327
1328    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1329
1330    // Delay time in millisecs
1331    static final int BROADCAST_DELAY = 10 * 1000;
1332
1333    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1334            2 * 60 * 60 * 1000L; /* two hours */
1335
1336    static UserManagerService sUserManager;
1337
1338    // Stores a list of users whose package restrictions file needs to be updated
1339    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1340
1341    final private DefaultContainerConnection mDefContainerConn =
1342            new DefaultContainerConnection();
1343    class DefaultContainerConnection implements ServiceConnection {
1344        public void onServiceConnected(ComponentName name, IBinder service) {
1345            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1346            final IMediaContainerService imcs = IMediaContainerService.Stub
1347                    .asInterface(Binder.allowBlocking(service));
1348            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1349        }
1350
1351        public void onServiceDisconnected(ComponentName name) {
1352            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1353        }
1354    }
1355
1356    // Recordkeeping of restore-after-install operations that are currently in flight
1357    // between the Package Manager and the Backup Manager
1358    static class PostInstallData {
1359        public InstallArgs args;
1360        public PackageInstalledInfo res;
1361
1362        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1363            args = _a;
1364            res = _r;
1365        }
1366    }
1367
1368    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1369    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1370
1371    // XML tags for backup/restore of various bits of state
1372    private static final String TAG_PREFERRED_BACKUP = "pa";
1373    private static final String TAG_DEFAULT_APPS = "da";
1374    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1375
1376    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1377    private static final String TAG_ALL_GRANTS = "rt-grants";
1378    private static final String TAG_GRANT = "grant";
1379    private static final String ATTR_PACKAGE_NAME = "pkg";
1380
1381    private static final String TAG_PERMISSION = "perm";
1382    private static final String ATTR_PERMISSION_NAME = "name";
1383    private static final String ATTR_IS_GRANTED = "g";
1384    private static final String ATTR_USER_SET = "set";
1385    private static final String ATTR_USER_FIXED = "fixed";
1386    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1387
1388    // System/policy permission grants are not backed up
1389    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1390            FLAG_PERMISSION_POLICY_FIXED
1391            | FLAG_PERMISSION_SYSTEM_FIXED
1392            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1393
1394    // And we back up these user-adjusted states
1395    private static final int USER_RUNTIME_GRANT_MASK =
1396            FLAG_PERMISSION_USER_SET
1397            | FLAG_PERMISSION_USER_FIXED
1398            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1399
1400    final @Nullable String mRequiredVerifierPackage;
1401    final @NonNull String mRequiredInstallerPackage;
1402    final @NonNull String mRequiredUninstallerPackage;
1403    final @Nullable String mSetupWizardPackage;
1404    final @Nullable String mStorageManagerPackage;
1405    final @NonNull String mServicesSystemSharedLibraryPackageName;
1406    final @NonNull String mSharedSystemSharedLibraryPackageName;
1407
1408    final boolean mPermissionReviewRequired;
1409
1410    private final PackageUsage mPackageUsage = new PackageUsage();
1411    private final CompilerStats mCompilerStats = new CompilerStats();
1412
1413    class PackageHandler extends Handler {
1414        private boolean mBound = false;
1415        final ArrayList<HandlerParams> mPendingInstalls =
1416            new ArrayList<HandlerParams>();
1417
1418        private boolean connectToService() {
1419            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1420                    " DefaultContainerService");
1421            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1424                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1425                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426                mBound = true;
1427                return true;
1428            }
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430            return false;
1431        }
1432
1433        private void disconnectService() {
1434            mContainerService = null;
1435            mBound = false;
1436            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1437            mContext.unbindService(mDefContainerConn);
1438            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1439        }
1440
1441        PackageHandler(Looper looper) {
1442            super(looper);
1443        }
1444
1445        public void handleMessage(Message msg) {
1446            try {
1447                doHandleMessage(msg);
1448            } finally {
1449                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1450            }
1451        }
1452
1453        void doHandleMessage(Message msg) {
1454            switch (msg.what) {
1455                case INIT_COPY: {
1456                    HandlerParams params = (HandlerParams) msg.obj;
1457                    int idx = mPendingInstalls.size();
1458                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1459                    // If a bind was already initiated we dont really
1460                    // need to do anything. The pending install
1461                    // will be processed later on.
1462                    if (!mBound) {
1463                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1464                                System.identityHashCode(mHandler));
1465                        // If this is the only one pending we might
1466                        // have to bind to the service again.
1467                        if (!connectToService()) {
1468                            Slog.e(TAG, "Failed to bind to media container service");
1469                            params.serviceError();
1470                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1471                                    System.identityHashCode(mHandler));
1472                            if (params.traceMethod != null) {
1473                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1474                                        params.traceCookie);
1475                            }
1476                            return;
1477                        } else {
1478                            // Once we bind to the service, the first
1479                            // pending request will be processed.
1480                            mPendingInstalls.add(idx, params);
1481                        }
1482                    } else {
1483                        mPendingInstalls.add(idx, params);
1484                        // Already bound to the service. Just make
1485                        // sure we trigger off processing the first request.
1486                        if (idx == 0) {
1487                            mHandler.sendEmptyMessage(MCS_BOUND);
1488                        }
1489                    }
1490                    break;
1491                }
1492                case MCS_BOUND: {
1493                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1494                    if (msg.obj != null) {
1495                        mContainerService = (IMediaContainerService) msg.obj;
1496                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1497                                System.identityHashCode(mHandler));
1498                    }
1499                    if (mContainerService == null) {
1500                        if (!mBound) {
1501                            // Something seriously wrong since we are not bound and we are not
1502                            // waiting for connection. Bail out.
1503                            Slog.e(TAG, "Cannot bind to media container service");
1504                            for (HandlerParams params : mPendingInstalls) {
1505                                // Indicate service bind error
1506                                params.serviceError();
1507                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1508                                        System.identityHashCode(params));
1509                                if (params.traceMethod != null) {
1510                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1511                                            params.traceMethod, params.traceCookie);
1512                                }
1513                                return;
1514                            }
1515                            mPendingInstalls.clear();
1516                        } else {
1517                            Slog.w(TAG, "Waiting to connect to media container service");
1518                        }
1519                    } else if (mPendingInstalls.size() > 0) {
1520                        HandlerParams params = mPendingInstalls.get(0);
1521                        if (params != null) {
1522                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1523                                    System.identityHashCode(params));
1524                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1525                            if (params.startCopy()) {
1526                                // We are done...  look for more work or to
1527                                // go idle.
1528                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1529                                        "Checking for more work or unbind...");
1530                                // Delete pending install
1531                                if (mPendingInstalls.size() > 0) {
1532                                    mPendingInstalls.remove(0);
1533                                }
1534                                if (mPendingInstalls.size() == 0) {
1535                                    if (mBound) {
1536                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1537                                                "Posting delayed MCS_UNBIND");
1538                                        removeMessages(MCS_UNBIND);
1539                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1540                                        // Unbind after a little delay, to avoid
1541                                        // continual thrashing.
1542                                        sendMessageDelayed(ubmsg, 10000);
1543                                    }
1544                                } else {
1545                                    // There are more pending requests in queue.
1546                                    // Just post MCS_BOUND message to trigger processing
1547                                    // of next pending install.
1548                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1549                                            "Posting MCS_BOUND for next work");
1550                                    mHandler.sendEmptyMessage(MCS_BOUND);
1551                                }
1552                            }
1553                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1554                        }
1555                    } else {
1556                        // Should never happen ideally.
1557                        Slog.w(TAG, "Empty queue");
1558                    }
1559                    break;
1560                }
1561                case MCS_RECONNECT: {
1562                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1563                    if (mPendingInstalls.size() > 0) {
1564                        if (mBound) {
1565                            disconnectService();
1566                        }
1567                        if (!connectToService()) {
1568                            Slog.e(TAG, "Failed to bind to media container service");
1569                            for (HandlerParams params : mPendingInstalls) {
1570                                // Indicate service bind error
1571                                params.serviceError();
1572                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1573                                        System.identityHashCode(params));
1574                            }
1575                            mPendingInstalls.clear();
1576                        }
1577                    }
1578                    break;
1579                }
1580                case MCS_UNBIND: {
1581                    // If there is no actual work left, then time to unbind.
1582                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1583
1584                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1585                        if (mBound) {
1586                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1587
1588                            disconnectService();
1589                        }
1590                    } else if (mPendingInstalls.size() > 0) {
1591                        // There are more pending requests in queue.
1592                        // Just post MCS_BOUND message to trigger processing
1593                        // of next pending install.
1594                        mHandler.sendEmptyMessage(MCS_BOUND);
1595                    }
1596
1597                    break;
1598                }
1599                case MCS_GIVE_UP: {
1600                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1601                    HandlerParams params = mPendingInstalls.remove(0);
1602                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1603                            System.identityHashCode(params));
1604                    break;
1605                }
1606                case SEND_PENDING_BROADCAST: {
1607                    String packages[];
1608                    ArrayList<String> components[];
1609                    int size = 0;
1610                    int uids[];
1611                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1612                    synchronized (mPackages) {
1613                        if (mPendingBroadcasts == null) {
1614                            return;
1615                        }
1616                        size = mPendingBroadcasts.size();
1617                        if (size <= 0) {
1618                            // Nothing to be done. Just return
1619                            return;
1620                        }
1621                        packages = new String[size];
1622                        components = new ArrayList[size];
1623                        uids = new int[size];
1624                        int i = 0;  // filling out the above arrays
1625
1626                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1627                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1628                            Iterator<Map.Entry<String, ArrayList<String>>> it
1629                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1630                                            .entrySet().iterator();
1631                            while (it.hasNext() && i < size) {
1632                                Map.Entry<String, ArrayList<String>> ent = it.next();
1633                                packages[i] = ent.getKey();
1634                                components[i] = ent.getValue();
1635                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1636                                uids[i] = (ps != null)
1637                                        ? UserHandle.getUid(packageUserId, ps.appId)
1638                                        : -1;
1639                                i++;
1640                            }
1641                        }
1642                        size = i;
1643                        mPendingBroadcasts.clear();
1644                    }
1645                    // Send broadcasts
1646                    for (int i = 0; i < size; i++) {
1647                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1648                    }
1649                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1650                    break;
1651                }
1652                case START_CLEANING_PACKAGE: {
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1654                    final String packageName = (String)msg.obj;
1655                    final int userId = msg.arg1;
1656                    final boolean andCode = msg.arg2 != 0;
1657                    synchronized (mPackages) {
1658                        if (userId == UserHandle.USER_ALL) {
1659                            int[] users = sUserManager.getUserIds();
1660                            for (int user : users) {
1661                                mSettings.addPackageToCleanLPw(
1662                                        new PackageCleanItem(user, packageName, andCode));
1663                            }
1664                        } else {
1665                            mSettings.addPackageToCleanLPw(
1666                                    new PackageCleanItem(userId, packageName, andCode));
1667                        }
1668                    }
1669                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1670                    startCleaningPackages();
1671                } break;
1672                case POST_INSTALL: {
1673                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1674
1675                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1676                    final boolean didRestore = (msg.arg2 != 0);
1677                    mRunningInstalls.delete(msg.arg1);
1678
1679                    if (data != null) {
1680                        InstallArgs args = data.args;
1681                        PackageInstalledInfo parentRes = data.res;
1682
1683                        final boolean grantPermissions = (args.installFlags
1684                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1685                        final boolean killApp = (args.installFlags
1686                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1687                        final boolean virtualPreload = ((args.installFlags
1688                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1689                        final String[] grantedPermissions = args.installGrantPermissions;
1690
1691                        // Handle the parent package
1692                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1693                                virtualPreload, grantedPermissions, didRestore,
1694                                args.installerPackageName, args.observer);
1695
1696                        // Handle the child packages
1697                        final int childCount = (parentRes.addedChildPackages != null)
1698                                ? parentRes.addedChildPackages.size() : 0;
1699                        for (int i = 0; i < childCount; i++) {
1700                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1701                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1702                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1703                                    args.installerPackageName, args.observer);
1704                        }
1705
1706                        // Log tracing if needed
1707                        if (args.traceMethod != null) {
1708                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1709                                    args.traceCookie);
1710                        }
1711                    } else {
1712                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1713                    }
1714
1715                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1716                } break;
1717                case UPDATED_MEDIA_STATUS: {
1718                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1719                    boolean reportStatus = msg.arg1 == 1;
1720                    boolean doGc = msg.arg2 == 1;
1721                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1722                    if (doGc) {
1723                        // Force a gc to clear up stale containers.
1724                        Runtime.getRuntime().gc();
1725                    }
1726                    if (msg.obj != null) {
1727                        @SuppressWarnings("unchecked")
1728                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1729                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1730                        // Unload containers
1731                        unloadAllContainers(args);
1732                    }
1733                    if (reportStatus) {
1734                        try {
1735                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1736                                    "Invoking StorageManagerService call back");
1737                            PackageHelper.getStorageManager().finishMediaUpdate();
1738                        } catch (RemoteException e) {
1739                            Log.e(TAG, "StorageManagerService not running?");
1740                        }
1741                    }
1742                } break;
1743                case WRITE_SETTINGS: {
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1745                    synchronized (mPackages) {
1746                        removeMessages(WRITE_SETTINGS);
1747                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1748                        mSettings.writeLPr();
1749                        mDirtyUsers.clear();
1750                    }
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1752                } break;
1753                case WRITE_PACKAGE_RESTRICTIONS: {
1754                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1755                    synchronized (mPackages) {
1756                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1757                        for (int userId : mDirtyUsers) {
1758                            mSettings.writePackageRestrictionsLPr(userId);
1759                        }
1760                        mDirtyUsers.clear();
1761                    }
1762                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1763                } break;
1764                case WRITE_PACKAGE_LIST: {
1765                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1766                    synchronized (mPackages) {
1767                        removeMessages(WRITE_PACKAGE_LIST);
1768                        mSettings.writePackageListLPr(msg.arg1);
1769                    }
1770                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1771                } break;
1772                case CHECK_PENDING_VERIFICATION: {
1773                    final int verificationId = msg.arg1;
1774                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1775
1776                    if ((state != null) && !state.timeoutExtended()) {
1777                        final InstallArgs args = state.getInstallArgs();
1778                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1779
1780                        Slog.i(TAG, "Verification timed out for " + originUri);
1781                        mPendingVerification.remove(verificationId);
1782
1783                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1784
1785                        final UserHandle user = args.getUser();
1786                        if (getDefaultVerificationResponse(user)
1787                                == PackageManager.VERIFICATION_ALLOW) {
1788                            Slog.i(TAG, "Continuing with installation of " + originUri);
1789                            state.setVerifierResponse(Binder.getCallingUid(),
1790                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1791                            broadcastPackageVerified(verificationId, originUri,
1792                                    PackageManager.VERIFICATION_ALLOW, user);
1793                            try {
1794                                ret = args.copyApk(mContainerService, true);
1795                            } catch (RemoteException e) {
1796                                Slog.e(TAG, "Could not contact the ContainerService");
1797                            }
1798                        } else {
1799                            broadcastPackageVerified(verificationId, originUri,
1800                                    PackageManager.VERIFICATION_REJECT, user);
1801                        }
1802
1803                        Trace.asyncTraceEnd(
1804                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1805
1806                        processPendingInstall(args, ret);
1807                        mHandler.sendEmptyMessage(MCS_UNBIND);
1808                    }
1809                    break;
1810                }
1811                case PACKAGE_VERIFIED: {
1812                    final int verificationId = msg.arg1;
1813
1814                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1815                    if (state == null) {
1816                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1817                        break;
1818                    }
1819
1820                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1821
1822                    state.setVerifierResponse(response.callerUid, response.code);
1823
1824                    if (state.isVerificationComplete()) {
1825                        mPendingVerification.remove(verificationId);
1826
1827                        final InstallArgs args = state.getInstallArgs();
1828                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1829
1830                        int ret;
1831                        if (state.isInstallAllowed()) {
1832                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1833                            broadcastPackageVerified(verificationId, originUri,
1834                                    response.code, state.getInstallArgs().getUser());
1835                            try {
1836                                ret = args.copyApk(mContainerService, true);
1837                            } catch (RemoteException e) {
1838                                Slog.e(TAG, "Could not contact the ContainerService");
1839                            }
1840                        } else {
1841                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1842                        }
1843
1844                        Trace.asyncTraceEnd(
1845                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1846
1847                        processPendingInstall(args, ret);
1848                        mHandler.sendEmptyMessage(MCS_UNBIND);
1849                    }
1850
1851                    break;
1852                }
1853                case START_INTENT_FILTER_VERIFICATIONS: {
1854                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1855                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1856                            params.replacing, params.pkg);
1857                    break;
1858                }
1859                case INTENT_FILTER_VERIFIED: {
1860                    final int verificationId = msg.arg1;
1861
1862                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1863                            verificationId);
1864                    if (state == null) {
1865                        Slog.w(TAG, "Invalid IntentFilter verification token "
1866                                + verificationId + " received");
1867                        break;
1868                    }
1869
1870                    final int userId = state.getUserId();
1871
1872                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1873                            "Processing IntentFilter verification with token:"
1874                            + verificationId + " and userId:" + userId);
1875
1876                    final IntentFilterVerificationResponse response =
1877                            (IntentFilterVerificationResponse) msg.obj;
1878
1879                    state.setVerifierResponse(response.callerUid, response.code);
1880
1881                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1882                            "IntentFilter verification with token:" + verificationId
1883                            + " and userId:" + userId
1884                            + " is settings verifier response with response code:"
1885                            + response.code);
1886
1887                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1888                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1889                                + response.getFailedDomainsString());
1890                    }
1891
1892                    if (state.isVerificationComplete()) {
1893                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1894                    } else {
1895                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1896                                "IntentFilter verification with token:" + verificationId
1897                                + " was not said to be complete");
1898                    }
1899
1900                    break;
1901                }
1902                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1903                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1904                            mInstantAppResolverConnection,
1905                            (InstantAppRequest) msg.obj,
1906                            mInstantAppInstallerActivity,
1907                            mHandler);
1908                }
1909            }
1910        }
1911    }
1912
1913    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1914            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1915            boolean launchedForRestore, String installerPackage,
1916            IPackageInstallObserver2 installObserver) {
1917        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1918            // Send the removed broadcasts
1919            if (res.removedInfo != null) {
1920                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1921            }
1922
1923            // Now that we successfully installed the package, grant runtime
1924            // permissions if requested before broadcasting the install. Also
1925            // for legacy apps in permission review mode we clear the permission
1926            // review flag which is used to emulate runtime permissions for
1927            // legacy apps.
1928            if (grantPermissions) {
1929                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1930            }
1931
1932            final boolean update = res.removedInfo != null
1933                    && res.removedInfo.removedPackage != null;
1934            final String installerPackageName =
1935                    res.installerPackageName != null
1936                            ? res.installerPackageName
1937                            : res.removedInfo != null
1938                                    ? res.removedInfo.installerPackageName
1939                                    : null;
1940
1941            // If this is the first time we have child packages for a disabled privileged
1942            // app that had no children, we grant requested runtime permissions to the new
1943            // children if the parent on the system image had them already granted.
1944            if (res.pkg.parentPackage != null) {
1945                synchronized (mPackages) {
1946                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1947                }
1948            }
1949
1950            synchronized (mPackages) {
1951                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1952            }
1953
1954            final String packageName = res.pkg.applicationInfo.packageName;
1955
1956            // Determine the set of users who are adding this package for
1957            // the first time vs. those who are seeing an update.
1958            int[] firstUsers = EMPTY_INT_ARRAY;
1959            int[] updateUsers = EMPTY_INT_ARRAY;
1960            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1961            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1962            for (int newUser : res.newUsers) {
1963                if (ps.getInstantApp(newUser)) {
1964                    continue;
1965                }
1966                if (allNewUsers) {
1967                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1968                    continue;
1969                }
1970                boolean isNew = true;
1971                for (int origUser : res.origUsers) {
1972                    if (origUser == newUser) {
1973                        isNew = false;
1974                        break;
1975                    }
1976                }
1977                if (isNew) {
1978                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1979                } else {
1980                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1981                }
1982            }
1983
1984            // Send installed broadcasts if the package is not a static shared lib.
1985            if (res.pkg.staticSharedLibName == null) {
1986                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1987
1988                // Send added for users that see the package for the first time
1989                // sendPackageAddedForNewUsers also deals with system apps
1990                int appId = UserHandle.getAppId(res.uid);
1991                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1992                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1993                        virtualPreload /*startReceiver*/, appId, firstUsers);
1994
1995                // Send added for users that don't see the package for the first time
1996                Bundle extras = new Bundle(1);
1997                extras.putInt(Intent.EXTRA_UID, res.uid);
1998                if (update) {
1999                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2000                }
2001                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2002                        extras, 0 /*flags*/,
2003                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2004                if (installerPackageName != null) {
2005                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2006                            extras, 0 /*flags*/,
2007                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2008                }
2009
2010                // Send replaced for users that don't see the package for the first time
2011                if (update) {
2012                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2013                            packageName, extras, 0 /*flags*/,
2014                            null /*targetPackage*/, null /*finishedReceiver*/,
2015                            updateUsers);
2016                    if (installerPackageName != null) {
2017                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2018                                extras, 0 /*flags*/,
2019                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2020                    }
2021                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2022                            null /*package*/, null /*extras*/, 0 /*flags*/,
2023                            packageName /*targetPackage*/,
2024                            null /*finishedReceiver*/, updateUsers);
2025                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2026                    // First-install and we did a restore, so we're responsible for the
2027                    // first-launch broadcast.
2028                    if (DEBUG_BACKUP) {
2029                        Slog.i(TAG, "Post-restore of " + packageName
2030                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2031                    }
2032                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2033                }
2034
2035                // Send broadcast package appeared if forward locked/external for all users
2036                // treat asec-hosted packages like removable media on upgrade
2037                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2038                    if (DEBUG_INSTALL) {
2039                        Slog.i(TAG, "upgrading pkg " + res.pkg
2040                                + " is ASEC-hosted -> AVAILABLE");
2041                    }
2042                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2043                    ArrayList<String> pkgList = new ArrayList<>(1);
2044                    pkgList.add(packageName);
2045                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2046                }
2047            }
2048
2049            // Work that needs to happen on first install within each user
2050            if (firstUsers != null && firstUsers.length > 0) {
2051                synchronized (mPackages) {
2052                    for (int userId : firstUsers) {
2053                        // If this app is a browser and it's newly-installed for some
2054                        // users, clear any default-browser state in those users. The
2055                        // app's nature doesn't depend on the user, so we can just check
2056                        // its browser nature in any user and generalize.
2057                        if (packageIsBrowser(packageName, userId)) {
2058                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2059                        }
2060
2061                        // We may also need to apply pending (restored) runtime
2062                        // permission grants within these users.
2063                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2064                    }
2065                }
2066            }
2067
2068            // Log current value of "unknown sources" setting
2069            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2070                    getUnknownSourcesSettings());
2071
2072            // Remove the replaced package's older resources safely now
2073            // We delete after a gc for applications  on sdcard.
2074            if (res.removedInfo != null && res.removedInfo.args != null) {
2075                Runtime.getRuntime().gc();
2076                synchronized (mInstallLock) {
2077                    res.removedInfo.args.doPostDeleteLI(true);
2078                }
2079            } else {
2080                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2081                // and not block here.
2082                VMRuntime.getRuntime().requestConcurrentGC();
2083            }
2084
2085            // Notify DexManager that the package was installed for new users.
2086            // The updated users should already be indexed and the package code paths
2087            // should not change.
2088            // Don't notify the manager for ephemeral apps as they are not expected to
2089            // survive long enough to benefit of background optimizations.
2090            for (int userId : firstUsers) {
2091                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2092                // There's a race currently where some install events may interleave with an uninstall.
2093                // This can lead to package info being null (b/36642664).
2094                if (info != null) {
2095                    mDexManager.notifyPackageInstalled(info, userId);
2096                }
2097            }
2098        }
2099
2100        // If someone is watching installs - notify them
2101        if (installObserver != null) {
2102            try {
2103                Bundle extras = extrasForInstallResult(res);
2104                installObserver.onPackageInstalled(res.name, res.returnCode,
2105                        res.returnMsg, extras);
2106            } catch (RemoteException e) {
2107                Slog.i(TAG, "Observer no longer exists.");
2108            }
2109        }
2110    }
2111
2112    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2113            PackageParser.Package pkg) {
2114        if (pkg.parentPackage == null) {
2115            return;
2116        }
2117        if (pkg.requestedPermissions == null) {
2118            return;
2119        }
2120        final PackageSetting disabledSysParentPs = mSettings
2121                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2122        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2123                || !disabledSysParentPs.isPrivileged()
2124                || (disabledSysParentPs.childPackageNames != null
2125                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2126            return;
2127        }
2128        final int[] allUserIds = sUserManager.getUserIds();
2129        final int permCount = pkg.requestedPermissions.size();
2130        for (int i = 0; i < permCount; i++) {
2131            String permission = pkg.requestedPermissions.get(i);
2132            BasePermission bp = mSettings.mPermissions.get(permission);
2133            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2134                continue;
2135            }
2136            for (int userId : allUserIds) {
2137                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2138                        permission, userId)) {
2139                    grantRuntimePermission(pkg.packageName, permission, userId);
2140                }
2141            }
2142        }
2143    }
2144
2145    private StorageEventListener mStorageListener = new StorageEventListener() {
2146        @Override
2147        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2148            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2149                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2150                    final String volumeUuid = vol.getFsUuid();
2151
2152                    // Clean up any users or apps that were removed or recreated
2153                    // while this volume was missing
2154                    sUserManager.reconcileUsers(volumeUuid);
2155                    reconcileApps(volumeUuid);
2156
2157                    // Clean up any install sessions that expired or were
2158                    // cancelled while this volume was missing
2159                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2160
2161                    loadPrivatePackages(vol);
2162
2163                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2164                    unloadPrivatePackages(vol);
2165                }
2166            }
2167
2168            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2169                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2170                    updateExternalMediaStatus(true, false);
2171                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2172                    updateExternalMediaStatus(false, false);
2173                }
2174            }
2175        }
2176
2177        @Override
2178        public void onVolumeForgotten(String fsUuid) {
2179            if (TextUtils.isEmpty(fsUuid)) {
2180                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2181                return;
2182            }
2183
2184            // Remove any apps installed on the forgotten volume
2185            synchronized (mPackages) {
2186                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2187                for (PackageSetting ps : packages) {
2188                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2189                    deletePackageVersioned(new VersionedPackage(ps.name,
2190                            PackageManager.VERSION_CODE_HIGHEST),
2191                            new LegacyPackageDeleteObserver(null).getBinder(),
2192                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2193                    // Try very hard to release any references to this package
2194                    // so we don't risk the system server being killed due to
2195                    // open FDs
2196                    AttributeCache.instance().removePackage(ps.name);
2197                }
2198
2199                mSettings.onVolumeForgotten(fsUuid);
2200                mSettings.writeLPr();
2201            }
2202        }
2203    };
2204
2205    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2206            String[] grantedPermissions) {
2207        for (int userId : userIds) {
2208            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2209        }
2210    }
2211
2212    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2213            String[] grantedPermissions) {
2214        PackageSetting ps = (PackageSetting) pkg.mExtras;
2215        if (ps == null) {
2216            return;
2217        }
2218
2219        PermissionsState permissionsState = ps.getPermissionsState();
2220
2221        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2222                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2223
2224        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2225                >= Build.VERSION_CODES.M;
2226
2227        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2228
2229        for (String permission : pkg.requestedPermissions) {
2230            final BasePermission bp;
2231            synchronized (mPackages) {
2232                bp = mSettings.mPermissions.get(permission);
2233            }
2234            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2235                    && (!instantApp || bp.isInstant())
2236                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2237                    && (grantedPermissions == null
2238                           || ArrayUtils.contains(grantedPermissions, permission))) {
2239                final int flags = permissionsState.getPermissionFlags(permission, userId);
2240                if (supportsRuntimePermissions) {
2241                    // Installer cannot change immutable permissions.
2242                    if ((flags & immutableFlags) == 0) {
2243                        grantRuntimePermission(pkg.packageName, permission, userId);
2244                    }
2245                } else if (mPermissionReviewRequired) {
2246                    // In permission review mode we clear the review flag when we
2247                    // are asked to install the app with all permissions granted.
2248                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2249                        updatePermissionFlags(permission, pkg.packageName,
2250                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2251                    }
2252                }
2253            }
2254        }
2255    }
2256
2257    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2258        Bundle extras = null;
2259        switch (res.returnCode) {
2260            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2261                extras = new Bundle();
2262                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2263                        res.origPermission);
2264                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2265                        res.origPackage);
2266                break;
2267            }
2268            case PackageManager.INSTALL_SUCCEEDED: {
2269                extras = new Bundle();
2270                extras.putBoolean(Intent.EXTRA_REPLACING,
2271                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2272                break;
2273            }
2274        }
2275        return extras;
2276    }
2277
2278    void scheduleWriteSettingsLocked() {
2279        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2280            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2281        }
2282    }
2283
2284    void scheduleWritePackageListLocked(int userId) {
2285        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2286            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2287            msg.arg1 = userId;
2288            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2289        }
2290    }
2291
2292    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2293        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2294        scheduleWritePackageRestrictionsLocked(userId);
2295    }
2296
2297    void scheduleWritePackageRestrictionsLocked(int userId) {
2298        final int[] userIds = (userId == UserHandle.USER_ALL)
2299                ? sUserManager.getUserIds() : new int[]{userId};
2300        for (int nextUserId : userIds) {
2301            if (!sUserManager.exists(nextUserId)) return;
2302            mDirtyUsers.add(nextUserId);
2303            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2304                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2305            }
2306        }
2307    }
2308
2309    public static PackageManagerService main(Context context, Installer installer,
2310            boolean factoryTest, boolean onlyCore) {
2311        // Self-check for initial settings.
2312        PackageManagerServiceCompilerMapping.checkProperties();
2313
2314        PackageManagerService m = new PackageManagerService(context, installer,
2315                factoryTest, onlyCore);
2316        m.enableSystemUserPackages();
2317        ServiceManager.addService("package", m);
2318        final PackageManagerNative pmn = m.new PackageManagerNative();
2319        ServiceManager.addService("package_native", pmn);
2320        return m;
2321    }
2322
2323    private void enableSystemUserPackages() {
2324        if (!UserManager.isSplitSystemUser()) {
2325            return;
2326        }
2327        // For system user, enable apps based on the following conditions:
2328        // - app is whitelisted or belong to one of these groups:
2329        //   -- system app which has no launcher icons
2330        //   -- system app which has INTERACT_ACROSS_USERS permission
2331        //   -- system IME app
2332        // - app is not in the blacklist
2333        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2334        Set<String> enableApps = new ArraySet<>();
2335        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2336                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2337                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2338        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2339        enableApps.addAll(wlApps);
2340        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2341                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2342        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2343        enableApps.removeAll(blApps);
2344        Log.i(TAG, "Applications installed for system user: " + enableApps);
2345        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2346                UserHandle.SYSTEM);
2347        final int allAppsSize = allAps.size();
2348        synchronized (mPackages) {
2349            for (int i = 0; i < allAppsSize; i++) {
2350                String pName = allAps.get(i);
2351                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2352                // Should not happen, but we shouldn't be failing if it does
2353                if (pkgSetting == null) {
2354                    continue;
2355                }
2356                boolean install = enableApps.contains(pName);
2357                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2358                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2359                            + " for system user");
2360                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2361                }
2362            }
2363            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2364        }
2365    }
2366
2367    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2368        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2369                Context.DISPLAY_SERVICE);
2370        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2371    }
2372
2373    /**
2374     * Requests that files preopted on a secondary system partition be copied to the data partition
2375     * if possible.  Note that the actual copying of the files is accomplished by init for security
2376     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2377     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2378     */
2379    private static void requestCopyPreoptedFiles() {
2380        final int WAIT_TIME_MS = 100;
2381        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2382        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2383            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2384            // We will wait for up to 100 seconds.
2385            final long timeStart = SystemClock.uptimeMillis();
2386            final long timeEnd = timeStart + 100 * 1000;
2387            long timeNow = timeStart;
2388            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2389                try {
2390                    Thread.sleep(WAIT_TIME_MS);
2391                } catch (InterruptedException e) {
2392                    // Do nothing
2393                }
2394                timeNow = SystemClock.uptimeMillis();
2395                if (timeNow > timeEnd) {
2396                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2397                    Slog.wtf(TAG, "cppreopt did not finish!");
2398                    break;
2399                }
2400            }
2401
2402            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2403        }
2404    }
2405
2406    public PackageManagerService(Context context, Installer installer,
2407            boolean factoryTest, boolean onlyCore) {
2408        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2409        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2410        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2411                SystemClock.uptimeMillis());
2412
2413        if (mSdkVersion <= 0) {
2414            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2415        }
2416
2417        mContext = context;
2418
2419        mPermissionReviewRequired = context.getResources().getBoolean(
2420                R.bool.config_permissionReviewRequired);
2421
2422        mFactoryTest = factoryTest;
2423        mOnlyCore = onlyCore;
2424        mMetrics = new DisplayMetrics();
2425        mSettings = new Settings(mPackages);
2426        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2427                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2428        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2429                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2430        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2431                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2432        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2433                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2434        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2435                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2436        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2437                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2438
2439        String separateProcesses = SystemProperties.get("debug.separate_processes");
2440        if (separateProcesses != null && separateProcesses.length() > 0) {
2441            if ("*".equals(separateProcesses)) {
2442                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2443                mSeparateProcesses = null;
2444                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2445            } else {
2446                mDefParseFlags = 0;
2447                mSeparateProcesses = separateProcesses.split(",");
2448                Slog.w(TAG, "Running with debug.separate_processes: "
2449                        + separateProcesses);
2450            }
2451        } else {
2452            mDefParseFlags = 0;
2453            mSeparateProcesses = null;
2454        }
2455
2456        mInstaller = installer;
2457        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2458                "*dexopt*");
2459        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2460        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2461
2462        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2463                FgThread.get().getLooper());
2464
2465        getDefaultDisplayMetrics(context, mMetrics);
2466
2467        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2468        SystemConfig systemConfig = SystemConfig.getInstance();
2469        mGlobalGids = systemConfig.getGlobalGids();
2470        mSystemPermissions = systemConfig.getSystemPermissions();
2471        mAvailableFeatures = systemConfig.getAvailableFeatures();
2472        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2473
2474        mProtectedPackages = new ProtectedPackages(mContext);
2475
2476        synchronized (mInstallLock) {
2477        // writer
2478        synchronized (mPackages) {
2479            mHandlerThread = new ServiceThread(TAG,
2480                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2481            mHandlerThread.start();
2482            mHandler = new PackageHandler(mHandlerThread.getLooper());
2483            mProcessLoggingHandler = new ProcessLoggingHandler();
2484            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2485
2486            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2487            mInstantAppRegistry = new InstantAppRegistry(this);
2488
2489            File dataDir = Environment.getDataDirectory();
2490            mAppInstallDir = new File(dataDir, "app");
2491            mAppLib32InstallDir = new File(dataDir, "app-lib");
2492            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2493            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2494            sUserManager = new UserManagerService(context, this,
2495                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2496
2497            // Propagate permission configuration in to package manager.
2498            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2499                    = systemConfig.getPermissions();
2500            for (int i=0; i<permConfig.size(); i++) {
2501                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2502                BasePermission bp = mSettings.mPermissions.get(perm.name);
2503                if (bp == null) {
2504                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2505                    mSettings.mPermissions.put(perm.name, bp);
2506                }
2507                if (perm.gids != null) {
2508                    bp.setGids(perm.gids, perm.perUser);
2509                }
2510            }
2511
2512            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2513            final int builtInLibCount = libConfig.size();
2514            for (int i = 0; i < builtInLibCount; i++) {
2515                String name = libConfig.keyAt(i);
2516                String path = libConfig.valueAt(i);
2517                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2518                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2519            }
2520
2521            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2522
2523            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2524            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2525            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2526
2527            // Clean up orphaned packages for which the code path doesn't exist
2528            // and they are an update to a system app - caused by bug/32321269
2529            final int packageSettingCount = mSettings.mPackages.size();
2530            for (int i = packageSettingCount - 1; i >= 0; i--) {
2531                PackageSetting ps = mSettings.mPackages.valueAt(i);
2532                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2533                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2534                    mSettings.mPackages.removeAt(i);
2535                    mSettings.enableSystemPackageLPw(ps.name);
2536                }
2537            }
2538
2539            if (mFirstBoot) {
2540                requestCopyPreoptedFiles();
2541            }
2542
2543            String customResolverActivity = Resources.getSystem().getString(
2544                    R.string.config_customResolverActivity);
2545            if (TextUtils.isEmpty(customResolverActivity)) {
2546                customResolverActivity = null;
2547            } else {
2548                mCustomResolverComponentName = ComponentName.unflattenFromString(
2549                        customResolverActivity);
2550            }
2551
2552            long startTime = SystemClock.uptimeMillis();
2553
2554            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2555                    startTime);
2556
2557            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2558            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2559
2560            if (bootClassPath == null) {
2561                Slog.w(TAG, "No BOOTCLASSPATH found!");
2562            }
2563
2564            if (systemServerClassPath == null) {
2565                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2566            }
2567
2568            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2569
2570            final VersionInfo ver = mSettings.getInternalVersion();
2571            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2572            if (mIsUpgrade) {
2573                logCriticalInfo(Log.INFO,
2574                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2575            }
2576
2577            // when upgrading from pre-M, promote system app permissions from install to runtime
2578            mPromoteSystemApps =
2579                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2580
2581            // When upgrading from pre-N, we need to handle package extraction like first boot,
2582            // as there is no profiling data available.
2583            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2584
2585            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2586
2587            // save off the names of pre-existing system packages prior to scanning; we don't
2588            // want to automatically grant runtime permissions for new system apps
2589            if (mPromoteSystemApps) {
2590                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2591                while (pkgSettingIter.hasNext()) {
2592                    PackageSetting ps = pkgSettingIter.next();
2593                    if (isSystemApp(ps)) {
2594                        mExistingSystemPackages.add(ps.name);
2595                    }
2596                }
2597            }
2598
2599            mCacheDir = preparePackageParserCache(mIsUpgrade);
2600
2601            // Set flag to monitor and not change apk file paths when
2602            // scanning install directories.
2603            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2604
2605            if (mIsUpgrade || mFirstBoot) {
2606                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2607            }
2608
2609            // Collect vendor overlay packages. (Do this before scanning any apps.)
2610            // For security and version matching reason, only consider
2611            // overlay packages if they reside in the right directory.
2612            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2613                    | PackageParser.PARSE_IS_SYSTEM
2614                    | PackageParser.PARSE_IS_SYSTEM_DIR
2615                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2616
2617            mParallelPackageParserCallback.findStaticOverlayPackages();
2618
2619            // Find base frameworks (resource packages without code).
2620            scanDirTracedLI(frameworkDir, mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR
2623                    | PackageParser.PARSE_IS_PRIVILEGED,
2624                    scanFlags | SCAN_NO_DEX, 0);
2625
2626            // Collected privileged system packages.
2627            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2628            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2629                    | PackageParser.PARSE_IS_SYSTEM
2630                    | PackageParser.PARSE_IS_SYSTEM_DIR
2631                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2632
2633            // Collect ordinary system packages.
2634            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2635            scanDirTracedLI(systemAppDir, mDefParseFlags
2636                    | PackageParser.PARSE_IS_SYSTEM
2637                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2638
2639            // Collect all vendor packages.
2640            File vendorAppDir = new File("/vendor/app");
2641            try {
2642                vendorAppDir = vendorAppDir.getCanonicalFile();
2643            } catch (IOException e) {
2644                // failed to look up canonical path, continue with original one
2645            }
2646            scanDirTracedLI(vendorAppDir, mDefParseFlags
2647                    | PackageParser.PARSE_IS_SYSTEM
2648                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2649
2650            // Collect all OEM packages.
2651            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2652            scanDirTracedLI(oemAppDir, mDefParseFlags
2653                    | PackageParser.PARSE_IS_SYSTEM
2654                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2655
2656            // Prune any system packages that no longer exist.
2657            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2658            // Stub packages must either be replaced with full versions in the /data
2659            // partition or be disabled.
2660            final List<String> stubSystemApps = new ArrayList<>();
2661            if (!mOnlyCore) {
2662                // do this first before mucking with mPackages for the "expecting better" case
2663                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2664                while (pkgIterator.hasNext()) {
2665                    final PackageParser.Package pkg = pkgIterator.next();
2666                    if (pkg.isStub) {
2667                        stubSystemApps.add(pkg.packageName);
2668                    }
2669                }
2670
2671                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2672                while (psit.hasNext()) {
2673                    PackageSetting ps = psit.next();
2674
2675                    /*
2676                     * If this is not a system app, it can't be a
2677                     * disable system app.
2678                     */
2679                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2680                        continue;
2681                    }
2682
2683                    /*
2684                     * If the package is scanned, it's not erased.
2685                     */
2686                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2687                    if (scannedPkg != null) {
2688                        /*
2689                         * If the system app is both scanned and in the
2690                         * disabled packages list, then it must have been
2691                         * added via OTA. Remove it from the currently
2692                         * scanned package so the previously user-installed
2693                         * application can be scanned.
2694                         */
2695                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2696                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2697                                    + ps.name + "; removing system app.  Last known codePath="
2698                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2699                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2700                                    + scannedPkg.mVersionCode);
2701                            removePackageLI(scannedPkg, true);
2702                            mExpectingBetter.put(ps.name, ps.codePath);
2703                        }
2704
2705                        continue;
2706                    }
2707
2708                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2709                        psit.remove();
2710                        logCriticalInfo(Log.WARN, "System package " + ps.name
2711                                + " no longer exists; it's data will be wiped");
2712                        // Actual deletion of code and data will be handled by later
2713                        // reconciliation step
2714                    } else {
2715                        // we still have a disabled system package, but, it still might have
2716                        // been removed. check the code path still exists and check there's
2717                        // still a package. the latter can happen if an OTA keeps the same
2718                        // code path, but, changes the package name.
2719                        final PackageSetting disabledPs =
2720                                mSettings.getDisabledSystemPkgLPr(ps.name);
2721                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2722                                || disabledPs.pkg == null) {
2723                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2724                        }
2725                    }
2726                }
2727            }
2728
2729            //look for any incomplete package installations
2730            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2731            for (int i = 0; i < deletePkgsList.size(); i++) {
2732                // Actual deletion of code and data will be handled by later
2733                // reconciliation step
2734                final String packageName = deletePkgsList.get(i).name;
2735                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2736                synchronized (mPackages) {
2737                    mSettings.removePackageLPw(packageName);
2738                }
2739            }
2740
2741            //delete tmp files
2742            deleteTempPackageFiles();
2743
2744            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2745
2746            // Remove any shared userIDs that have no associated packages
2747            mSettings.pruneSharedUsersLPw();
2748            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2749            final int systemPackagesCount = mPackages.size();
2750            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2751                    + " ms, packageCount: " + systemPackagesCount
2752                    + " , timePerPackage: "
2753                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2754                    + " , cached: " + cachedSystemApps);
2755            if (mIsUpgrade && systemPackagesCount > 0) {
2756                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2757                        ((int) systemScanTime) / systemPackagesCount);
2758            }
2759            if (!mOnlyCore) {
2760                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2761                        SystemClock.uptimeMillis());
2762                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2763
2764                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2765                        | PackageParser.PARSE_FORWARD_LOCK,
2766                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2767
2768                // Remove disable package settings for updated system apps that were
2769                // removed via an OTA. If the update is no longer present, remove the
2770                // app completely. Otherwise, revoke their system privileges.
2771                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2772                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2773                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2774
2775                    final String msg;
2776                    if (deletedPkg == null) {
2777                        // should have found an update, but, we didn't; remove everything
2778                        msg = "Updated system package " + deletedAppName
2779                                + " no longer exists; removing its data";
2780                        // Actual deletion of code and data will be handled by later
2781                        // reconciliation step
2782                    } else {
2783                        // found an update; revoke system privileges
2784                        msg = "Updated system package + " + deletedAppName
2785                                + " no longer exists; revoking system privileges";
2786
2787                        // Don't do anything if a stub is removed from the system image. If
2788                        // we were to remove the uncompressed version from the /data partition,
2789                        // this is where it'd be done.
2790
2791                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2792                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2793                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2794                    }
2795                    logCriticalInfo(Log.WARN, msg);
2796                }
2797
2798                /*
2799                 * Make sure all system apps that we expected to appear on
2800                 * the userdata partition actually showed up. If they never
2801                 * appeared, crawl back and revive the system version.
2802                 */
2803                for (int i = 0; i < mExpectingBetter.size(); i++) {
2804                    final String packageName = mExpectingBetter.keyAt(i);
2805                    if (!mPackages.containsKey(packageName)) {
2806                        final File scanFile = mExpectingBetter.valueAt(i);
2807
2808                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2809                                + " but never showed up; reverting to system");
2810
2811                        int reparseFlags = mDefParseFlags;
2812                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2813                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2814                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2815                                    | PackageParser.PARSE_IS_PRIVILEGED;
2816                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2817                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2818                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2819                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2820                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2821                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2822                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2823                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2824                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2825                        } else {
2826                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2827                            continue;
2828                        }
2829
2830                        mSettings.enableSystemPackageLPw(packageName);
2831
2832                        try {
2833                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2834                        } catch (PackageManagerException e) {
2835                            Slog.e(TAG, "Failed to parse original system package: "
2836                                    + e.getMessage());
2837                        }
2838                    }
2839                }
2840
2841                // Uncompress and install any stubbed system applications.
2842                // This must be done last to ensure all stubs are replaced or disabled.
2843                decompressSystemApplications(stubSystemApps, scanFlags);
2844
2845                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2846                                - cachedSystemApps;
2847
2848                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2849                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2850                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2851                        + " ms, packageCount: " + dataPackagesCount
2852                        + " , timePerPackage: "
2853                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2854                        + " , cached: " + cachedNonSystemApps);
2855                if (mIsUpgrade && dataPackagesCount > 0) {
2856                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2857                            ((int) dataScanTime) / dataPackagesCount);
2858                }
2859            }
2860            mExpectingBetter.clear();
2861
2862            // Resolve the storage manager.
2863            mStorageManagerPackage = getStorageManagerPackageName();
2864
2865            // Resolve protected action filters. Only the setup wizard is allowed to
2866            // have a high priority filter for these actions.
2867            mSetupWizardPackage = getSetupWizardPackageName();
2868            if (mProtectedFilters.size() > 0) {
2869                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2870                    Slog.i(TAG, "No setup wizard;"
2871                        + " All protected intents capped to priority 0");
2872                }
2873                for (ActivityIntentInfo filter : mProtectedFilters) {
2874                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2875                        if (DEBUG_FILTERS) {
2876                            Slog.i(TAG, "Found setup wizard;"
2877                                + " allow priority " + filter.getPriority() + ";"
2878                                + " package: " + filter.activity.info.packageName
2879                                + " activity: " + filter.activity.className
2880                                + " priority: " + filter.getPriority());
2881                        }
2882                        // skip setup wizard; allow it to keep the high priority filter
2883                        continue;
2884                    }
2885                    if (DEBUG_FILTERS) {
2886                        Slog.i(TAG, "Protected action; cap priority to 0;"
2887                                + " package: " + filter.activity.info.packageName
2888                                + " activity: " + filter.activity.className
2889                                + " origPrio: " + filter.getPriority());
2890                    }
2891                    filter.setPriority(0);
2892                }
2893            }
2894            mDeferProtectedFilters = false;
2895            mProtectedFilters.clear();
2896
2897            // Now that we know all of the shared libraries, update all clients to have
2898            // the correct library paths.
2899            updateAllSharedLibrariesLPw(null);
2900
2901            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2902                // NOTE: We ignore potential failures here during a system scan (like
2903                // the rest of the commands above) because there's precious little we
2904                // can do about it. A settings error is reported, though.
2905                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2906            }
2907
2908            // Now that we know all the packages we are keeping,
2909            // read and update their last usage times.
2910            mPackageUsage.read(mPackages);
2911            mCompilerStats.read();
2912
2913            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2914                    SystemClock.uptimeMillis());
2915            Slog.i(TAG, "Time to scan packages: "
2916                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2917                    + " seconds");
2918
2919            // If the platform SDK has changed since the last time we booted,
2920            // we need to re-grant app permission to catch any new ones that
2921            // appear.  This is really a hack, and means that apps can in some
2922            // cases get permissions that the user didn't initially explicitly
2923            // allow...  it would be nice to have some better way to handle
2924            // this situation.
2925            int updateFlags = UPDATE_PERMISSIONS_ALL;
2926            if (ver.sdkVersion != mSdkVersion) {
2927                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2928                        + mSdkVersion + "; regranting permissions for internal storage");
2929                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2930            }
2931            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2932            ver.sdkVersion = mSdkVersion;
2933
2934            // If this is the first boot or an update from pre-M, and it is a normal
2935            // boot, then we need to initialize the default preferred apps across
2936            // all defined users.
2937            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2938                for (UserInfo user : sUserManager.getUsers(true)) {
2939                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2940                    applyFactoryDefaultBrowserLPw(user.id);
2941                    primeDomainVerificationsLPw(user.id);
2942                }
2943            }
2944
2945            // Prepare storage for system user really early during boot,
2946            // since core system apps like SettingsProvider and SystemUI
2947            // can't wait for user to start
2948            final int storageFlags;
2949            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2950                storageFlags = StorageManager.FLAG_STORAGE_DE;
2951            } else {
2952                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2953            }
2954            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2955                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2956                    true /* onlyCoreApps */);
2957            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2958                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2959                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2960                traceLog.traceBegin("AppDataFixup");
2961                try {
2962                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2963                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2964                } catch (InstallerException e) {
2965                    Slog.w(TAG, "Trouble fixing GIDs", e);
2966                }
2967                traceLog.traceEnd();
2968
2969                traceLog.traceBegin("AppDataPrepare");
2970                if (deferPackages == null || deferPackages.isEmpty()) {
2971                    return;
2972                }
2973                int count = 0;
2974                for (String pkgName : deferPackages) {
2975                    PackageParser.Package pkg = null;
2976                    synchronized (mPackages) {
2977                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2978                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2979                            pkg = ps.pkg;
2980                        }
2981                    }
2982                    if (pkg != null) {
2983                        synchronized (mInstallLock) {
2984                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2985                                    true /* maybeMigrateAppData */);
2986                        }
2987                        count++;
2988                    }
2989                }
2990                traceLog.traceEnd();
2991                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2992            }, "prepareAppData");
2993
2994            // If this is first boot after an OTA, and a normal boot, then
2995            // we need to clear code cache directories.
2996            // Note that we do *not* clear the application profiles. These remain valid
2997            // across OTAs and are used to drive profile verification (post OTA) and
2998            // profile compilation (without waiting to collect a fresh set of profiles).
2999            if (mIsUpgrade && !onlyCore) {
3000                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3001                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3002                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3003                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3004                        // No apps are running this early, so no need to freeze
3005                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3006                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3007                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3008                    }
3009                }
3010                ver.fingerprint = Build.FINGERPRINT;
3011            }
3012
3013            checkDefaultBrowser();
3014
3015            // clear only after permissions and other defaults have been updated
3016            mExistingSystemPackages.clear();
3017            mPromoteSystemApps = false;
3018
3019            // All the changes are done during package scanning.
3020            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3021
3022            // can downgrade to reader
3023            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3024            mSettings.writeLPr();
3025            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3026            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3027                    SystemClock.uptimeMillis());
3028
3029            if (!mOnlyCore) {
3030                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3031                mRequiredInstallerPackage = getRequiredInstallerLPr();
3032                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3033                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3034                if (mIntentFilterVerifierComponent != null) {
3035                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3036                            mIntentFilterVerifierComponent);
3037                } else {
3038                    mIntentFilterVerifier = null;
3039                }
3040                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3041                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3042                        SharedLibraryInfo.VERSION_UNDEFINED);
3043                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3044                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3045                        SharedLibraryInfo.VERSION_UNDEFINED);
3046            } else {
3047                mRequiredVerifierPackage = null;
3048                mRequiredInstallerPackage = null;
3049                mRequiredUninstallerPackage = null;
3050                mIntentFilterVerifierComponent = null;
3051                mIntentFilterVerifier = null;
3052                mServicesSystemSharedLibraryPackageName = null;
3053                mSharedSystemSharedLibraryPackageName = null;
3054            }
3055
3056            mInstallerService = new PackageInstallerService(context, this);
3057            final Pair<ComponentName, String> instantAppResolverComponent =
3058                    getInstantAppResolverLPr();
3059            if (instantAppResolverComponent != null) {
3060                if (DEBUG_EPHEMERAL) {
3061                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3062                }
3063                mInstantAppResolverConnection = new EphemeralResolverConnection(
3064                        mContext, instantAppResolverComponent.first,
3065                        instantAppResolverComponent.second);
3066                mInstantAppResolverSettingsComponent =
3067                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3068            } else {
3069                mInstantAppResolverConnection = null;
3070                mInstantAppResolverSettingsComponent = null;
3071            }
3072            updateInstantAppInstallerLocked(null);
3073
3074            // Read and update the usage of dex files.
3075            // Do this at the end of PM init so that all the packages have their
3076            // data directory reconciled.
3077            // At this point we know the code paths of the packages, so we can validate
3078            // the disk file and build the internal cache.
3079            // The usage file is expected to be small so loading and verifying it
3080            // should take a fairly small time compare to the other activities (e.g. package
3081            // scanning).
3082            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3083            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3084            for (int userId : currentUserIds) {
3085                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3086            }
3087            mDexManager.load(userPackages);
3088            if (mIsUpgrade) {
3089                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3090                        (int) (SystemClock.uptimeMillis() - startTime));
3091            }
3092        } // synchronized (mPackages)
3093        } // synchronized (mInstallLock)
3094
3095        // Now after opening every single application zip, make sure they
3096        // are all flushed.  Not really needed, but keeps things nice and
3097        // tidy.
3098        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3099        Runtime.getRuntime().gc();
3100        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3101
3102        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3103        FallbackCategoryProvider.loadFallbacks();
3104        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3105
3106        // The initial scanning above does many calls into installd while
3107        // holding the mPackages lock, but we're mostly interested in yelling
3108        // once we have a booted system.
3109        mInstaller.setWarnIfHeld(mPackages);
3110
3111        // Expose private service for system components to use.
3112        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3113        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3114    }
3115
3116    /**
3117     * Uncompress and install stub applications.
3118     * <p>In order to save space on the system partition, some applications are shipped in a
3119     * compressed form. In addition the compressed bits for the full application, the
3120     * system image contains a tiny stub comprised of only the Android manifest.
3121     * <p>During the first boot, attempt to uncompress and install the full application. If
3122     * the application can't be installed for any reason, disable the stub and prevent
3123     * uncompressing the full application during future boots.
3124     * <p>In order to forcefully attempt an installation of a full application, go to app
3125     * settings and enable the application.
3126     */
3127    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3128        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3129            final String pkgName = stubSystemApps.get(i);
3130            // skip if the system package is already disabled
3131            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3132                stubSystemApps.remove(i);
3133                continue;
3134            }
3135            // skip if the package isn't installed (?!); this should never happen
3136            final PackageParser.Package pkg = mPackages.get(pkgName);
3137            if (pkg == null) {
3138                stubSystemApps.remove(i);
3139                continue;
3140            }
3141            // skip if the package has been disabled by the user
3142            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3143            if (ps != null) {
3144                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3145                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3146                    stubSystemApps.remove(i);
3147                    continue;
3148                }
3149            }
3150
3151            if (DEBUG_COMPRESSION) {
3152                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3153            }
3154
3155            // uncompress the binary to its eventual destination on /data
3156            final File scanFile = decompressPackage(pkg);
3157            if (scanFile == null) {
3158                continue;
3159            }
3160
3161            // install the package to replace the stub on /system
3162            try {
3163                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3164                removePackageLI(pkg, true /*chatty*/);
3165                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3166                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3167                        UserHandle.USER_SYSTEM, "android");
3168                stubSystemApps.remove(i);
3169                continue;
3170            } catch (PackageManagerException e) {
3171                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3172            }
3173
3174            // any failed attempt to install the package will be cleaned up later
3175        }
3176
3177        // disable any stub still left; these failed to install the full application
3178        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3179            final String pkgName = stubSystemApps.get(i);
3180            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3181            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3182                    UserHandle.USER_SYSTEM, "android");
3183            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3184        }
3185    }
3186
3187    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3188        if (DEBUG_COMPRESSION) {
3189            Slog.i(TAG, "Decompress file"
3190                    + "; src: " + srcFile.getAbsolutePath()
3191                    + ", dst: " + dstFile.getAbsolutePath());
3192        }
3193        try (
3194                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3195                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3196        ) {
3197            Streams.copy(fileIn, fileOut);
3198            Os.chmod(dstFile.getAbsolutePath(), 0644);
3199            return PackageManager.INSTALL_SUCCEEDED;
3200        } catch (IOException e) {
3201            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3202                    + "; src: " + srcFile.getAbsolutePath()
3203                    + ", dst: " + dstFile.getAbsolutePath());
3204        }
3205        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3206    }
3207
3208    private File[] getCompressedFiles(String codePath) {
3209        final File stubCodePath = new File(codePath);
3210        final String stubName = stubCodePath.getName();
3211
3212        // The layout of a compressed package on a given partition is as follows :
3213        //
3214        // Compressed artifacts:
3215        //
3216        // /partition/ModuleName/foo.gz
3217        // /partation/ModuleName/bar.gz
3218        //
3219        // Stub artifact:
3220        //
3221        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3222        //
3223        // In other words, stub is on the same partition as the compressed artifacts
3224        // and in a directory that's suffixed with "-Stub".
3225        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3226        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3227            return null;
3228        }
3229
3230        final File stubParentDir = stubCodePath.getParentFile();
3231        if (stubParentDir == null) {
3232            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3233            return null;
3234        }
3235
3236        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3237        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3238            @Override
3239            public boolean accept(File dir, String name) {
3240                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3241            }
3242        });
3243
3244        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3245            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3246        }
3247
3248        return files;
3249    }
3250
3251    private boolean compressedFileExists(String codePath) {
3252        final File[] compressedFiles = getCompressedFiles(codePath);
3253        return compressedFiles != null && compressedFiles.length > 0;
3254    }
3255
3256    /**
3257     * Decompresses the given package on the system image onto
3258     * the /data partition.
3259     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3260     */
3261    private File decompressPackage(PackageParser.Package pkg) {
3262        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3263        if (compressedFiles == null || compressedFiles.length == 0) {
3264            if (DEBUG_COMPRESSION) {
3265                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3266            }
3267            return null;
3268        }
3269        final File dstCodePath =
3270                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3271        int ret = PackageManager.INSTALL_SUCCEEDED;
3272        try {
3273            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3274            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3275            for (File srcFile : compressedFiles) {
3276                final String srcFileName = srcFile.getName();
3277                final String dstFileName = srcFileName.substring(
3278                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3279                final File dstFile = new File(dstCodePath, dstFileName);
3280                ret = decompressFile(srcFile, dstFile);
3281                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3282                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3283                            + "; pkg: " + pkg.packageName
3284                            + ", file: " + dstFileName);
3285                    break;
3286                }
3287            }
3288        } catch (ErrnoException e) {
3289            logCriticalInfo(Log.ERROR, "Failed to decompress"
3290                    + "; pkg: " + pkg.packageName
3291                    + ", err: " + e.errno);
3292        }
3293        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3294            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3295            NativeLibraryHelper.Handle handle = null;
3296            try {
3297                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3298                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3299                        null /*abiOverride*/);
3300            } catch (IOException e) {
3301                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3302                        + "; pkg: " + pkg.packageName);
3303                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3304            } finally {
3305                IoUtils.closeQuietly(handle);
3306            }
3307        }
3308        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3309            if (dstCodePath == null || !dstCodePath.exists()) {
3310                return null;
3311            }
3312            removeCodePathLI(dstCodePath);
3313            return null;
3314        }
3315        return dstCodePath;
3316    }
3317
3318    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3319        // we're only interested in updating the installer appliction when 1) it's not
3320        // already set or 2) the modified package is the installer
3321        if (mInstantAppInstallerActivity != null
3322                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3323                        .equals(modifiedPackage)) {
3324            return;
3325        }
3326        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3327    }
3328
3329    private static File preparePackageParserCache(boolean isUpgrade) {
3330        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3331            return null;
3332        }
3333
3334        // Disable package parsing on eng builds to allow for faster incremental development.
3335        if (Build.IS_ENG) {
3336            return null;
3337        }
3338
3339        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3340            Slog.i(TAG, "Disabling package parser cache due to system property.");
3341            return null;
3342        }
3343
3344        // The base directory for the package parser cache lives under /data/system/.
3345        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3346                "package_cache");
3347        if (cacheBaseDir == null) {
3348            return null;
3349        }
3350
3351        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3352        // This also serves to "GC" unused entries when the package cache version changes (which
3353        // can only happen during upgrades).
3354        if (isUpgrade) {
3355            FileUtils.deleteContents(cacheBaseDir);
3356        }
3357
3358
3359        // Return the versioned package cache directory. This is something like
3360        // "/data/system/package_cache/1"
3361        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3362
3363        // The following is a workaround to aid development on non-numbered userdebug
3364        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3365        // the system partition is newer.
3366        //
3367        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3368        // that starts with "eng." to signify that this is an engineering build and not
3369        // destined for release.
3370        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3371            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3372
3373            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3374            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3375            // in general and should not be used for production changes. In this specific case,
3376            // we know that they will work.
3377            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3378            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3379                FileUtils.deleteContents(cacheBaseDir);
3380                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3381            }
3382        }
3383
3384        return cacheDir;
3385    }
3386
3387    @Override
3388    public boolean isFirstBoot() {
3389        // allow instant applications
3390        return mFirstBoot;
3391    }
3392
3393    @Override
3394    public boolean isOnlyCoreApps() {
3395        // allow instant applications
3396        return mOnlyCore;
3397    }
3398
3399    @Override
3400    public boolean isUpgrade() {
3401        // allow instant applications
3402        return mIsUpgrade;
3403    }
3404
3405    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3406        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3407
3408        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3409                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3410                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3411        if (matches.size() == 1) {
3412            return matches.get(0).getComponentInfo().packageName;
3413        } else if (matches.size() == 0) {
3414            Log.e(TAG, "There should probably be a verifier, but, none were found");
3415            return null;
3416        }
3417        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3418    }
3419
3420    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3421        synchronized (mPackages) {
3422            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3423            if (libraryEntry == null) {
3424                throw new IllegalStateException("Missing required shared library:" + name);
3425            }
3426            return libraryEntry.apk;
3427        }
3428    }
3429
3430    private @NonNull String getRequiredInstallerLPr() {
3431        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3432        intent.addCategory(Intent.CATEGORY_DEFAULT);
3433        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3434
3435        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3436                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3437                UserHandle.USER_SYSTEM);
3438        if (matches.size() == 1) {
3439            ResolveInfo resolveInfo = matches.get(0);
3440            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3441                throw new RuntimeException("The installer must be a privileged app");
3442            }
3443            return matches.get(0).getComponentInfo().packageName;
3444        } else {
3445            throw new RuntimeException("There must be exactly one installer; found " + matches);
3446        }
3447    }
3448
3449    private @NonNull String getRequiredUninstallerLPr() {
3450        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3451        intent.addCategory(Intent.CATEGORY_DEFAULT);
3452        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3453
3454        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3455                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3456                UserHandle.USER_SYSTEM);
3457        if (resolveInfo == null ||
3458                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3459            throw new RuntimeException("There must be exactly one uninstaller; found "
3460                    + resolveInfo);
3461        }
3462        return resolveInfo.getComponentInfo().packageName;
3463    }
3464
3465    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3466        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3467
3468        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3469                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3470                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3471        ResolveInfo best = null;
3472        final int N = matches.size();
3473        for (int i = 0; i < N; i++) {
3474            final ResolveInfo cur = matches.get(i);
3475            final String packageName = cur.getComponentInfo().packageName;
3476            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3477                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3478                continue;
3479            }
3480
3481            if (best == null || cur.priority > best.priority) {
3482                best = cur;
3483            }
3484        }
3485
3486        if (best != null) {
3487            return best.getComponentInfo().getComponentName();
3488        }
3489        Slog.w(TAG, "Intent filter verifier not found");
3490        return null;
3491    }
3492
3493    @Override
3494    public @Nullable ComponentName getInstantAppResolverComponent() {
3495        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3496            return null;
3497        }
3498        synchronized (mPackages) {
3499            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3500            if (instantAppResolver == null) {
3501                return null;
3502            }
3503            return instantAppResolver.first;
3504        }
3505    }
3506
3507    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3508        final String[] packageArray =
3509                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3510        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3511            if (DEBUG_EPHEMERAL) {
3512                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3513            }
3514            return null;
3515        }
3516
3517        final int callingUid = Binder.getCallingUid();
3518        final int resolveFlags =
3519                MATCH_DIRECT_BOOT_AWARE
3520                | MATCH_DIRECT_BOOT_UNAWARE
3521                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3522        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3523        final Intent resolverIntent = new Intent(actionName);
3524        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3525                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3526        // temporarily look for the old action
3527        if (resolvers.size() == 0) {
3528            if (DEBUG_EPHEMERAL) {
3529                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3530            }
3531            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3532            resolverIntent.setAction(actionName);
3533            resolvers = queryIntentServicesInternal(resolverIntent, null,
3534                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3535        }
3536        final int N = resolvers.size();
3537        if (N == 0) {
3538            if (DEBUG_EPHEMERAL) {
3539                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3540            }
3541            return null;
3542        }
3543
3544        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3545        for (int i = 0; i < N; i++) {
3546            final ResolveInfo info = resolvers.get(i);
3547
3548            if (info.serviceInfo == null) {
3549                continue;
3550            }
3551
3552            final String packageName = info.serviceInfo.packageName;
3553            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3554                if (DEBUG_EPHEMERAL) {
3555                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3556                            + " pkg: " + packageName + ", info:" + info);
3557                }
3558                continue;
3559            }
3560
3561            if (DEBUG_EPHEMERAL) {
3562                Slog.v(TAG, "Ephemeral resolver found;"
3563                        + " pkg: " + packageName + ", info:" + info);
3564            }
3565            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3566        }
3567        if (DEBUG_EPHEMERAL) {
3568            Slog.v(TAG, "Ephemeral resolver NOT found");
3569        }
3570        return null;
3571    }
3572
3573    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3574        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3575        intent.addCategory(Intent.CATEGORY_DEFAULT);
3576        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3577
3578        final int resolveFlags =
3579                MATCH_DIRECT_BOOT_AWARE
3580                | MATCH_DIRECT_BOOT_UNAWARE
3581                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3582        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3583                resolveFlags, UserHandle.USER_SYSTEM);
3584        // temporarily look for the old action
3585        if (matches.isEmpty()) {
3586            if (DEBUG_EPHEMERAL) {
3587                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3588            }
3589            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3590            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3591                    resolveFlags, UserHandle.USER_SYSTEM);
3592        }
3593        Iterator<ResolveInfo> iter = matches.iterator();
3594        while (iter.hasNext()) {
3595            final ResolveInfo rInfo = iter.next();
3596            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3597            if (ps != null) {
3598                final PermissionsState permissionsState = ps.getPermissionsState();
3599                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3600                    continue;
3601                }
3602            }
3603            iter.remove();
3604        }
3605        if (matches.size() == 0) {
3606            return null;
3607        } else if (matches.size() == 1) {
3608            return (ActivityInfo) matches.get(0).getComponentInfo();
3609        } else {
3610            throw new RuntimeException(
3611                    "There must be at most one ephemeral installer; found " + matches);
3612        }
3613    }
3614
3615    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3616            @NonNull ComponentName resolver) {
3617        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3618                .addCategory(Intent.CATEGORY_DEFAULT)
3619                .setPackage(resolver.getPackageName());
3620        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3621        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3622                UserHandle.USER_SYSTEM);
3623        // temporarily look for the old action
3624        if (matches.isEmpty()) {
3625            if (DEBUG_EPHEMERAL) {
3626                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3627            }
3628            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3629            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3630                    UserHandle.USER_SYSTEM);
3631        }
3632        if (matches.isEmpty()) {
3633            return null;
3634        }
3635        return matches.get(0).getComponentInfo().getComponentName();
3636    }
3637
3638    private void primeDomainVerificationsLPw(int userId) {
3639        if (DEBUG_DOMAIN_VERIFICATION) {
3640            Slog.d(TAG, "Priming domain verifications in user " + userId);
3641        }
3642
3643        SystemConfig systemConfig = SystemConfig.getInstance();
3644        ArraySet<String> packages = systemConfig.getLinkedApps();
3645
3646        for (String packageName : packages) {
3647            PackageParser.Package pkg = mPackages.get(packageName);
3648            if (pkg != null) {
3649                if (!pkg.isSystemApp()) {
3650                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3651                    continue;
3652                }
3653
3654                ArraySet<String> domains = null;
3655                for (PackageParser.Activity a : pkg.activities) {
3656                    for (ActivityIntentInfo filter : a.intents) {
3657                        if (hasValidDomains(filter)) {
3658                            if (domains == null) {
3659                                domains = new ArraySet<String>();
3660                            }
3661                            domains.addAll(filter.getHostsList());
3662                        }
3663                    }
3664                }
3665
3666                if (domains != null && domains.size() > 0) {
3667                    if (DEBUG_DOMAIN_VERIFICATION) {
3668                        Slog.v(TAG, "      + " + packageName);
3669                    }
3670                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3671                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3672                    // and then 'always' in the per-user state actually used for intent resolution.
3673                    final IntentFilterVerificationInfo ivi;
3674                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3675                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3676                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3677                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3678                } else {
3679                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3680                            + "' does not handle web links");
3681                }
3682            } else {
3683                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3684            }
3685        }
3686
3687        scheduleWritePackageRestrictionsLocked(userId);
3688        scheduleWriteSettingsLocked();
3689    }
3690
3691    private void applyFactoryDefaultBrowserLPw(int userId) {
3692        // The default browser app's package name is stored in a string resource,
3693        // with a product-specific overlay used for vendor customization.
3694        String browserPkg = mContext.getResources().getString(
3695                com.android.internal.R.string.default_browser);
3696        if (!TextUtils.isEmpty(browserPkg)) {
3697            // non-empty string => required to be a known package
3698            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3699            if (ps == null) {
3700                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3701                browserPkg = null;
3702            } else {
3703                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3704            }
3705        }
3706
3707        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3708        // default.  If there's more than one, just leave everything alone.
3709        if (browserPkg == null) {
3710            calculateDefaultBrowserLPw(userId);
3711        }
3712    }
3713
3714    private void calculateDefaultBrowserLPw(int userId) {
3715        List<String> allBrowsers = resolveAllBrowserApps(userId);
3716        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3717        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3718    }
3719
3720    private List<String> resolveAllBrowserApps(int userId) {
3721        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3722        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3723                PackageManager.MATCH_ALL, userId);
3724
3725        final int count = list.size();
3726        List<String> result = new ArrayList<String>(count);
3727        for (int i=0; i<count; i++) {
3728            ResolveInfo info = list.get(i);
3729            if (info.activityInfo == null
3730                    || !info.handleAllWebDataURI
3731                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3732                    || result.contains(info.activityInfo.packageName)) {
3733                continue;
3734            }
3735            result.add(info.activityInfo.packageName);
3736        }
3737
3738        return result;
3739    }
3740
3741    private boolean packageIsBrowser(String packageName, int userId) {
3742        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3743                PackageManager.MATCH_ALL, userId);
3744        final int N = list.size();
3745        for (int i = 0; i < N; i++) {
3746            ResolveInfo info = list.get(i);
3747            if (packageName.equals(info.activityInfo.packageName)) {
3748                return true;
3749            }
3750        }
3751        return false;
3752    }
3753
3754    private void checkDefaultBrowser() {
3755        final int myUserId = UserHandle.myUserId();
3756        final String packageName = getDefaultBrowserPackageName(myUserId);
3757        if (packageName != null) {
3758            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3759            if (info == null) {
3760                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3761                synchronized (mPackages) {
3762                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3763                }
3764            }
3765        }
3766    }
3767
3768    @Override
3769    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3770            throws RemoteException {
3771        try {
3772            return super.onTransact(code, data, reply, flags);
3773        } catch (RuntimeException e) {
3774            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3775                Slog.wtf(TAG, "Package Manager Crash", e);
3776            }
3777            throw e;
3778        }
3779    }
3780
3781    static int[] appendInts(int[] cur, int[] add) {
3782        if (add == null) return cur;
3783        if (cur == null) return add;
3784        final int N = add.length;
3785        for (int i=0; i<N; i++) {
3786            cur = appendInt(cur, add[i]);
3787        }
3788        return cur;
3789    }
3790
3791    /**
3792     * Returns whether or not a full application can see an instant application.
3793     * <p>
3794     * Currently, there are three cases in which this can occur:
3795     * <ol>
3796     * <li>The calling application is a "special" process. The special
3797     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3798     *     and {@code 0}</li>
3799     * <li>The calling application has the permission
3800     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3801     * <li>The calling application is the default launcher on the
3802     *     system partition.</li>
3803     * </ol>
3804     */
3805    private boolean canViewInstantApps(int callingUid, int userId) {
3806        if (callingUid == Process.SYSTEM_UID
3807                || callingUid == Process.SHELL_UID
3808                || callingUid == Process.ROOT_UID) {
3809            return true;
3810        }
3811        if (mContext.checkCallingOrSelfPermission(
3812                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3813            return true;
3814        }
3815        if (mContext.checkCallingOrSelfPermission(
3816                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3817            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3818            if (homeComponent != null
3819                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3820                return true;
3821            }
3822        }
3823        return false;
3824    }
3825
3826    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3827        if (!sUserManager.exists(userId)) return null;
3828        if (ps == null) {
3829            return null;
3830        }
3831        PackageParser.Package p = ps.pkg;
3832        if (p == null) {
3833            return null;
3834        }
3835        final int callingUid = Binder.getCallingUid();
3836        // Filter out ephemeral app metadata:
3837        //   * The system/shell/root can see metadata for any app
3838        //   * An installed app can see metadata for 1) other installed apps
3839        //     and 2) ephemeral apps that have explicitly interacted with it
3840        //   * Ephemeral apps can only see their own data and exposed installed apps
3841        //   * Holding a signature permission allows seeing instant apps
3842        if (filterAppAccessLPr(ps, callingUid, userId)) {
3843            return null;
3844        }
3845
3846        final PermissionsState permissionsState = ps.getPermissionsState();
3847
3848        // Compute GIDs only if requested
3849        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3850                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3851        // Compute granted permissions only if package has requested permissions
3852        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3853                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3854        final PackageUserState state = ps.readUserState(userId);
3855
3856        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3857                && ps.isSystem()) {
3858            flags |= MATCH_ANY_USER;
3859        }
3860
3861        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3862                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3863
3864        if (packageInfo == null) {
3865            return null;
3866        }
3867
3868        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3869                resolveExternalPackageNameLPr(p);
3870
3871        return packageInfo;
3872    }
3873
3874    @Override
3875    public void checkPackageStartable(String packageName, int userId) {
3876        final int callingUid = Binder.getCallingUid();
3877        if (getInstantAppPackageName(callingUid) != null) {
3878            throw new SecurityException("Instant applications don't have access to this method");
3879        }
3880        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3881        synchronized (mPackages) {
3882            final PackageSetting ps = mSettings.mPackages.get(packageName);
3883            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3884                throw new SecurityException("Package " + packageName + " was not found!");
3885            }
3886
3887            if (!ps.getInstalled(userId)) {
3888                throw new SecurityException(
3889                        "Package " + packageName + " was not installed for user " + userId + "!");
3890            }
3891
3892            if (mSafeMode && !ps.isSystem()) {
3893                throw new SecurityException("Package " + packageName + " not a system app!");
3894            }
3895
3896            if (mFrozenPackages.contains(packageName)) {
3897                throw new SecurityException("Package " + packageName + " is currently frozen!");
3898            }
3899
3900            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3901                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3902            }
3903        }
3904    }
3905
3906    @Override
3907    public boolean isPackageAvailable(String packageName, int userId) {
3908        if (!sUserManager.exists(userId)) return false;
3909        final int callingUid = Binder.getCallingUid();
3910        enforceCrossUserPermission(callingUid, userId,
3911                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3912        synchronized (mPackages) {
3913            PackageParser.Package p = mPackages.get(packageName);
3914            if (p != null) {
3915                final PackageSetting ps = (PackageSetting) p.mExtras;
3916                if (filterAppAccessLPr(ps, callingUid, userId)) {
3917                    return false;
3918                }
3919                if (ps != null) {
3920                    final PackageUserState state = ps.readUserState(userId);
3921                    if (state != null) {
3922                        return PackageParser.isAvailable(state);
3923                    }
3924                }
3925            }
3926        }
3927        return false;
3928    }
3929
3930    @Override
3931    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3932        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3933                flags, Binder.getCallingUid(), userId);
3934    }
3935
3936    @Override
3937    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3938            int flags, int userId) {
3939        return getPackageInfoInternal(versionedPackage.getPackageName(),
3940                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3941    }
3942
3943    /**
3944     * Important: The provided filterCallingUid is used exclusively to filter out packages
3945     * that can be seen based on user state. It's typically the original caller uid prior
3946     * to clearing. Because it can only be provided by trusted code, it's value can be
3947     * trusted and will be used as-is; unlike userId which will be validated by this method.
3948     */
3949    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3950            int flags, int filterCallingUid, int userId) {
3951        if (!sUserManager.exists(userId)) return null;
3952        flags = updateFlagsForPackage(flags, userId, packageName);
3953        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3954                false /* requireFullPermission */, false /* checkShell */, "get package info");
3955
3956        // reader
3957        synchronized (mPackages) {
3958            // Normalize package name to handle renamed packages and static libs
3959            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3960
3961            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3962            if (matchFactoryOnly) {
3963                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3964                if (ps != null) {
3965                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3966                        return null;
3967                    }
3968                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3969                        return null;
3970                    }
3971                    return generatePackageInfo(ps, flags, userId);
3972                }
3973            }
3974
3975            PackageParser.Package p = mPackages.get(packageName);
3976            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3977                return null;
3978            }
3979            if (DEBUG_PACKAGE_INFO)
3980                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3981            if (p != null) {
3982                final PackageSetting ps = (PackageSetting) p.mExtras;
3983                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3984                    return null;
3985                }
3986                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3987                    return null;
3988                }
3989                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3990            }
3991            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3992                final PackageSetting ps = mSettings.mPackages.get(packageName);
3993                if (ps == null) return null;
3994                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3995                    return null;
3996                }
3997                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3998                    return null;
3999                }
4000                return generatePackageInfo(ps, flags, userId);
4001            }
4002        }
4003        return null;
4004    }
4005
4006    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4007        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4008            return true;
4009        }
4010        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4011            return true;
4012        }
4013        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4014            return true;
4015        }
4016        return false;
4017    }
4018
4019    private boolean isComponentVisibleToInstantApp(
4020            @Nullable ComponentName component, @ComponentType int type) {
4021        if (type == TYPE_ACTIVITY) {
4022            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4023            return activity != null
4024                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4025                    : false;
4026        } else if (type == TYPE_RECEIVER) {
4027            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4028            return activity != null
4029                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4030                    : false;
4031        } else if (type == TYPE_SERVICE) {
4032            final PackageParser.Service service = mServices.mServices.get(component);
4033            return service != null
4034                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4035                    : false;
4036        } else if (type == TYPE_PROVIDER) {
4037            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4038            return provider != null
4039                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4040                    : false;
4041        } else if (type == TYPE_UNKNOWN) {
4042            return isComponentVisibleToInstantApp(component);
4043        }
4044        return false;
4045    }
4046
4047    /**
4048     * Returns whether or not access to the application should be filtered.
4049     * <p>
4050     * Access may be limited based upon whether the calling or target applications
4051     * are instant applications.
4052     *
4053     * @see #canAccessInstantApps(int)
4054     */
4055    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4056            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4057        // if we're in an isolated process, get the real calling UID
4058        if (Process.isIsolated(callingUid)) {
4059            callingUid = mIsolatedOwners.get(callingUid);
4060        }
4061        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4062        final boolean callerIsInstantApp = instantAppPkgName != null;
4063        if (ps == null) {
4064            if (callerIsInstantApp) {
4065                // pretend the application exists, but, needs to be filtered
4066                return true;
4067            }
4068            return false;
4069        }
4070        // if the target and caller are the same application, don't filter
4071        if (isCallerSameApp(ps.name, callingUid)) {
4072            return false;
4073        }
4074        if (callerIsInstantApp) {
4075            // request for a specific component; if it hasn't been explicitly exposed, filter
4076            if (component != null) {
4077                return !isComponentVisibleToInstantApp(component, componentType);
4078            }
4079            // request for application; if no components have been explicitly exposed, filter
4080            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4081        }
4082        if (ps.getInstantApp(userId)) {
4083            // caller can see all components of all instant applications, don't filter
4084            if (canViewInstantApps(callingUid, userId)) {
4085                return false;
4086            }
4087            // request for a specific instant application component, filter
4088            if (component != null) {
4089                return true;
4090            }
4091            // request for an instant application; if the caller hasn't been granted access, filter
4092            return !mInstantAppRegistry.isInstantAccessGranted(
4093                    userId, UserHandle.getAppId(callingUid), ps.appId);
4094        }
4095        return false;
4096    }
4097
4098    /**
4099     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4100     */
4101    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4102        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4103    }
4104
4105    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4106            int flags) {
4107        // Callers can access only the libs they depend on, otherwise they need to explicitly
4108        // ask for the shared libraries given the caller is allowed to access all static libs.
4109        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4110            // System/shell/root get to see all static libs
4111            final int appId = UserHandle.getAppId(uid);
4112            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4113                    || appId == Process.ROOT_UID) {
4114                return false;
4115            }
4116        }
4117
4118        // No package means no static lib as it is always on internal storage
4119        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4120            return false;
4121        }
4122
4123        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4124                ps.pkg.staticSharedLibVersion);
4125        if (libEntry == null) {
4126            return false;
4127        }
4128
4129        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4130        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4131        if (uidPackageNames == null) {
4132            return true;
4133        }
4134
4135        for (String uidPackageName : uidPackageNames) {
4136            if (ps.name.equals(uidPackageName)) {
4137                return false;
4138            }
4139            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4140            if (uidPs != null) {
4141                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4142                        libEntry.info.getName());
4143                if (index < 0) {
4144                    continue;
4145                }
4146                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4147                    return false;
4148                }
4149            }
4150        }
4151        return true;
4152    }
4153
4154    @Override
4155    public String[] currentToCanonicalPackageNames(String[] names) {
4156        final int callingUid = Binder.getCallingUid();
4157        if (getInstantAppPackageName(callingUid) != null) {
4158            return names;
4159        }
4160        final String[] out = new String[names.length];
4161        // reader
4162        synchronized (mPackages) {
4163            final int callingUserId = UserHandle.getUserId(callingUid);
4164            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4165            for (int i=names.length-1; i>=0; i--) {
4166                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4167                boolean translateName = false;
4168                if (ps != null && ps.realName != null) {
4169                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4170                    translateName = !targetIsInstantApp
4171                            || canViewInstantApps
4172                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4173                                    UserHandle.getAppId(callingUid), ps.appId);
4174                }
4175                out[i] = translateName ? ps.realName : names[i];
4176            }
4177        }
4178        return out;
4179    }
4180
4181    @Override
4182    public String[] canonicalToCurrentPackageNames(String[] names) {
4183        final int callingUid = Binder.getCallingUid();
4184        if (getInstantAppPackageName(callingUid) != null) {
4185            return names;
4186        }
4187        final String[] out = new String[names.length];
4188        // reader
4189        synchronized (mPackages) {
4190            final int callingUserId = UserHandle.getUserId(callingUid);
4191            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4192            for (int i=names.length-1; i>=0; i--) {
4193                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4194                boolean translateName = false;
4195                if (cur != null) {
4196                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4197                    final boolean targetIsInstantApp =
4198                            ps != null && ps.getInstantApp(callingUserId);
4199                    translateName = !targetIsInstantApp
4200                            || canViewInstantApps
4201                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4202                                    UserHandle.getAppId(callingUid), ps.appId);
4203                }
4204                out[i] = translateName ? cur : names[i];
4205            }
4206        }
4207        return out;
4208    }
4209
4210    @Override
4211    public int getPackageUid(String packageName, int flags, int userId) {
4212        if (!sUserManager.exists(userId)) return -1;
4213        final int callingUid = Binder.getCallingUid();
4214        flags = updateFlagsForPackage(flags, userId, packageName);
4215        enforceCrossUserPermission(callingUid, userId,
4216                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4217
4218        // reader
4219        synchronized (mPackages) {
4220            final PackageParser.Package p = mPackages.get(packageName);
4221            if (p != null && p.isMatch(flags)) {
4222                PackageSetting ps = (PackageSetting) p.mExtras;
4223                if (filterAppAccessLPr(ps, callingUid, userId)) {
4224                    return -1;
4225                }
4226                return UserHandle.getUid(userId, p.applicationInfo.uid);
4227            }
4228            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4229                final PackageSetting ps = mSettings.mPackages.get(packageName);
4230                if (ps != null && ps.isMatch(flags)
4231                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4232                    return UserHandle.getUid(userId, ps.appId);
4233                }
4234            }
4235        }
4236
4237        return -1;
4238    }
4239
4240    @Override
4241    public int[] getPackageGids(String packageName, int flags, int userId) {
4242        if (!sUserManager.exists(userId)) return null;
4243        final int callingUid = Binder.getCallingUid();
4244        flags = updateFlagsForPackage(flags, userId, packageName);
4245        enforceCrossUserPermission(callingUid, userId,
4246                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4247
4248        // reader
4249        synchronized (mPackages) {
4250            final PackageParser.Package p = mPackages.get(packageName);
4251            if (p != null && p.isMatch(flags)) {
4252                PackageSetting ps = (PackageSetting) p.mExtras;
4253                if (filterAppAccessLPr(ps, callingUid, userId)) {
4254                    return null;
4255                }
4256                // TODO: Shouldn't this be checking for package installed state for userId and
4257                // return null?
4258                return ps.getPermissionsState().computeGids(userId);
4259            }
4260            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4261                final PackageSetting ps = mSettings.mPackages.get(packageName);
4262                if (ps != null && ps.isMatch(flags)
4263                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4264                    return ps.getPermissionsState().computeGids(userId);
4265                }
4266            }
4267        }
4268
4269        return null;
4270    }
4271
4272    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4273        if (bp.perm != null) {
4274            return PackageParser.generatePermissionInfo(bp.perm, flags);
4275        }
4276        PermissionInfo pi = new PermissionInfo();
4277        pi.name = bp.name;
4278        pi.packageName = bp.sourcePackage;
4279        pi.nonLocalizedLabel = bp.name;
4280        pi.protectionLevel = bp.protectionLevel;
4281        return pi;
4282    }
4283
4284    @Override
4285    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4286        final int callingUid = Binder.getCallingUid();
4287        if (getInstantAppPackageName(callingUid) != null) {
4288            return null;
4289        }
4290        // reader
4291        synchronized (mPackages) {
4292            final BasePermission p = mSettings.mPermissions.get(name);
4293            if (p == null) {
4294                return null;
4295            }
4296            // If the caller is an app that targets pre 26 SDK drop protection flags.
4297            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4298            if (permissionInfo != null) {
4299                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4300                        permissionInfo.protectionLevel, packageName, callingUid);
4301                if (permissionInfo.protectionLevel != protectionLevel) {
4302                    // If we return different protection level, don't use the cached info
4303                    if (p.perm != null && p.perm.info == permissionInfo) {
4304                        permissionInfo = new PermissionInfo(permissionInfo);
4305                    }
4306                    permissionInfo.protectionLevel = protectionLevel;
4307                }
4308            }
4309            return permissionInfo;
4310        }
4311    }
4312
4313    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4314            String packageName, int uid) {
4315        // Signature permission flags area always reported
4316        final int protectionLevelMasked = protectionLevel
4317                & (PermissionInfo.PROTECTION_NORMAL
4318                | PermissionInfo.PROTECTION_DANGEROUS
4319                | PermissionInfo.PROTECTION_SIGNATURE);
4320        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4321            return protectionLevel;
4322        }
4323
4324        // System sees all flags.
4325        final int appId = UserHandle.getAppId(uid);
4326        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4327                || appId == Process.SHELL_UID) {
4328            return protectionLevel;
4329        }
4330
4331        // Normalize package name to handle renamed packages and static libs
4332        packageName = resolveInternalPackageNameLPr(packageName,
4333                PackageManager.VERSION_CODE_HIGHEST);
4334
4335        // Apps that target O see flags for all protection levels.
4336        final PackageSetting ps = mSettings.mPackages.get(packageName);
4337        if (ps == null) {
4338            return protectionLevel;
4339        }
4340        if (ps.appId != appId) {
4341            return protectionLevel;
4342        }
4343
4344        final PackageParser.Package pkg = mPackages.get(packageName);
4345        if (pkg == null) {
4346            return protectionLevel;
4347        }
4348        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4349            return protectionLevelMasked;
4350        }
4351
4352        return protectionLevel;
4353    }
4354
4355    @Override
4356    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4357            int flags) {
4358        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4359            return null;
4360        }
4361        // reader
4362        synchronized (mPackages) {
4363            if (group != null && !mPermissionGroups.containsKey(group)) {
4364                // This is thrown as NameNotFoundException
4365                return null;
4366            }
4367
4368            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4369            for (BasePermission p : mSettings.mPermissions.values()) {
4370                if (group == null) {
4371                    if (p.perm == null || p.perm.info.group == null) {
4372                        out.add(generatePermissionInfo(p, flags));
4373                    }
4374                } else {
4375                    if (p.perm != null && group.equals(p.perm.info.group)) {
4376                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4377                    }
4378                }
4379            }
4380            return new ParceledListSlice<>(out);
4381        }
4382    }
4383
4384    @Override
4385    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4386        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4387            return null;
4388        }
4389        // reader
4390        synchronized (mPackages) {
4391            return PackageParser.generatePermissionGroupInfo(
4392                    mPermissionGroups.get(name), flags);
4393        }
4394    }
4395
4396    @Override
4397    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4398        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4399            return ParceledListSlice.emptyList();
4400        }
4401        // reader
4402        synchronized (mPackages) {
4403            final int N = mPermissionGroups.size();
4404            ArrayList<PermissionGroupInfo> out
4405                    = new ArrayList<PermissionGroupInfo>(N);
4406            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4407                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4408            }
4409            return new ParceledListSlice<>(out);
4410        }
4411    }
4412
4413    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4414            int filterCallingUid, int userId) {
4415        if (!sUserManager.exists(userId)) return null;
4416        PackageSetting ps = mSettings.mPackages.get(packageName);
4417        if (ps != null) {
4418            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4419                return null;
4420            }
4421            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4422                return null;
4423            }
4424            if (ps.pkg == null) {
4425                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4426                if (pInfo != null) {
4427                    return pInfo.applicationInfo;
4428                }
4429                return null;
4430            }
4431            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4432                    ps.readUserState(userId), userId);
4433            if (ai != null) {
4434                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4435            }
4436            return ai;
4437        }
4438        return null;
4439    }
4440
4441    @Override
4442    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4443        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4444    }
4445
4446    /**
4447     * Important: The provided filterCallingUid is used exclusively to filter out applications
4448     * that can be seen based on user state. It's typically the original caller uid prior
4449     * to clearing. Because it can only be provided by trusted code, it's value can be
4450     * trusted and will be used as-is; unlike userId which will be validated by this method.
4451     */
4452    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4453            int filterCallingUid, int userId) {
4454        if (!sUserManager.exists(userId)) return null;
4455        flags = updateFlagsForApplication(flags, userId, packageName);
4456        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4457                false /* requireFullPermission */, false /* checkShell */, "get application info");
4458
4459        // writer
4460        synchronized (mPackages) {
4461            // Normalize package name to handle renamed packages and static libs
4462            packageName = resolveInternalPackageNameLPr(packageName,
4463                    PackageManager.VERSION_CODE_HIGHEST);
4464
4465            PackageParser.Package p = mPackages.get(packageName);
4466            if (DEBUG_PACKAGE_INFO) Log.v(
4467                    TAG, "getApplicationInfo " + packageName
4468                    + ": " + p);
4469            if (p != null) {
4470                PackageSetting ps = mSettings.mPackages.get(packageName);
4471                if (ps == null) return null;
4472                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4473                    return null;
4474                }
4475                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4476                    return null;
4477                }
4478                // Note: isEnabledLP() does not apply here - always return info
4479                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4480                        p, flags, ps.readUserState(userId), userId);
4481                if (ai != null) {
4482                    ai.packageName = resolveExternalPackageNameLPr(p);
4483                }
4484                return ai;
4485            }
4486            if ("android".equals(packageName)||"system".equals(packageName)) {
4487                return mAndroidApplication;
4488            }
4489            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4490                // Already generates the external package name
4491                return generateApplicationInfoFromSettingsLPw(packageName,
4492                        flags, filterCallingUid, userId);
4493            }
4494        }
4495        return null;
4496    }
4497
4498    private String normalizePackageNameLPr(String packageName) {
4499        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4500        return normalizedPackageName != null ? normalizedPackageName : packageName;
4501    }
4502
4503    @Override
4504    public void deletePreloadsFileCache() {
4505        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4506            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4507        }
4508        File dir = Environment.getDataPreloadsFileCacheDirectory();
4509        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4510        FileUtils.deleteContents(dir);
4511    }
4512
4513    @Override
4514    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4515            final int storageFlags, final IPackageDataObserver observer) {
4516        mContext.enforceCallingOrSelfPermission(
4517                android.Manifest.permission.CLEAR_APP_CACHE, null);
4518        mHandler.post(() -> {
4519            boolean success = false;
4520            try {
4521                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4522                success = true;
4523            } catch (IOException e) {
4524                Slog.w(TAG, e);
4525            }
4526            if (observer != null) {
4527                try {
4528                    observer.onRemoveCompleted(null, success);
4529                } catch (RemoteException e) {
4530                    Slog.w(TAG, e);
4531                }
4532            }
4533        });
4534    }
4535
4536    @Override
4537    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4538            final int storageFlags, final IntentSender pi) {
4539        mContext.enforceCallingOrSelfPermission(
4540                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4541        mHandler.post(() -> {
4542            boolean success = false;
4543            try {
4544                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4545                success = true;
4546            } catch (IOException e) {
4547                Slog.w(TAG, e);
4548            }
4549            if (pi != null) {
4550                try {
4551                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4552                } catch (SendIntentException e) {
4553                    Slog.w(TAG, e);
4554                }
4555            }
4556        });
4557    }
4558
4559    /**
4560     * Blocking call to clear various types of cached data across the system
4561     * until the requested bytes are available.
4562     */
4563    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4564        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4565        final File file = storage.findPathForUuid(volumeUuid);
4566        if (file.getUsableSpace() >= bytes) return;
4567
4568        if (ENABLE_FREE_CACHE_V2) {
4569            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4570                    volumeUuid);
4571            final boolean aggressive = (storageFlags
4572                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4573            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4574
4575            // 1. Pre-flight to determine if we have any chance to succeed
4576            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4577            if (internalVolume && (aggressive || SystemProperties
4578                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4579                deletePreloadsFileCache();
4580                if (file.getUsableSpace() >= bytes) return;
4581            }
4582
4583            // 3. Consider parsed APK data (aggressive only)
4584            if (internalVolume && aggressive) {
4585                FileUtils.deleteContents(mCacheDir);
4586                if (file.getUsableSpace() >= bytes) return;
4587            }
4588
4589            // 4. Consider cached app data (above quotas)
4590            try {
4591                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4592                        Installer.FLAG_FREE_CACHE_V2);
4593            } catch (InstallerException ignored) {
4594            }
4595            if (file.getUsableSpace() >= bytes) return;
4596
4597            // 5. Consider shared libraries with refcount=0 and age>min cache period
4598            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4599                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4600                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4601                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4602                return;
4603            }
4604
4605            // 6. Consider dexopt output (aggressive only)
4606            // TODO: Implement
4607
4608            // 7. Consider installed instant apps unused longer than min cache period
4609            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4610                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4611                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4612                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4613                return;
4614            }
4615
4616            // 8. Consider cached app data (below quotas)
4617            try {
4618                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4619                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4620            } catch (InstallerException ignored) {
4621            }
4622            if (file.getUsableSpace() >= bytes) return;
4623
4624            // 9. Consider DropBox entries
4625            // TODO: Implement
4626
4627            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4628            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4629                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4630                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4631                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4632                return;
4633            }
4634        } else {
4635            try {
4636                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4637            } catch (InstallerException ignored) {
4638            }
4639            if (file.getUsableSpace() >= bytes) return;
4640        }
4641
4642        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4643    }
4644
4645    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4646            throws IOException {
4647        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4648        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4649
4650        List<VersionedPackage> packagesToDelete = null;
4651        final long now = System.currentTimeMillis();
4652
4653        synchronized (mPackages) {
4654            final int[] allUsers = sUserManager.getUserIds();
4655            final int libCount = mSharedLibraries.size();
4656            for (int i = 0; i < libCount; i++) {
4657                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4658                if (versionedLib == null) {
4659                    continue;
4660                }
4661                final int versionCount = versionedLib.size();
4662                for (int j = 0; j < versionCount; j++) {
4663                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4664                    // Skip packages that are not static shared libs.
4665                    if (!libInfo.isStatic()) {
4666                        break;
4667                    }
4668                    // Important: We skip static shared libs used for some user since
4669                    // in such a case we need to keep the APK on the device. The check for
4670                    // a lib being used for any user is performed by the uninstall call.
4671                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4672                    // Resolve the package name - we use synthetic package names internally
4673                    final String internalPackageName = resolveInternalPackageNameLPr(
4674                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4675                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4676                    // Skip unused static shared libs cached less than the min period
4677                    // to prevent pruning a lib needed by a subsequently installed package.
4678                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4679                        continue;
4680                    }
4681                    if (packagesToDelete == null) {
4682                        packagesToDelete = new ArrayList<>();
4683                    }
4684                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4685                            declaringPackage.getVersionCode()));
4686                }
4687            }
4688        }
4689
4690        if (packagesToDelete != null) {
4691            final int packageCount = packagesToDelete.size();
4692            for (int i = 0; i < packageCount; i++) {
4693                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4694                // Delete the package synchronously (will fail of the lib used for any user).
4695                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4696                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4697                                == PackageManager.DELETE_SUCCEEDED) {
4698                    if (volume.getUsableSpace() >= neededSpace) {
4699                        return true;
4700                    }
4701                }
4702            }
4703        }
4704
4705        return false;
4706    }
4707
4708    /**
4709     * Update given flags based on encryption status of current user.
4710     */
4711    private int updateFlags(int flags, int userId) {
4712        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4713                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4714            // Caller expressed an explicit opinion about what encryption
4715            // aware/unaware components they want to see, so fall through and
4716            // give them what they want
4717        } else {
4718            // Caller expressed no opinion, so match based on user state
4719            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4720                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4721            } else {
4722                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4723            }
4724        }
4725        return flags;
4726    }
4727
4728    private UserManagerInternal getUserManagerInternal() {
4729        if (mUserManagerInternal == null) {
4730            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4731        }
4732        return mUserManagerInternal;
4733    }
4734
4735    private DeviceIdleController.LocalService getDeviceIdleController() {
4736        if (mDeviceIdleController == null) {
4737            mDeviceIdleController =
4738                    LocalServices.getService(DeviceIdleController.LocalService.class);
4739        }
4740        return mDeviceIdleController;
4741    }
4742
4743    /**
4744     * Update given flags when being used to request {@link PackageInfo}.
4745     */
4746    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4747        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4748        boolean triaged = true;
4749        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4750                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4751            // Caller is asking for component details, so they'd better be
4752            // asking for specific encryption matching behavior, or be triaged
4753            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4754                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4755                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4756                triaged = false;
4757            }
4758        }
4759        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4760                | PackageManager.MATCH_SYSTEM_ONLY
4761                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4762            triaged = false;
4763        }
4764        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4765            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4766                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4767                    + Debug.getCallers(5));
4768        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4769                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4770            // If the caller wants all packages and has a restricted profile associated with it,
4771            // then match all users. This is to make sure that launchers that need to access work
4772            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4773            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4774            flags |= PackageManager.MATCH_ANY_USER;
4775        }
4776        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4777            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4778                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4779        }
4780        return updateFlags(flags, userId);
4781    }
4782
4783    /**
4784     * Update given flags when being used to request {@link ApplicationInfo}.
4785     */
4786    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4787        return updateFlagsForPackage(flags, userId, cookie);
4788    }
4789
4790    /**
4791     * Update given flags when being used to request {@link ComponentInfo}.
4792     */
4793    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4794        if (cookie instanceof Intent) {
4795            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4796                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4797            }
4798        }
4799
4800        boolean triaged = true;
4801        // Caller is asking for component details, so they'd better be
4802        // asking for specific encryption matching behavior, or be triaged
4803        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4804                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4805                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4806            triaged = false;
4807        }
4808        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4809            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4810                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4811        }
4812
4813        return updateFlags(flags, userId);
4814    }
4815
4816    /**
4817     * Update given intent when being used to request {@link ResolveInfo}.
4818     */
4819    private Intent updateIntentForResolve(Intent intent) {
4820        if (intent.getSelector() != null) {
4821            intent = intent.getSelector();
4822        }
4823        if (DEBUG_PREFERRED) {
4824            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4825        }
4826        return intent;
4827    }
4828
4829    /**
4830     * Update given flags when being used to request {@link ResolveInfo}.
4831     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4832     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4833     * flag set. However, this flag is only honoured in three circumstances:
4834     * <ul>
4835     * <li>when called from a system process</li>
4836     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4837     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4838     * action and a {@code android.intent.category.BROWSABLE} category</li>
4839     * </ul>
4840     */
4841    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4842        return updateFlagsForResolve(flags, userId, intent, callingUid,
4843                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4844    }
4845    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4846            boolean wantInstantApps) {
4847        return updateFlagsForResolve(flags, userId, intent, callingUid,
4848                wantInstantApps, false /*onlyExposedExplicitly*/);
4849    }
4850    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4851            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4852        // Safe mode means we shouldn't match any third-party components
4853        if (mSafeMode) {
4854            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4855        }
4856        if (getInstantAppPackageName(callingUid) != null) {
4857            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4858            if (onlyExposedExplicitly) {
4859                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4860            }
4861            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4862            flags |= PackageManager.MATCH_INSTANT;
4863        } else {
4864            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4865            final boolean allowMatchInstant =
4866                    (wantInstantApps
4867                            && Intent.ACTION_VIEW.equals(intent.getAction())
4868                            && hasWebURI(intent))
4869                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4870            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4871                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4872            if (!allowMatchInstant) {
4873                flags &= ~PackageManager.MATCH_INSTANT;
4874            }
4875        }
4876        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4877    }
4878
4879    @Override
4880    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4881        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4882    }
4883
4884    /**
4885     * Important: The provided filterCallingUid is used exclusively to filter out activities
4886     * that can be seen based on user state. It's typically the original caller uid prior
4887     * to clearing. Because it can only be provided by trusted code, it's value can be
4888     * trusted and will be used as-is; unlike userId which will be validated by this method.
4889     */
4890    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4891            int filterCallingUid, int userId) {
4892        if (!sUserManager.exists(userId)) return null;
4893        flags = updateFlagsForComponent(flags, userId, component);
4894        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4895                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4896        synchronized (mPackages) {
4897            PackageParser.Activity a = mActivities.mActivities.get(component);
4898
4899            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4900            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4901                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4902                if (ps == null) return null;
4903                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4904                    return null;
4905                }
4906                return PackageParser.generateActivityInfo(
4907                        a, flags, ps.readUserState(userId), userId);
4908            }
4909            if (mResolveComponentName.equals(component)) {
4910                return PackageParser.generateActivityInfo(
4911                        mResolveActivity, flags, new PackageUserState(), userId);
4912            }
4913        }
4914        return null;
4915    }
4916
4917    @Override
4918    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4919            String resolvedType) {
4920        synchronized (mPackages) {
4921            if (component.equals(mResolveComponentName)) {
4922                // The resolver supports EVERYTHING!
4923                return true;
4924            }
4925            final int callingUid = Binder.getCallingUid();
4926            final int callingUserId = UserHandle.getUserId(callingUid);
4927            PackageParser.Activity a = mActivities.mActivities.get(component);
4928            if (a == null) {
4929                return false;
4930            }
4931            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4932            if (ps == null) {
4933                return false;
4934            }
4935            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4936                return false;
4937            }
4938            for (int i=0; i<a.intents.size(); i++) {
4939                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4940                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4941                    return true;
4942                }
4943            }
4944            return false;
4945        }
4946    }
4947
4948    @Override
4949    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4950        if (!sUserManager.exists(userId)) return null;
4951        final int callingUid = Binder.getCallingUid();
4952        flags = updateFlagsForComponent(flags, userId, component);
4953        enforceCrossUserPermission(callingUid, userId,
4954                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4955        synchronized (mPackages) {
4956            PackageParser.Activity a = mReceivers.mActivities.get(component);
4957            if (DEBUG_PACKAGE_INFO) Log.v(
4958                TAG, "getReceiverInfo " + component + ": " + a);
4959            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4960                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4961                if (ps == null) return null;
4962                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4963                    return null;
4964                }
4965                return PackageParser.generateActivityInfo(
4966                        a, flags, ps.readUserState(userId), userId);
4967            }
4968        }
4969        return null;
4970    }
4971
4972    @Override
4973    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4974            int flags, int userId) {
4975        if (!sUserManager.exists(userId)) return null;
4976        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4977        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4978            return null;
4979        }
4980
4981        flags = updateFlagsForPackage(flags, userId, null);
4982
4983        final boolean canSeeStaticLibraries =
4984                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4985                        == PERMISSION_GRANTED
4986                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4987                        == PERMISSION_GRANTED
4988                || canRequestPackageInstallsInternal(packageName,
4989                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4990                        false  /* throwIfPermNotDeclared*/)
4991                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4992                        == PERMISSION_GRANTED;
4993
4994        synchronized (mPackages) {
4995            List<SharedLibraryInfo> result = null;
4996
4997            final int libCount = mSharedLibraries.size();
4998            for (int i = 0; i < libCount; i++) {
4999                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5000                if (versionedLib == null) {
5001                    continue;
5002                }
5003
5004                final int versionCount = versionedLib.size();
5005                for (int j = 0; j < versionCount; j++) {
5006                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5007                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5008                        break;
5009                    }
5010                    final long identity = Binder.clearCallingIdentity();
5011                    try {
5012                        PackageInfo packageInfo = getPackageInfoVersioned(
5013                                libInfo.getDeclaringPackage(), flags
5014                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5015                        if (packageInfo == null) {
5016                            continue;
5017                        }
5018                    } finally {
5019                        Binder.restoreCallingIdentity(identity);
5020                    }
5021
5022                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5023                            libInfo.getVersion(), libInfo.getType(),
5024                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5025                            flags, userId));
5026
5027                    if (result == null) {
5028                        result = new ArrayList<>();
5029                    }
5030                    result.add(resLibInfo);
5031                }
5032            }
5033
5034            return result != null ? new ParceledListSlice<>(result) : null;
5035        }
5036    }
5037
5038    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5039            SharedLibraryInfo libInfo, int flags, int userId) {
5040        List<VersionedPackage> versionedPackages = null;
5041        final int packageCount = mSettings.mPackages.size();
5042        for (int i = 0; i < packageCount; i++) {
5043            PackageSetting ps = mSettings.mPackages.valueAt(i);
5044
5045            if (ps == null) {
5046                continue;
5047            }
5048
5049            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5050                continue;
5051            }
5052
5053            final String libName = libInfo.getName();
5054            if (libInfo.isStatic()) {
5055                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5056                if (libIdx < 0) {
5057                    continue;
5058                }
5059                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5060                    continue;
5061                }
5062                if (versionedPackages == null) {
5063                    versionedPackages = new ArrayList<>();
5064                }
5065                // If the dependent is a static shared lib, use the public package name
5066                String dependentPackageName = ps.name;
5067                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5068                    dependentPackageName = ps.pkg.manifestPackageName;
5069                }
5070                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5071            } else if (ps.pkg != null) {
5072                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5073                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5074                    if (versionedPackages == null) {
5075                        versionedPackages = new ArrayList<>();
5076                    }
5077                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5078                }
5079            }
5080        }
5081
5082        return versionedPackages;
5083    }
5084
5085    @Override
5086    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5087        if (!sUserManager.exists(userId)) return null;
5088        final int callingUid = Binder.getCallingUid();
5089        flags = updateFlagsForComponent(flags, userId, component);
5090        enforceCrossUserPermission(callingUid, userId,
5091                false /* requireFullPermission */, false /* checkShell */, "get service info");
5092        synchronized (mPackages) {
5093            PackageParser.Service s = mServices.mServices.get(component);
5094            if (DEBUG_PACKAGE_INFO) Log.v(
5095                TAG, "getServiceInfo " + component + ": " + s);
5096            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5097                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5098                if (ps == null) return null;
5099                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5100                    return null;
5101                }
5102                return PackageParser.generateServiceInfo(
5103                        s, flags, ps.readUserState(userId), userId);
5104            }
5105        }
5106        return null;
5107    }
5108
5109    @Override
5110    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5111        if (!sUserManager.exists(userId)) return null;
5112        final int callingUid = Binder.getCallingUid();
5113        flags = updateFlagsForComponent(flags, userId, component);
5114        enforceCrossUserPermission(callingUid, userId,
5115                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5116        synchronized (mPackages) {
5117            PackageParser.Provider p = mProviders.mProviders.get(component);
5118            if (DEBUG_PACKAGE_INFO) Log.v(
5119                TAG, "getProviderInfo " + component + ": " + p);
5120            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5121                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5122                if (ps == null) return null;
5123                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5124                    return null;
5125                }
5126                return PackageParser.generateProviderInfo(
5127                        p, flags, ps.readUserState(userId), userId);
5128            }
5129        }
5130        return null;
5131    }
5132
5133    @Override
5134    public String[] getSystemSharedLibraryNames() {
5135        // allow instant applications
5136        synchronized (mPackages) {
5137            Set<String> libs = null;
5138            final int libCount = mSharedLibraries.size();
5139            for (int i = 0; i < libCount; i++) {
5140                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5141                if (versionedLib == null) {
5142                    continue;
5143                }
5144                final int versionCount = versionedLib.size();
5145                for (int j = 0; j < versionCount; j++) {
5146                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5147                    if (!libEntry.info.isStatic()) {
5148                        if (libs == null) {
5149                            libs = new ArraySet<>();
5150                        }
5151                        libs.add(libEntry.info.getName());
5152                        break;
5153                    }
5154                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5155                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5156                            UserHandle.getUserId(Binder.getCallingUid()),
5157                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5158                        if (libs == null) {
5159                            libs = new ArraySet<>();
5160                        }
5161                        libs.add(libEntry.info.getName());
5162                        break;
5163                    }
5164                }
5165            }
5166
5167            if (libs != null) {
5168                String[] libsArray = new String[libs.size()];
5169                libs.toArray(libsArray);
5170                return libsArray;
5171            }
5172
5173            return null;
5174        }
5175    }
5176
5177    @Override
5178    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5179        // allow instant applications
5180        synchronized (mPackages) {
5181            return mServicesSystemSharedLibraryPackageName;
5182        }
5183    }
5184
5185    @Override
5186    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5187        // allow instant applications
5188        synchronized (mPackages) {
5189            return mSharedSystemSharedLibraryPackageName;
5190        }
5191    }
5192
5193    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5194        for (int i = userList.length - 1; i >= 0; --i) {
5195            final int userId = userList[i];
5196            // don't add instant app to the list of updates
5197            if (pkgSetting.getInstantApp(userId)) {
5198                continue;
5199            }
5200            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5201            if (changedPackages == null) {
5202                changedPackages = new SparseArray<>();
5203                mChangedPackages.put(userId, changedPackages);
5204            }
5205            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5206            if (sequenceNumbers == null) {
5207                sequenceNumbers = new HashMap<>();
5208                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5209            }
5210            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5211            if (sequenceNumber != null) {
5212                changedPackages.remove(sequenceNumber);
5213            }
5214            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5215            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5216        }
5217        mChangedPackagesSequenceNumber++;
5218    }
5219
5220    @Override
5221    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5222        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5223            return null;
5224        }
5225        synchronized (mPackages) {
5226            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5227                return null;
5228            }
5229            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5230            if (changedPackages == null) {
5231                return null;
5232            }
5233            final List<String> packageNames =
5234                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5235            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5236                final String packageName = changedPackages.get(i);
5237                if (packageName != null) {
5238                    packageNames.add(packageName);
5239                }
5240            }
5241            return packageNames.isEmpty()
5242                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5243        }
5244    }
5245
5246    @Override
5247    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5248        // allow instant applications
5249        ArrayList<FeatureInfo> res;
5250        synchronized (mAvailableFeatures) {
5251            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5252            res.addAll(mAvailableFeatures.values());
5253        }
5254        final FeatureInfo fi = new FeatureInfo();
5255        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5256                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5257        res.add(fi);
5258
5259        return new ParceledListSlice<>(res);
5260    }
5261
5262    @Override
5263    public boolean hasSystemFeature(String name, int version) {
5264        // allow instant applications
5265        synchronized (mAvailableFeatures) {
5266            final FeatureInfo feat = mAvailableFeatures.get(name);
5267            if (feat == null) {
5268                return false;
5269            } else {
5270                return feat.version >= version;
5271            }
5272        }
5273    }
5274
5275    @Override
5276    public int checkPermission(String permName, String pkgName, int userId) {
5277        if (!sUserManager.exists(userId)) {
5278            return PackageManager.PERMISSION_DENIED;
5279        }
5280        final int callingUid = Binder.getCallingUid();
5281
5282        synchronized (mPackages) {
5283            final PackageParser.Package p = mPackages.get(pkgName);
5284            if (p != null && p.mExtras != null) {
5285                final PackageSetting ps = (PackageSetting) p.mExtras;
5286                if (filterAppAccessLPr(ps, callingUid, userId)) {
5287                    return PackageManager.PERMISSION_DENIED;
5288                }
5289                final boolean instantApp = ps.getInstantApp(userId);
5290                final PermissionsState permissionsState = ps.getPermissionsState();
5291                if (permissionsState.hasPermission(permName, userId)) {
5292                    if (instantApp) {
5293                        BasePermission bp = mSettings.mPermissions.get(permName);
5294                        if (bp != null && bp.isInstant()) {
5295                            return PackageManager.PERMISSION_GRANTED;
5296                        }
5297                    } else {
5298                        return PackageManager.PERMISSION_GRANTED;
5299                    }
5300                }
5301                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5302                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5303                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5304                    return PackageManager.PERMISSION_GRANTED;
5305                }
5306            }
5307        }
5308
5309        return PackageManager.PERMISSION_DENIED;
5310    }
5311
5312    @Override
5313    public int checkUidPermission(String permName, int uid) {
5314        final int callingUid = Binder.getCallingUid();
5315        final int callingUserId = UserHandle.getUserId(callingUid);
5316        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5317        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5318        final int userId = UserHandle.getUserId(uid);
5319        if (!sUserManager.exists(userId)) {
5320            return PackageManager.PERMISSION_DENIED;
5321        }
5322
5323        synchronized (mPackages) {
5324            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5325            if (obj != null) {
5326                if (obj instanceof SharedUserSetting) {
5327                    if (isCallerInstantApp) {
5328                        return PackageManager.PERMISSION_DENIED;
5329                    }
5330                } else if (obj instanceof PackageSetting) {
5331                    final PackageSetting ps = (PackageSetting) obj;
5332                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5333                        return PackageManager.PERMISSION_DENIED;
5334                    }
5335                }
5336                final SettingBase settingBase = (SettingBase) obj;
5337                final PermissionsState permissionsState = settingBase.getPermissionsState();
5338                if (permissionsState.hasPermission(permName, userId)) {
5339                    if (isUidInstantApp) {
5340                        BasePermission bp = mSettings.mPermissions.get(permName);
5341                        if (bp != null && bp.isInstant()) {
5342                            return PackageManager.PERMISSION_GRANTED;
5343                        }
5344                    } else {
5345                        return PackageManager.PERMISSION_GRANTED;
5346                    }
5347                }
5348                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5349                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5350                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5351                    return PackageManager.PERMISSION_GRANTED;
5352                }
5353            } else {
5354                ArraySet<String> perms = mSystemPermissions.get(uid);
5355                if (perms != null) {
5356                    if (perms.contains(permName)) {
5357                        return PackageManager.PERMISSION_GRANTED;
5358                    }
5359                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5360                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5361                        return PackageManager.PERMISSION_GRANTED;
5362                    }
5363                }
5364            }
5365        }
5366
5367        return PackageManager.PERMISSION_DENIED;
5368    }
5369
5370    @Override
5371    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5372        if (UserHandle.getCallingUserId() != userId) {
5373            mContext.enforceCallingPermission(
5374                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5375                    "isPermissionRevokedByPolicy for user " + userId);
5376        }
5377
5378        if (checkPermission(permission, packageName, userId)
5379                == PackageManager.PERMISSION_GRANTED) {
5380            return false;
5381        }
5382
5383        final int callingUid = Binder.getCallingUid();
5384        if (getInstantAppPackageName(callingUid) != null) {
5385            if (!isCallerSameApp(packageName, callingUid)) {
5386                return false;
5387            }
5388        } else {
5389            if (isInstantApp(packageName, userId)) {
5390                return false;
5391            }
5392        }
5393
5394        final long identity = Binder.clearCallingIdentity();
5395        try {
5396            final int flags = getPermissionFlags(permission, packageName, userId);
5397            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5398        } finally {
5399            Binder.restoreCallingIdentity(identity);
5400        }
5401    }
5402
5403    @Override
5404    public String getPermissionControllerPackageName() {
5405        synchronized (mPackages) {
5406            return mRequiredInstallerPackage;
5407        }
5408    }
5409
5410    /**
5411     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5412     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5413     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5414     * @param message the message to log on security exception
5415     */
5416    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5417            boolean checkShell, String message) {
5418        if (userId < 0) {
5419            throw new IllegalArgumentException("Invalid userId " + userId);
5420        }
5421        if (checkShell) {
5422            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5423        }
5424        if (userId == UserHandle.getUserId(callingUid)) return;
5425        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5426            if (requireFullPermission) {
5427                mContext.enforceCallingOrSelfPermission(
5428                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5429            } else {
5430                try {
5431                    mContext.enforceCallingOrSelfPermission(
5432                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5433                } catch (SecurityException se) {
5434                    mContext.enforceCallingOrSelfPermission(
5435                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5436                }
5437            }
5438        }
5439    }
5440
5441    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5442        if (callingUid == Process.SHELL_UID) {
5443            if (userHandle >= 0
5444                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5445                throw new SecurityException("Shell does not have permission to access user "
5446                        + userHandle);
5447            } else if (userHandle < 0) {
5448                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5449                        + Debug.getCallers(3));
5450            }
5451        }
5452    }
5453
5454    private BasePermission findPermissionTreeLP(String permName) {
5455        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5456            if (permName.startsWith(bp.name) &&
5457                    permName.length() > bp.name.length() &&
5458                    permName.charAt(bp.name.length()) == '.') {
5459                return bp;
5460            }
5461        }
5462        return null;
5463    }
5464
5465    private BasePermission checkPermissionTreeLP(String permName) {
5466        if (permName != null) {
5467            BasePermission bp = findPermissionTreeLP(permName);
5468            if (bp != null) {
5469                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5470                    return bp;
5471                }
5472                throw new SecurityException("Calling uid "
5473                        + Binder.getCallingUid()
5474                        + " is not allowed to add to permission tree "
5475                        + bp.name + " owned by uid " + bp.uid);
5476            }
5477        }
5478        throw new SecurityException("No permission tree found for " + permName);
5479    }
5480
5481    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5482        if (s1 == null) {
5483            return s2 == null;
5484        }
5485        if (s2 == null) {
5486            return false;
5487        }
5488        if (s1.getClass() != s2.getClass()) {
5489            return false;
5490        }
5491        return s1.equals(s2);
5492    }
5493
5494    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5495        if (pi1.icon != pi2.icon) return false;
5496        if (pi1.logo != pi2.logo) return false;
5497        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5498        if (!compareStrings(pi1.name, pi2.name)) return false;
5499        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5500        // We'll take care of setting this one.
5501        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5502        // These are not currently stored in settings.
5503        //if (!compareStrings(pi1.group, pi2.group)) return false;
5504        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5505        //if (pi1.labelRes != pi2.labelRes) return false;
5506        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5507        return true;
5508    }
5509
5510    int permissionInfoFootprint(PermissionInfo info) {
5511        int size = info.name.length();
5512        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5513        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5514        return size;
5515    }
5516
5517    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5518        int size = 0;
5519        for (BasePermission perm : mSettings.mPermissions.values()) {
5520            if (perm.uid == tree.uid) {
5521                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5522            }
5523        }
5524        return size;
5525    }
5526
5527    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5528        // We calculate the max size of permissions defined by this uid and throw
5529        // if that plus the size of 'info' would exceed our stated maximum.
5530        if (tree.uid != Process.SYSTEM_UID) {
5531            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5532            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5533                throw new SecurityException("Permission tree size cap exceeded");
5534            }
5535        }
5536    }
5537
5538    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5539        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5540            throw new SecurityException("Instant apps can't add permissions");
5541        }
5542        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5543            throw new SecurityException("Label must be specified in permission");
5544        }
5545        BasePermission tree = checkPermissionTreeLP(info.name);
5546        BasePermission bp = mSettings.mPermissions.get(info.name);
5547        boolean added = bp == null;
5548        boolean changed = true;
5549        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5550        if (added) {
5551            enforcePermissionCapLocked(info, tree);
5552            bp = new BasePermission(info.name, tree.sourcePackage,
5553                    BasePermission.TYPE_DYNAMIC);
5554        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5555            throw new SecurityException(
5556                    "Not allowed to modify non-dynamic permission "
5557                    + info.name);
5558        } else {
5559            if (bp.protectionLevel == fixedLevel
5560                    && bp.perm.owner.equals(tree.perm.owner)
5561                    && bp.uid == tree.uid
5562                    && comparePermissionInfos(bp.perm.info, info)) {
5563                changed = false;
5564            }
5565        }
5566        bp.protectionLevel = fixedLevel;
5567        info = new PermissionInfo(info);
5568        info.protectionLevel = fixedLevel;
5569        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5570        bp.perm.info.packageName = tree.perm.info.packageName;
5571        bp.uid = tree.uid;
5572        if (added) {
5573            mSettings.mPermissions.put(info.name, bp);
5574        }
5575        if (changed) {
5576            if (!async) {
5577                mSettings.writeLPr();
5578            } else {
5579                scheduleWriteSettingsLocked();
5580            }
5581        }
5582        return added;
5583    }
5584
5585    @Override
5586    public boolean addPermission(PermissionInfo info) {
5587        synchronized (mPackages) {
5588            return addPermissionLocked(info, false);
5589        }
5590    }
5591
5592    @Override
5593    public boolean addPermissionAsync(PermissionInfo info) {
5594        synchronized (mPackages) {
5595            return addPermissionLocked(info, true);
5596        }
5597    }
5598
5599    @Override
5600    public void removePermission(String name) {
5601        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5602            throw new SecurityException("Instant applications don't have access to this method");
5603        }
5604        synchronized (mPackages) {
5605            checkPermissionTreeLP(name);
5606            BasePermission bp = mSettings.mPermissions.get(name);
5607            if (bp != null) {
5608                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5609                    throw new SecurityException(
5610                            "Not allowed to modify non-dynamic permission "
5611                            + name);
5612                }
5613                mSettings.mPermissions.remove(name);
5614                mSettings.writeLPr();
5615            }
5616        }
5617    }
5618
5619    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5620            PackageParser.Package pkg, BasePermission bp) {
5621        int index = pkg.requestedPermissions.indexOf(bp.name);
5622        if (index == -1) {
5623            throw new SecurityException("Package " + pkg.packageName
5624                    + " has not requested permission " + bp.name);
5625        }
5626        if (!bp.isRuntime() && !bp.isDevelopment()) {
5627            throw new SecurityException("Permission " + bp.name
5628                    + " is not a changeable permission type");
5629        }
5630    }
5631
5632    @Override
5633    public void grantRuntimePermission(String packageName, String name, final int userId) {
5634        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5635    }
5636
5637    private void grantRuntimePermission(String packageName, String name, final int userId,
5638            boolean overridePolicy) {
5639        if (!sUserManager.exists(userId)) {
5640            Log.e(TAG, "No such user:" + userId);
5641            return;
5642        }
5643        final int callingUid = Binder.getCallingUid();
5644
5645        mContext.enforceCallingOrSelfPermission(
5646                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5647                "grantRuntimePermission");
5648
5649        enforceCrossUserPermission(callingUid, userId,
5650                true /* requireFullPermission */, true /* checkShell */,
5651                "grantRuntimePermission");
5652
5653        final int uid;
5654        final PackageSetting ps;
5655
5656        synchronized (mPackages) {
5657            final PackageParser.Package pkg = mPackages.get(packageName);
5658            if (pkg == null) {
5659                throw new IllegalArgumentException("Unknown package: " + packageName);
5660            }
5661            final BasePermission bp = mSettings.mPermissions.get(name);
5662            if (bp == null) {
5663                throw new IllegalArgumentException("Unknown permission: " + name);
5664            }
5665            ps = (PackageSetting) pkg.mExtras;
5666            if (ps == null
5667                    || filterAppAccessLPr(ps, callingUid, userId)) {
5668                throw new IllegalArgumentException("Unknown package: " + packageName);
5669            }
5670
5671            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5672
5673            // If a permission review is required for legacy apps we represent
5674            // their permissions as always granted runtime ones since we need
5675            // to keep the review required permission flag per user while an
5676            // install permission's state is shared across all users.
5677            if (mPermissionReviewRequired
5678                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5679                    && bp.isRuntime()) {
5680                return;
5681            }
5682
5683            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5684
5685            final PermissionsState permissionsState = ps.getPermissionsState();
5686
5687            final int flags = permissionsState.getPermissionFlags(name, userId);
5688            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5689                throw new SecurityException("Cannot grant system fixed permission "
5690                        + name + " for package " + packageName);
5691            }
5692            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5693                throw new SecurityException("Cannot grant policy fixed permission "
5694                        + name + " for package " + packageName);
5695            }
5696
5697            if (bp.isDevelopment()) {
5698                // Development permissions must be handled specially, since they are not
5699                // normal runtime permissions.  For now they apply to all users.
5700                if (permissionsState.grantInstallPermission(bp) !=
5701                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5702                    scheduleWriteSettingsLocked();
5703                }
5704                return;
5705            }
5706
5707            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5708                throw new SecurityException("Cannot grant non-ephemeral permission"
5709                        + name + " for package " + packageName);
5710            }
5711
5712            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5713                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5714                return;
5715            }
5716
5717            final int result = permissionsState.grantRuntimePermission(bp, userId);
5718            switch (result) {
5719                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5720                    return;
5721                }
5722
5723                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5724                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5725                    mHandler.post(new Runnable() {
5726                        @Override
5727                        public void run() {
5728                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5729                        }
5730                    });
5731                }
5732                break;
5733            }
5734
5735            if (bp.isRuntime()) {
5736                logPermissionGranted(mContext, name, packageName);
5737            }
5738
5739            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5740
5741            // Not critical if that is lost - app has to request again.
5742            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5743        }
5744
5745        // Only need to do this if user is initialized. Otherwise it's a new user
5746        // and there are no processes running as the user yet and there's no need
5747        // to make an expensive call to remount processes for the changed permissions.
5748        if (READ_EXTERNAL_STORAGE.equals(name)
5749                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5750            final long token = Binder.clearCallingIdentity();
5751            try {
5752                if (sUserManager.isInitialized(userId)) {
5753                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5754                            StorageManagerInternal.class);
5755                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5756                }
5757            } finally {
5758                Binder.restoreCallingIdentity(token);
5759            }
5760        }
5761    }
5762
5763    @Override
5764    public void revokeRuntimePermission(String packageName, String name, int userId) {
5765        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5766    }
5767
5768    private void revokeRuntimePermission(String packageName, String name, int userId,
5769            boolean overridePolicy) {
5770        if (!sUserManager.exists(userId)) {
5771            Log.e(TAG, "No such user:" + userId);
5772            return;
5773        }
5774
5775        mContext.enforceCallingOrSelfPermission(
5776                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5777                "revokeRuntimePermission");
5778
5779        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5780                true /* requireFullPermission */, true /* checkShell */,
5781                "revokeRuntimePermission");
5782
5783        final int appId;
5784
5785        synchronized (mPackages) {
5786            final PackageParser.Package pkg = mPackages.get(packageName);
5787            if (pkg == null) {
5788                throw new IllegalArgumentException("Unknown package: " + packageName);
5789            }
5790            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5791            if (ps == null
5792                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5793                throw new IllegalArgumentException("Unknown package: " + packageName);
5794            }
5795            final BasePermission bp = mSettings.mPermissions.get(name);
5796            if (bp == null) {
5797                throw new IllegalArgumentException("Unknown permission: " + name);
5798            }
5799
5800            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5801
5802            // If a permission review is required for legacy apps we represent
5803            // their permissions as always granted runtime ones since we need
5804            // to keep the review required permission flag per user while an
5805            // install permission's state is shared across all users.
5806            if (mPermissionReviewRequired
5807                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5808                    && bp.isRuntime()) {
5809                return;
5810            }
5811
5812            final PermissionsState permissionsState = ps.getPermissionsState();
5813
5814            final int flags = permissionsState.getPermissionFlags(name, userId);
5815            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5816                throw new SecurityException("Cannot revoke system fixed permission "
5817                        + name + " for package " + packageName);
5818            }
5819            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5820                throw new SecurityException("Cannot revoke policy fixed permission "
5821                        + name + " for package " + packageName);
5822            }
5823
5824            if (bp.isDevelopment()) {
5825                // Development permissions must be handled specially, since they are not
5826                // normal runtime permissions.  For now they apply to all users.
5827                if (permissionsState.revokeInstallPermission(bp) !=
5828                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5829                    scheduleWriteSettingsLocked();
5830                }
5831                return;
5832            }
5833
5834            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5835                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5836                return;
5837            }
5838
5839            if (bp.isRuntime()) {
5840                logPermissionRevoked(mContext, name, packageName);
5841            }
5842
5843            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5844
5845            // Critical, after this call app should never have the permission.
5846            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5847
5848            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5849        }
5850
5851        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5852    }
5853
5854    /**
5855     * Get the first event id for the permission.
5856     *
5857     * <p>There are four events for each permission: <ul>
5858     *     <li>Request permission: first id + 0</li>
5859     *     <li>Grant permission: first id + 1</li>
5860     *     <li>Request for permission denied: first id + 2</li>
5861     *     <li>Revoke permission: first id + 3</li>
5862     * </ul></p>
5863     *
5864     * @param name name of the permission
5865     *
5866     * @return The first event id for the permission
5867     */
5868    private static int getBaseEventId(@NonNull String name) {
5869        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5870
5871        if (eventIdIndex == -1) {
5872            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5873                    || Build.IS_USER) {
5874                Log.i(TAG, "Unknown permission " + name);
5875
5876                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5877            } else {
5878                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5879                //
5880                // Also update
5881                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5882                // - metrics_constants.proto
5883                throw new IllegalStateException("Unknown permission " + name);
5884            }
5885        }
5886
5887        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5888    }
5889
5890    /**
5891     * Log that a permission was revoked.
5892     *
5893     * @param context Context of the caller
5894     * @param name name of the permission
5895     * @param packageName package permission if for
5896     */
5897    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5898            @NonNull String packageName) {
5899        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5900    }
5901
5902    /**
5903     * Log that a permission request was granted.
5904     *
5905     * @param context Context of the caller
5906     * @param name name of the permission
5907     * @param packageName package permission if for
5908     */
5909    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5910            @NonNull String packageName) {
5911        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5912    }
5913
5914    @Override
5915    public void resetRuntimePermissions() {
5916        mContext.enforceCallingOrSelfPermission(
5917                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5918                "revokeRuntimePermission");
5919
5920        int callingUid = Binder.getCallingUid();
5921        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5922            mContext.enforceCallingOrSelfPermission(
5923                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5924                    "resetRuntimePermissions");
5925        }
5926
5927        synchronized (mPackages) {
5928            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5929            for (int userId : UserManagerService.getInstance().getUserIds()) {
5930                final int packageCount = mPackages.size();
5931                for (int i = 0; i < packageCount; i++) {
5932                    PackageParser.Package pkg = mPackages.valueAt(i);
5933                    if (!(pkg.mExtras instanceof PackageSetting)) {
5934                        continue;
5935                    }
5936                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5937                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5938                }
5939            }
5940        }
5941    }
5942
5943    @Override
5944    public int getPermissionFlags(String name, String packageName, int userId) {
5945        if (!sUserManager.exists(userId)) {
5946            return 0;
5947        }
5948
5949        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5950
5951        final int callingUid = Binder.getCallingUid();
5952        enforceCrossUserPermission(callingUid, userId,
5953                true /* requireFullPermission */, false /* checkShell */,
5954                "getPermissionFlags");
5955
5956        synchronized (mPackages) {
5957            final PackageParser.Package pkg = mPackages.get(packageName);
5958            if (pkg == null) {
5959                return 0;
5960            }
5961            final BasePermission bp = mSettings.mPermissions.get(name);
5962            if (bp == null) {
5963                return 0;
5964            }
5965            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5966            if (ps == null
5967                    || filterAppAccessLPr(ps, callingUid, userId)) {
5968                return 0;
5969            }
5970            PermissionsState permissionsState = ps.getPermissionsState();
5971            return permissionsState.getPermissionFlags(name, userId);
5972        }
5973    }
5974
5975    @Override
5976    public void updatePermissionFlags(String name, String packageName, int flagMask,
5977            int flagValues, int userId) {
5978        if (!sUserManager.exists(userId)) {
5979            return;
5980        }
5981
5982        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5983
5984        final int callingUid = Binder.getCallingUid();
5985        enforceCrossUserPermission(callingUid, userId,
5986                true /* requireFullPermission */, true /* checkShell */,
5987                "updatePermissionFlags");
5988
5989        // Only the system can change these flags and nothing else.
5990        if (getCallingUid() != Process.SYSTEM_UID) {
5991            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5992            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5993            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5994            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5995            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5996        }
5997
5998        synchronized (mPackages) {
5999            final PackageParser.Package pkg = mPackages.get(packageName);
6000            if (pkg == null) {
6001                throw new IllegalArgumentException("Unknown package: " + packageName);
6002            }
6003            final PackageSetting ps = (PackageSetting) pkg.mExtras;
6004            if (ps == null
6005                    || filterAppAccessLPr(ps, callingUid, userId)) {
6006                throw new IllegalArgumentException("Unknown package: " + packageName);
6007            }
6008
6009            final BasePermission bp = mSettings.mPermissions.get(name);
6010            if (bp == null) {
6011                throw new IllegalArgumentException("Unknown permission: " + name);
6012            }
6013
6014            PermissionsState permissionsState = ps.getPermissionsState();
6015
6016            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6017
6018            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6019                // Install and runtime permissions are stored in different places,
6020                // so figure out what permission changed and persist the change.
6021                if (permissionsState.getInstallPermissionState(name) != null) {
6022                    scheduleWriteSettingsLocked();
6023                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6024                        || hadState) {
6025                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6026                }
6027            }
6028        }
6029    }
6030
6031    /**
6032     * Update the permission flags for all packages and runtime permissions of a user in order
6033     * to allow device or profile owner to remove POLICY_FIXED.
6034     */
6035    @Override
6036    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6037        if (!sUserManager.exists(userId)) {
6038            return;
6039        }
6040
6041        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6042
6043        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6044                true /* requireFullPermission */, true /* checkShell */,
6045                "updatePermissionFlagsForAllApps");
6046
6047        // Only the system can change system fixed flags.
6048        if (getCallingUid() != Process.SYSTEM_UID) {
6049            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6050            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6051        }
6052
6053        synchronized (mPackages) {
6054            boolean changed = false;
6055            final int packageCount = mPackages.size();
6056            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6057                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6058                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6059                if (ps == null) {
6060                    continue;
6061                }
6062                PermissionsState permissionsState = ps.getPermissionsState();
6063                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6064                        userId, flagMask, flagValues);
6065            }
6066            if (changed) {
6067                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6068            }
6069        }
6070    }
6071
6072    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6073        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6074                != PackageManager.PERMISSION_GRANTED
6075            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6076                != PackageManager.PERMISSION_GRANTED) {
6077            throw new SecurityException(message + " requires "
6078                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6079                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6080        }
6081    }
6082
6083    @Override
6084    public boolean shouldShowRequestPermissionRationale(String permissionName,
6085            String packageName, int userId) {
6086        if (UserHandle.getCallingUserId() != userId) {
6087            mContext.enforceCallingPermission(
6088                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6089                    "canShowRequestPermissionRationale for user " + userId);
6090        }
6091
6092        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6093        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6094            return false;
6095        }
6096
6097        if (checkPermission(permissionName, packageName, userId)
6098                == PackageManager.PERMISSION_GRANTED) {
6099            return false;
6100        }
6101
6102        final int flags;
6103
6104        final long identity = Binder.clearCallingIdentity();
6105        try {
6106            flags = getPermissionFlags(permissionName,
6107                    packageName, userId);
6108        } finally {
6109            Binder.restoreCallingIdentity(identity);
6110        }
6111
6112        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6113                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6114                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6115
6116        if ((flags & fixedFlags) != 0) {
6117            return false;
6118        }
6119
6120        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6121    }
6122
6123    @Override
6124    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6125        mContext.enforceCallingOrSelfPermission(
6126                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6127                "addOnPermissionsChangeListener");
6128
6129        synchronized (mPackages) {
6130            mOnPermissionChangeListeners.addListenerLocked(listener);
6131        }
6132    }
6133
6134    @Override
6135    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6136        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6137            throw new SecurityException("Instant applications don't have access to this method");
6138        }
6139        synchronized (mPackages) {
6140            mOnPermissionChangeListeners.removeListenerLocked(listener);
6141        }
6142    }
6143
6144    @Override
6145    public boolean isProtectedBroadcast(String actionName) {
6146        // allow instant applications
6147        synchronized (mProtectedBroadcasts) {
6148            if (mProtectedBroadcasts.contains(actionName)) {
6149                return true;
6150            } else if (actionName != null) {
6151                // TODO: remove these terrible hacks
6152                if (actionName.startsWith("android.net.netmon.lingerExpired")
6153                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6154                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6155                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6156                    return true;
6157                }
6158            }
6159        }
6160        return false;
6161    }
6162
6163    @Override
6164    public int checkSignatures(String pkg1, String pkg2) {
6165        synchronized (mPackages) {
6166            final PackageParser.Package p1 = mPackages.get(pkg1);
6167            final PackageParser.Package p2 = mPackages.get(pkg2);
6168            if (p1 == null || p1.mExtras == null
6169                    || p2 == null || p2.mExtras == null) {
6170                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6171            }
6172            final int callingUid = Binder.getCallingUid();
6173            final int callingUserId = UserHandle.getUserId(callingUid);
6174            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6175            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6176            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6177                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6178                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6179            }
6180            return compareSignatures(p1.mSignatures, p2.mSignatures);
6181        }
6182    }
6183
6184    @Override
6185    public int checkUidSignatures(int uid1, int uid2) {
6186        final int callingUid = Binder.getCallingUid();
6187        final int callingUserId = UserHandle.getUserId(callingUid);
6188        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6189        // Map to base uids.
6190        uid1 = UserHandle.getAppId(uid1);
6191        uid2 = UserHandle.getAppId(uid2);
6192        // reader
6193        synchronized (mPackages) {
6194            Signature[] s1;
6195            Signature[] s2;
6196            Object obj = mSettings.getUserIdLPr(uid1);
6197            if (obj != null) {
6198                if (obj instanceof SharedUserSetting) {
6199                    if (isCallerInstantApp) {
6200                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6201                    }
6202                    s1 = ((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                    s1 = ps.signatures.mSignatures;
6209                } else {
6210                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6211                }
6212            } else {
6213                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6214            }
6215            obj = mSettings.getUserIdLPr(uid2);
6216            if (obj != null) {
6217                if (obj instanceof SharedUserSetting) {
6218                    if (isCallerInstantApp) {
6219                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6220                    }
6221                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6222                } else if (obj instanceof PackageSetting) {
6223                    final PackageSetting ps = (PackageSetting) obj;
6224                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6225                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6226                    }
6227                    s2 = ps.signatures.mSignatures;
6228                } else {
6229                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6230                }
6231            } else {
6232                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6233            }
6234            return compareSignatures(s1, s2);
6235        }
6236    }
6237
6238    /**
6239     * This method should typically only be used when granting or revoking
6240     * permissions, since the app may immediately restart after this call.
6241     * <p>
6242     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6243     * guard your work against the app being relaunched.
6244     */
6245    private void killUid(int appId, int userId, String reason) {
6246        final long identity = Binder.clearCallingIdentity();
6247        try {
6248            IActivityManager am = ActivityManager.getService();
6249            if (am != null) {
6250                try {
6251                    am.killUid(appId, userId, reason);
6252                } catch (RemoteException e) {
6253                    /* ignore - same process */
6254                }
6255            }
6256        } finally {
6257            Binder.restoreCallingIdentity(identity);
6258        }
6259    }
6260
6261    /**
6262     * Compares two sets of signatures. Returns:
6263     * <br />
6264     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6265     * <br />
6266     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6267     * <br />
6268     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6269     * <br />
6270     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6271     * <br />
6272     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6273     */
6274    static int compareSignatures(Signature[] s1, Signature[] s2) {
6275        if (s1 == null) {
6276            return s2 == null
6277                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6278                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6279        }
6280
6281        if (s2 == null) {
6282            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6283        }
6284
6285        if (s1.length != s2.length) {
6286            return PackageManager.SIGNATURE_NO_MATCH;
6287        }
6288
6289        // Since both signature sets are of size 1, we can compare without HashSets.
6290        if (s1.length == 1) {
6291            return s1[0].equals(s2[0]) ?
6292                    PackageManager.SIGNATURE_MATCH :
6293                    PackageManager.SIGNATURE_NO_MATCH;
6294        }
6295
6296        ArraySet<Signature> set1 = new ArraySet<Signature>();
6297        for (Signature sig : s1) {
6298            set1.add(sig);
6299        }
6300        ArraySet<Signature> set2 = new ArraySet<Signature>();
6301        for (Signature sig : s2) {
6302            set2.add(sig);
6303        }
6304        // Make sure s2 contains all signatures in s1.
6305        if (set1.equals(set2)) {
6306            return PackageManager.SIGNATURE_MATCH;
6307        }
6308        return PackageManager.SIGNATURE_NO_MATCH;
6309    }
6310
6311    /**
6312     * If the database version for this type of package (internal storage or
6313     * external storage) is less than the version where package signatures
6314     * were updated, return true.
6315     */
6316    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6317        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6318        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6319    }
6320
6321    /**
6322     * Used for backward compatibility to make sure any packages with
6323     * certificate chains get upgraded to the new style. {@code existingSigs}
6324     * will be in the old format (since they were stored on disk from before the
6325     * system upgrade) and {@code scannedSigs} will be in the newer format.
6326     */
6327    private int compareSignaturesCompat(PackageSignatures existingSigs,
6328            PackageParser.Package scannedPkg) {
6329        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6330            return PackageManager.SIGNATURE_NO_MATCH;
6331        }
6332
6333        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6334        for (Signature sig : existingSigs.mSignatures) {
6335            existingSet.add(sig);
6336        }
6337        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6338        for (Signature sig : scannedPkg.mSignatures) {
6339            try {
6340                Signature[] chainSignatures = sig.getChainSignatures();
6341                for (Signature chainSig : chainSignatures) {
6342                    scannedCompatSet.add(chainSig);
6343                }
6344            } catch (CertificateEncodingException e) {
6345                scannedCompatSet.add(sig);
6346            }
6347        }
6348        /*
6349         * Make sure the expanded scanned set contains all signatures in the
6350         * existing one.
6351         */
6352        if (scannedCompatSet.equals(existingSet)) {
6353            // Migrate the old signatures to the new scheme.
6354            existingSigs.assignSignatures(scannedPkg.mSignatures);
6355            // The new KeySets will be re-added later in the scanning process.
6356            synchronized (mPackages) {
6357                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6358            }
6359            return PackageManager.SIGNATURE_MATCH;
6360        }
6361        return PackageManager.SIGNATURE_NO_MATCH;
6362    }
6363
6364    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6365        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6366        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6367    }
6368
6369    private int compareSignaturesRecover(PackageSignatures existingSigs,
6370            PackageParser.Package scannedPkg) {
6371        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6372            return PackageManager.SIGNATURE_NO_MATCH;
6373        }
6374
6375        String msg = null;
6376        try {
6377            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6378                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6379                        + scannedPkg.packageName);
6380                return PackageManager.SIGNATURE_MATCH;
6381            }
6382        } catch (CertificateException e) {
6383            msg = e.getMessage();
6384        }
6385
6386        logCriticalInfo(Log.INFO,
6387                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6388        return PackageManager.SIGNATURE_NO_MATCH;
6389    }
6390
6391    @Override
6392    public List<String> getAllPackages() {
6393        final int callingUid = Binder.getCallingUid();
6394        final int callingUserId = UserHandle.getUserId(callingUid);
6395        synchronized (mPackages) {
6396            if (canViewInstantApps(callingUid, callingUserId)) {
6397                return new ArrayList<String>(mPackages.keySet());
6398            }
6399            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6400            final List<String> result = new ArrayList<>();
6401            if (instantAppPkgName != null) {
6402                // caller is an instant application; filter unexposed applications
6403                for (PackageParser.Package pkg : mPackages.values()) {
6404                    if (!pkg.visibleToInstantApps) {
6405                        continue;
6406                    }
6407                    result.add(pkg.packageName);
6408                }
6409            } else {
6410                // caller is a normal application; filter instant applications
6411                for (PackageParser.Package pkg : mPackages.values()) {
6412                    final PackageSetting ps =
6413                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6414                    if (ps != null
6415                            && ps.getInstantApp(callingUserId)
6416                            && !mInstantAppRegistry.isInstantAccessGranted(
6417                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6418                        continue;
6419                    }
6420                    result.add(pkg.packageName);
6421                }
6422            }
6423            return result;
6424        }
6425    }
6426
6427    @Override
6428    public String[] getPackagesForUid(int uid) {
6429        final int callingUid = Binder.getCallingUid();
6430        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6431        final int userId = UserHandle.getUserId(uid);
6432        uid = UserHandle.getAppId(uid);
6433        // reader
6434        synchronized (mPackages) {
6435            Object obj = mSettings.getUserIdLPr(uid);
6436            if (obj instanceof SharedUserSetting) {
6437                if (isCallerInstantApp) {
6438                    return null;
6439                }
6440                final SharedUserSetting sus = (SharedUserSetting) obj;
6441                final int N = sus.packages.size();
6442                String[] res = new String[N];
6443                final Iterator<PackageSetting> it = sus.packages.iterator();
6444                int i = 0;
6445                while (it.hasNext()) {
6446                    PackageSetting ps = it.next();
6447                    if (ps.getInstalled(userId)) {
6448                        res[i++] = ps.name;
6449                    } else {
6450                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6451                    }
6452                }
6453                return res;
6454            } else if (obj instanceof PackageSetting) {
6455                final PackageSetting ps = (PackageSetting) obj;
6456                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6457                    return new String[]{ps.name};
6458                }
6459            }
6460        }
6461        return null;
6462    }
6463
6464    @Override
6465    public String getNameForUid(int uid) {
6466        final int callingUid = Binder.getCallingUid();
6467        if (getInstantAppPackageName(callingUid) != null) {
6468            return null;
6469        }
6470        synchronized (mPackages) {
6471            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6472            if (obj instanceof SharedUserSetting) {
6473                final SharedUserSetting sus = (SharedUserSetting) obj;
6474                return sus.name + ":" + sus.userId;
6475            } else if (obj instanceof PackageSetting) {
6476                final PackageSetting ps = (PackageSetting) obj;
6477                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6478                    return null;
6479                }
6480                return ps.name;
6481            }
6482            return null;
6483        }
6484    }
6485
6486    @Override
6487    public String[] getNamesForUids(int[] uids) {
6488        if (uids == null || uids.length == 0) {
6489            return null;
6490        }
6491        final int callingUid = Binder.getCallingUid();
6492        if (getInstantAppPackageName(callingUid) != null) {
6493            return null;
6494        }
6495        final String[] names = new String[uids.length];
6496        synchronized (mPackages) {
6497            for (int i = uids.length - 1; i >= 0; i--) {
6498                final int uid = uids[i];
6499                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6500                if (obj instanceof SharedUserSetting) {
6501                    final SharedUserSetting sus = (SharedUserSetting) obj;
6502                    names[i] = "shared:" + sus.name;
6503                } else if (obj instanceof PackageSetting) {
6504                    final PackageSetting ps = (PackageSetting) obj;
6505                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6506                        names[i] = null;
6507                    } else {
6508                        names[i] = ps.name;
6509                    }
6510                } else {
6511                    names[i] = null;
6512                }
6513            }
6514        }
6515        return names;
6516    }
6517
6518    @Override
6519    public int getUidForSharedUser(String sharedUserName) {
6520        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6521            return -1;
6522        }
6523        if (sharedUserName == null) {
6524            return -1;
6525        }
6526        // reader
6527        synchronized (mPackages) {
6528            SharedUserSetting suid;
6529            try {
6530                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6531                if (suid != null) {
6532                    return suid.userId;
6533                }
6534            } catch (PackageManagerException ignore) {
6535                // can't happen, but, still need to catch it
6536            }
6537            return -1;
6538        }
6539    }
6540
6541    @Override
6542    public int getFlagsForUid(int uid) {
6543        final int callingUid = Binder.getCallingUid();
6544        if (getInstantAppPackageName(callingUid) != null) {
6545            return 0;
6546        }
6547        synchronized (mPackages) {
6548            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6549            if (obj instanceof SharedUserSetting) {
6550                final SharedUserSetting sus = (SharedUserSetting) obj;
6551                return sus.pkgFlags;
6552            } else if (obj instanceof PackageSetting) {
6553                final PackageSetting ps = (PackageSetting) obj;
6554                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6555                    return 0;
6556                }
6557                return ps.pkgFlags;
6558            }
6559        }
6560        return 0;
6561    }
6562
6563    @Override
6564    public int getPrivateFlagsForUid(int uid) {
6565        final int callingUid = Binder.getCallingUid();
6566        if (getInstantAppPackageName(callingUid) != null) {
6567            return 0;
6568        }
6569        synchronized (mPackages) {
6570            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6571            if (obj instanceof SharedUserSetting) {
6572                final SharedUserSetting sus = (SharedUserSetting) obj;
6573                return sus.pkgPrivateFlags;
6574            } else if (obj instanceof PackageSetting) {
6575                final PackageSetting ps = (PackageSetting) obj;
6576                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6577                    return 0;
6578                }
6579                return ps.pkgPrivateFlags;
6580            }
6581        }
6582        return 0;
6583    }
6584
6585    @Override
6586    public boolean isUidPrivileged(int uid) {
6587        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6588            return false;
6589        }
6590        uid = UserHandle.getAppId(uid);
6591        // reader
6592        synchronized (mPackages) {
6593            Object obj = mSettings.getUserIdLPr(uid);
6594            if (obj instanceof SharedUserSetting) {
6595                final SharedUserSetting sus = (SharedUserSetting) obj;
6596                final Iterator<PackageSetting> it = sus.packages.iterator();
6597                while (it.hasNext()) {
6598                    if (it.next().isPrivileged()) {
6599                        return true;
6600                    }
6601                }
6602            } else if (obj instanceof PackageSetting) {
6603                final PackageSetting ps = (PackageSetting) obj;
6604                return ps.isPrivileged();
6605            }
6606        }
6607        return false;
6608    }
6609
6610    @Override
6611    public String[] getAppOpPermissionPackages(String permissionName) {
6612        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6613            return null;
6614        }
6615        synchronized (mPackages) {
6616            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6617            if (pkgs == null) {
6618                return null;
6619            }
6620            return pkgs.toArray(new String[pkgs.size()]);
6621        }
6622    }
6623
6624    @Override
6625    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6626            int flags, int userId) {
6627        return resolveIntentInternal(
6628                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6629    }
6630
6631    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6632            int flags, int userId, boolean resolveForStart) {
6633        try {
6634            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6635
6636            if (!sUserManager.exists(userId)) return null;
6637            final int callingUid = Binder.getCallingUid();
6638            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6639            enforceCrossUserPermission(callingUid, userId,
6640                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6641
6642            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6643            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6644                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6645            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6646
6647            final ResolveInfo bestChoice =
6648                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6649            return bestChoice;
6650        } finally {
6651            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6652        }
6653    }
6654
6655    @Override
6656    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6657        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6658            throw new SecurityException(
6659                    "findPersistentPreferredActivity can only be run by the system");
6660        }
6661        if (!sUserManager.exists(userId)) {
6662            return null;
6663        }
6664        final int callingUid = Binder.getCallingUid();
6665        intent = updateIntentForResolve(intent);
6666        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6667        final int flags = updateFlagsForResolve(
6668                0, userId, intent, callingUid, false /*includeInstantApps*/);
6669        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6670                userId);
6671        synchronized (mPackages) {
6672            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6673                    userId);
6674        }
6675    }
6676
6677    @Override
6678    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6679            IntentFilter filter, int match, ComponentName activity) {
6680        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6681            return;
6682        }
6683        final int userId = UserHandle.getCallingUserId();
6684        if (DEBUG_PREFERRED) {
6685            Log.v(TAG, "setLastChosenActivity intent=" + intent
6686                + " resolvedType=" + resolvedType
6687                + " flags=" + flags
6688                + " filter=" + filter
6689                + " match=" + match
6690                + " activity=" + activity);
6691            filter.dump(new PrintStreamPrinter(System.out), "    ");
6692        }
6693        intent.setComponent(null);
6694        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6695                userId);
6696        // Find any earlier preferred or last chosen entries and nuke them
6697        findPreferredActivity(intent, resolvedType,
6698                flags, query, 0, false, true, false, userId);
6699        // Add the new activity as the last chosen for this filter
6700        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6701                "Setting last chosen");
6702    }
6703
6704    @Override
6705    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6706        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6707            return null;
6708        }
6709        final int userId = UserHandle.getCallingUserId();
6710        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6711        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6712                userId);
6713        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6714                false, false, false, userId);
6715    }
6716
6717    /**
6718     * Returns whether or not instant apps have been disabled remotely.
6719     */
6720    private boolean isEphemeralDisabled() {
6721        return mEphemeralAppsDisabled;
6722    }
6723
6724    private boolean isInstantAppAllowed(
6725            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6726            boolean skipPackageCheck) {
6727        if (mInstantAppResolverConnection == null) {
6728            return false;
6729        }
6730        if (mInstantAppInstallerActivity == null) {
6731            return false;
6732        }
6733        if (intent.getComponent() != null) {
6734            return false;
6735        }
6736        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6737            return false;
6738        }
6739        if (!skipPackageCheck && intent.getPackage() != null) {
6740            return false;
6741        }
6742        final boolean isWebUri = hasWebURI(intent);
6743        if (!isWebUri || intent.getData().getHost() == null) {
6744            return false;
6745        }
6746        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6747        // Or if there's already an ephemeral app installed that handles the action
6748        synchronized (mPackages) {
6749            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6750            for (int n = 0; n < count; n++) {
6751                final ResolveInfo info = resolvedActivities.get(n);
6752                final String packageName = info.activityInfo.packageName;
6753                final PackageSetting ps = mSettings.mPackages.get(packageName);
6754                if (ps != null) {
6755                    // only check domain verification status if the app is not a browser
6756                    if (!info.handleAllWebDataURI) {
6757                        // Try to get the status from User settings first
6758                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6759                        final int status = (int) (packedStatus >> 32);
6760                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6761                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6762                            if (DEBUG_EPHEMERAL) {
6763                                Slog.v(TAG, "DENY instant app;"
6764                                    + " pkg: " + packageName + ", status: " + status);
6765                            }
6766                            return false;
6767                        }
6768                    }
6769                    if (ps.getInstantApp(userId)) {
6770                        if (DEBUG_EPHEMERAL) {
6771                            Slog.v(TAG, "DENY instant app installed;"
6772                                    + " pkg: " + packageName);
6773                        }
6774                        return false;
6775                    }
6776                }
6777            }
6778        }
6779        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6780        return true;
6781    }
6782
6783    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6784            Intent origIntent, String resolvedType, String callingPackage,
6785            Bundle verificationBundle, int userId) {
6786        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6787                new InstantAppRequest(responseObj, origIntent, resolvedType,
6788                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6789        mHandler.sendMessage(msg);
6790    }
6791
6792    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6793            int flags, List<ResolveInfo> query, int userId) {
6794        if (query != null) {
6795            final int N = query.size();
6796            if (N == 1) {
6797                return query.get(0);
6798            } else if (N > 1) {
6799                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6800                // If there is more than one activity with the same priority,
6801                // then let the user decide between them.
6802                ResolveInfo r0 = query.get(0);
6803                ResolveInfo r1 = query.get(1);
6804                if (DEBUG_INTENT_MATCHING || debug) {
6805                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6806                            + r1.activityInfo.name + "=" + r1.priority);
6807                }
6808                // If the first activity has a higher priority, or a different
6809                // default, then it is always desirable to pick it.
6810                if (r0.priority != r1.priority
6811                        || r0.preferredOrder != r1.preferredOrder
6812                        || r0.isDefault != r1.isDefault) {
6813                    return query.get(0);
6814                }
6815                // If we have saved a preference for a preferred activity for
6816                // this Intent, use that.
6817                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6818                        flags, query, r0.priority, true, false, debug, userId);
6819                if (ri != null) {
6820                    return ri;
6821                }
6822                // If we have an ephemeral app, use it
6823                for (int i = 0; i < N; i++) {
6824                    ri = query.get(i);
6825                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6826                        final String packageName = ri.activityInfo.packageName;
6827                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6828                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6829                        final int status = (int)(packedStatus >> 32);
6830                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6831                            return ri;
6832                        }
6833                    }
6834                }
6835                ri = new ResolveInfo(mResolveInfo);
6836                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6837                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6838                // If all of the options come from the same package, show the application's
6839                // label and icon instead of the generic resolver's.
6840                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6841                // and then throw away the ResolveInfo itself, meaning that the caller loses
6842                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6843                // a fallback for this case; we only set the target package's resources on
6844                // the ResolveInfo, not the ActivityInfo.
6845                final String intentPackage = intent.getPackage();
6846                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6847                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6848                    ri.resolvePackageName = intentPackage;
6849                    if (userNeedsBadging(userId)) {
6850                        ri.noResourceId = true;
6851                    } else {
6852                        ri.icon = appi.icon;
6853                    }
6854                    ri.iconResourceId = appi.icon;
6855                    ri.labelRes = appi.labelRes;
6856                }
6857                ri.activityInfo.applicationInfo = new ApplicationInfo(
6858                        ri.activityInfo.applicationInfo);
6859                if (userId != 0) {
6860                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6861                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6862                }
6863                // Make sure that the resolver is displayable in car mode
6864                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6865                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6866                return ri;
6867            }
6868        }
6869        return null;
6870    }
6871
6872    /**
6873     * Return true if the given list is not empty and all of its contents have
6874     * an activityInfo with the given package name.
6875     */
6876    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6877        if (ArrayUtils.isEmpty(list)) {
6878            return false;
6879        }
6880        for (int i = 0, N = list.size(); i < N; i++) {
6881            final ResolveInfo ri = list.get(i);
6882            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6883            if (ai == null || !packageName.equals(ai.packageName)) {
6884                return false;
6885            }
6886        }
6887        return true;
6888    }
6889
6890    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6891            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6892        final int N = query.size();
6893        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6894                .get(userId);
6895        // Get the list of persistent preferred activities that handle the intent
6896        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6897        List<PersistentPreferredActivity> pprefs = ppir != null
6898                ? ppir.queryIntent(intent, resolvedType,
6899                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6900                        userId)
6901                : null;
6902        if (pprefs != null && pprefs.size() > 0) {
6903            final int M = pprefs.size();
6904            for (int i=0; i<M; i++) {
6905                final PersistentPreferredActivity ppa = pprefs.get(i);
6906                if (DEBUG_PREFERRED || debug) {
6907                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6908                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6909                            + "\n  component=" + ppa.mComponent);
6910                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6911                }
6912                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6913                        flags | MATCH_DISABLED_COMPONENTS, userId);
6914                if (DEBUG_PREFERRED || debug) {
6915                    Slog.v(TAG, "Found persistent preferred activity:");
6916                    if (ai != null) {
6917                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6918                    } else {
6919                        Slog.v(TAG, "  null");
6920                    }
6921                }
6922                if (ai == null) {
6923                    // This previously registered persistent preferred activity
6924                    // component is no longer known. Ignore it and do NOT remove it.
6925                    continue;
6926                }
6927                for (int j=0; j<N; j++) {
6928                    final ResolveInfo ri = query.get(j);
6929                    if (!ri.activityInfo.applicationInfo.packageName
6930                            .equals(ai.applicationInfo.packageName)) {
6931                        continue;
6932                    }
6933                    if (!ri.activityInfo.name.equals(ai.name)) {
6934                        continue;
6935                    }
6936                    //  Found a persistent preference that can handle the intent.
6937                    if (DEBUG_PREFERRED || debug) {
6938                        Slog.v(TAG, "Returning persistent preferred activity: " +
6939                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6940                    }
6941                    return ri;
6942                }
6943            }
6944        }
6945        return null;
6946    }
6947
6948    // TODO: handle preferred activities missing while user has amnesia
6949    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6950            List<ResolveInfo> query, int priority, boolean always,
6951            boolean removeMatches, boolean debug, int userId) {
6952        if (!sUserManager.exists(userId)) return null;
6953        final int callingUid = Binder.getCallingUid();
6954        flags = updateFlagsForResolve(
6955                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6956        intent = updateIntentForResolve(intent);
6957        // writer
6958        synchronized (mPackages) {
6959            // Try to find a matching persistent preferred activity.
6960            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6961                    debug, userId);
6962
6963            // If a persistent preferred activity matched, use it.
6964            if (pri != null) {
6965                return pri;
6966            }
6967
6968            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6969            // Get the list of preferred activities that handle the intent
6970            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6971            List<PreferredActivity> prefs = pir != null
6972                    ? pir.queryIntent(intent, resolvedType,
6973                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6974                            userId)
6975                    : null;
6976            if (prefs != null && prefs.size() > 0) {
6977                boolean changed = false;
6978                try {
6979                    // First figure out how good the original match set is.
6980                    // We will only allow preferred activities that came
6981                    // from the same match quality.
6982                    int match = 0;
6983
6984                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6985
6986                    final int N = query.size();
6987                    for (int j=0; j<N; j++) {
6988                        final ResolveInfo ri = query.get(j);
6989                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6990                                + ": 0x" + Integer.toHexString(match));
6991                        if (ri.match > match) {
6992                            match = ri.match;
6993                        }
6994                    }
6995
6996                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6997                            + Integer.toHexString(match));
6998
6999                    match &= IntentFilter.MATCH_CATEGORY_MASK;
7000                    final int M = prefs.size();
7001                    for (int i=0; i<M; i++) {
7002                        final PreferredActivity pa = prefs.get(i);
7003                        if (DEBUG_PREFERRED || debug) {
7004                            Slog.v(TAG, "Checking PreferredActivity ds="
7005                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
7006                                    + "\n  component=" + pa.mPref.mComponent);
7007                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7008                        }
7009                        if (pa.mPref.mMatch != match) {
7010                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7011                                    + Integer.toHexString(pa.mPref.mMatch));
7012                            continue;
7013                        }
7014                        // If it's not an "always" type preferred activity and that's what we're
7015                        // looking for, skip it.
7016                        if (always && !pa.mPref.mAlways) {
7017                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7018                            continue;
7019                        }
7020                        final ActivityInfo ai = getActivityInfo(
7021                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7022                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7023                                userId);
7024                        if (DEBUG_PREFERRED || debug) {
7025                            Slog.v(TAG, "Found preferred activity:");
7026                            if (ai != null) {
7027                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7028                            } else {
7029                                Slog.v(TAG, "  null");
7030                            }
7031                        }
7032                        if (ai == null) {
7033                            // This previously registered preferred activity
7034                            // component is no longer known.  Most likely an update
7035                            // to the app was installed and in the new version this
7036                            // component no longer exists.  Clean it up by removing
7037                            // it from the preferred activities list, and skip it.
7038                            Slog.w(TAG, "Removing dangling preferred activity: "
7039                                    + pa.mPref.mComponent);
7040                            pir.removeFilter(pa);
7041                            changed = true;
7042                            continue;
7043                        }
7044                        for (int j=0; j<N; j++) {
7045                            final ResolveInfo ri = query.get(j);
7046                            if (!ri.activityInfo.applicationInfo.packageName
7047                                    .equals(ai.applicationInfo.packageName)) {
7048                                continue;
7049                            }
7050                            if (!ri.activityInfo.name.equals(ai.name)) {
7051                                continue;
7052                            }
7053
7054                            if (removeMatches) {
7055                                pir.removeFilter(pa);
7056                                changed = true;
7057                                if (DEBUG_PREFERRED) {
7058                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7059                                }
7060                                break;
7061                            }
7062
7063                            // Okay we found a previously set preferred or last chosen app.
7064                            // If the result set is different from when this
7065                            // was created, and is not a subset of the preferred set, we need to
7066                            // clear it and re-ask the user their preference, if we're looking for
7067                            // an "always" type entry.
7068                            if (always && !pa.mPref.sameSet(query)) {
7069                                if (pa.mPref.isSuperset(query)) {
7070                                    // some components of the set are no longer present in
7071                                    // the query, but the preferred activity can still be reused
7072                                    if (DEBUG_PREFERRED) {
7073                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7074                                                + " still valid as only non-preferred components"
7075                                                + " were removed for " + intent + " type "
7076                                                + resolvedType);
7077                                    }
7078                                    // remove obsolete components and re-add the up-to-date filter
7079                                    PreferredActivity freshPa = new PreferredActivity(pa,
7080                                            pa.mPref.mMatch,
7081                                            pa.mPref.discardObsoleteComponents(query),
7082                                            pa.mPref.mComponent,
7083                                            pa.mPref.mAlways);
7084                                    pir.removeFilter(pa);
7085                                    pir.addFilter(freshPa);
7086                                    changed = true;
7087                                } else {
7088                                    Slog.i(TAG,
7089                                            "Result set changed, dropping preferred activity for "
7090                                                    + intent + " type " + resolvedType);
7091                                    if (DEBUG_PREFERRED) {
7092                                        Slog.v(TAG, "Removing preferred activity since set changed "
7093                                                + pa.mPref.mComponent);
7094                                    }
7095                                    pir.removeFilter(pa);
7096                                    // Re-add the filter as a "last chosen" entry (!always)
7097                                    PreferredActivity lastChosen = new PreferredActivity(
7098                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7099                                    pir.addFilter(lastChosen);
7100                                    changed = true;
7101                                    return null;
7102                                }
7103                            }
7104
7105                            // Yay! Either the set matched or we're looking for the last chosen
7106                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7107                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7108                            return ri;
7109                        }
7110                    }
7111                } finally {
7112                    if (changed) {
7113                        if (DEBUG_PREFERRED) {
7114                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7115                        }
7116                        scheduleWritePackageRestrictionsLocked(userId);
7117                    }
7118                }
7119            }
7120        }
7121        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7122        return null;
7123    }
7124
7125    /*
7126     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7127     */
7128    @Override
7129    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7130            int targetUserId) {
7131        mContext.enforceCallingOrSelfPermission(
7132                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7133        List<CrossProfileIntentFilter> matches =
7134                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7135        if (matches != null) {
7136            int size = matches.size();
7137            for (int i = 0; i < size; i++) {
7138                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7139            }
7140        }
7141        if (hasWebURI(intent)) {
7142            // cross-profile app linking works only towards the parent.
7143            final int callingUid = Binder.getCallingUid();
7144            final UserInfo parent = getProfileParent(sourceUserId);
7145            synchronized(mPackages) {
7146                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7147                        false /*includeInstantApps*/);
7148                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7149                        intent, resolvedType, flags, sourceUserId, parent.id);
7150                return xpDomainInfo != null;
7151            }
7152        }
7153        return false;
7154    }
7155
7156    private UserInfo getProfileParent(int userId) {
7157        final long identity = Binder.clearCallingIdentity();
7158        try {
7159            return sUserManager.getProfileParent(userId);
7160        } finally {
7161            Binder.restoreCallingIdentity(identity);
7162        }
7163    }
7164
7165    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7166            String resolvedType, int userId) {
7167        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7168        if (resolver != null) {
7169            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7170        }
7171        return null;
7172    }
7173
7174    @Override
7175    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7176            String resolvedType, int flags, int userId) {
7177        try {
7178            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7179
7180            return new ParceledListSlice<>(
7181                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7182        } finally {
7183            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7184        }
7185    }
7186
7187    /**
7188     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7189     * instant, returns {@code null}.
7190     */
7191    private String getInstantAppPackageName(int callingUid) {
7192        synchronized (mPackages) {
7193            // If the caller is an isolated app use the owner's uid for the lookup.
7194            if (Process.isIsolated(callingUid)) {
7195                callingUid = mIsolatedOwners.get(callingUid);
7196            }
7197            final int appId = UserHandle.getAppId(callingUid);
7198            final Object obj = mSettings.getUserIdLPr(appId);
7199            if (obj instanceof PackageSetting) {
7200                final PackageSetting ps = (PackageSetting) obj;
7201                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7202                return isInstantApp ? ps.pkg.packageName : null;
7203            }
7204        }
7205        return null;
7206    }
7207
7208    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7209            String resolvedType, int flags, int userId) {
7210        return queryIntentActivitiesInternal(
7211                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7212                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7213    }
7214
7215    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7216            String resolvedType, int flags, int filterCallingUid, int userId,
7217            boolean resolveForStart, boolean allowDynamicSplits) {
7218        if (!sUserManager.exists(userId)) return Collections.emptyList();
7219        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7220        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7221                false /* requireFullPermission */, false /* checkShell */,
7222                "query intent activities");
7223        final String pkgName = intent.getPackage();
7224        ComponentName comp = intent.getComponent();
7225        if (comp == null) {
7226            if (intent.getSelector() != null) {
7227                intent = intent.getSelector();
7228                comp = intent.getComponent();
7229            }
7230        }
7231
7232        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7233                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7234        if (comp != null) {
7235            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7236            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7237            if (ai != null) {
7238                // When specifying an explicit component, we prevent the activity from being
7239                // used when either 1) the calling package is normal and the activity is within
7240                // an ephemeral application or 2) the calling package is ephemeral and the
7241                // activity is not visible to ephemeral applications.
7242                final boolean matchInstantApp =
7243                        (flags & PackageManager.MATCH_INSTANT) != 0;
7244                final boolean matchVisibleToInstantAppOnly =
7245                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7246                final boolean matchExplicitlyVisibleOnly =
7247                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7248                final boolean isCallerInstantApp =
7249                        instantAppPkgName != null;
7250                final boolean isTargetSameInstantApp =
7251                        comp.getPackageName().equals(instantAppPkgName);
7252                final boolean isTargetInstantApp =
7253                        (ai.applicationInfo.privateFlags
7254                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7255                final boolean isTargetVisibleToInstantApp =
7256                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7257                final boolean isTargetExplicitlyVisibleToInstantApp =
7258                        isTargetVisibleToInstantApp
7259                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7260                final boolean isTargetHiddenFromInstantApp =
7261                        !isTargetVisibleToInstantApp
7262                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7263                final boolean blockResolution =
7264                        !isTargetSameInstantApp
7265                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7266                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7267                                        && isTargetHiddenFromInstantApp));
7268                if (!blockResolution) {
7269                    final ResolveInfo ri = new ResolveInfo();
7270                    ri.activityInfo = ai;
7271                    list.add(ri);
7272                }
7273            }
7274            return applyPostResolutionFilter(
7275                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7276        }
7277
7278        // reader
7279        boolean sortResult = false;
7280        boolean addEphemeral = false;
7281        List<ResolveInfo> result;
7282        final boolean ephemeralDisabled = isEphemeralDisabled();
7283        synchronized (mPackages) {
7284            if (pkgName == null) {
7285                List<CrossProfileIntentFilter> matchingFilters =
7286                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7287                // Check for results that need to skip the current profile.
7288                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7289                        resolvedType, flags, userId);
7290                if (xpResolveInfo != null) {
7291                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7292                    xpResult.add(xpResolveInfo);
7293                    return applyPostResolutionFilter(
7294                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7295                            allowDynamicSplits, filterCallingUid, userId);
7296                }
7297
7298                // Check for results in the current profile.
7299                result = filterIfNotSystemUser(mActivities.queryIntent(
7300                        intent, resolvedType, flags, userId), userId);
7301                addEphemeral = !ephemeralDisabled
7302                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7303                // Check for cross profile results.
7304                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7305                xpResolveInfo = queryCrossProfileIntents(
7306                        matchingFilters, intent, resolvedType, flags, userId,
7307                        hasNonNegativePriorityResult);
7308                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7309                    boolean isVisibleToUser = filterIfNotSystemUser(
7310                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7311                    if (isVisibleToUser) {
7312                        result.add(xpResolveInfo);
7313                        sortResult = true;
7314                    }
7315                }
7316                if (hasWebURI(intent)) {
7317                    CrossProfileDomainInfo xpDomainInfo = null;
7318                    final UserInfo parent = getProfileParent(userId);
7319                    if (parent != null) {
7320                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7321                                flags, userId, parent.id);
7322                    }
7323                    if (xpDomainInfo != null) {
7324                        if (xpResolveInfo != null) {
7325                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7326                            // in the result.
7327                            result.remove(xpResolveInfo);
7328                        }
7329                        if (result.size() == 0 && !addEphemeral) {
7330                            // No result in current profile, but found candidate in parent user.
7331                            // And we are not going to add emphemeral app, so we can return the
7332                            // result straight away.
7333                            result.add(xpDomainInfo.resolveInfo);
7334                            return applyPostResolutionFilter(result, instantAppPkgName,
7335                                    allowDynamicSplits, filterCallingUid, userId);
7336                        }
7337                    } else if (result.size() <= 1 && !addEphemeral) {
7338                        // No result in parent user and <= 1 result in current profile, and we
7339                        // are not going to add emphemeral app, so we can return the result without
7340                        // further processing.
7341                        return applyPostResolutionFilter(result, instantAppPkgName,
7342                                allowDynamicSplits, filterCallingUid, userId);
7343                    }
7344                    // We have more than one candidate (combining results from current and parent
7345                    // profile), so we need filtering and sorting.
7346                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7347                            intent, flags, result, xpDomainInfo, userId);
7348                    sortResult = true;
7349                }
7350            } else {
7351                final PackageParser.Package pkg = mPackages.get(pkgName);
7352                result = null;
7353                if (pkg != null) {
7354                    result = filterIfNotSystemUser(
7355                            mActivities.queryIntentForPackage(
7356                                    intent, resolvedType, flags, pkg.activities, userId),
7357                            userId);
7358                }
7359                if (result == null || result.size() == 0) {
7360                    // the caller wants to resolve for a particular package; however, there
7361                    // were no installed results, so, try to find an ephemeral result
7362                    addEphemeral = !ephemeralDisabled
7363                            && isInstantAppAllowed(
7364                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7365                    if (result == null) {
7366                        result = new ArrayList<>();
7367                    }
7368                }
7369            }
7370        }
7371        if (addEphemeral) {
7372            result = maybeAddInstantAppInstaller(
7373                    result, intent, resolvedType, flags, userId, resolveForStart);
7374        }
7375        if (sortResult) {
7376            Collections.sort(result, mResolvePrioritySorter);
7377        }
7378        return applyPostResolutionFilter(
7379                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7380    }
7381
7382    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7383            String resolvedType, int flags, int userId, boolean resolveForStart) {
7384        // first, check to see if we've got an instant app already installed
7385        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7386        ResolveInfo localInstantApp = null;
7387        boolean blockResolution = false;
7388        if (!alreadyResolvedLocally) {
7389            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7390                    flags
7391                        | PackageManager.GET_RESOLVED_FILTER
7392                        | PackageManager.MATCH_INSTANT
7393                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7394                    userId);
7395            for (int i = instantApps.size() - 1; i >= 0; --i) {
7396                final ResolveInfo info = instantApps.get(i);
7397                final String packageName = info.activityInfo.packageName;
7398                final PackageSetting ps = mSettings.mPackages.get(packageName);
7399                if (ps.getInstantApp(userId)) {
7400                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7401                    final int status = (int)(packedStatus >> 32);
7402                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7403                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7404                        // there's a local instant application installed, but, the user has
7405                        // chosen to never use it; skip resolution and don't acknowledge
7406                        // an instant application is even available
7407                        if (DEBUG_EPHEMERAL) {
7408                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7409                        }
7410                        blockResolution = true;
7411                        break;
7412                    } else {
7413                        // we have a locally installed instant application; skip resolution
7414                        // but acknowledge there's an instant application available
7415                        if (DEBUG_EPHEMERAL) {
7416                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7417                        }
7418                        localInstantApp = info;
7419                        break;
7420                    }
7421                }
7422            }
7423        }
7424        // no app installed, let's see if one's available
7425        AuxiliaryResolveInfo auxiliaryResponse = null;
7426        if (!blockResolution) {
7427            if (localInstantApp == null) {
7428                // we don't have an instant app locally, resolve externally
7429                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7430                final InstantAppRequest requestObject = new InstantAppRequest(
7431                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7432                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7433                        resolveForStart);
7434                auxiliaryResponse =
7435                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7436                                mContext, mInstantAppResolverConnection, requestObject);
7437                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7438            } else {
7439                // we have an instant application locally, but, we can't admit that since
7440                // callers shouldn't be able to determine prior browsing. create a dummy
7441                // auxiliary response so the downstream code behaves as if there's an
7442                // instant application available externally. when it comes time to start
7443                // the instant application, we'll do the right thing.
7444                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7445                auxiliaryResponse = new AuxiliaryResolveInfo(
7446                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7447                        ai.versionCode, null /*failureIntent*/);
7448            }
7449        }
7450        if (auxiliaryResponse != null) {
7451            if (DEBUG_EPHEMERAL) {
7452                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7453            }
7454            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7455            final PackageSetting ps =
7456                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7457            if (ps != null) {
7458                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7459                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7460                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7461                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7462                // make sure this resolver is the default
7463                ephemeralInstaller.isDefault = true;
7464                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7465                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7466                // add a non-generic filter
7467                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7468                ephemeralInstaller.filter.addDataPath(
7469                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7470                ephemeralInstaller.isInstantAppAvailable = true;
7471                result.add(ephemeralInstaller);
7472            }
7473        }
7474        return result;
7475    }
7476
7477    private static class CrossProfileDomainInfo {
7478        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7479        ResolveInfo resolveInfo;
7480        /* Best domain verification status of the activities found in the other profile */
7481        int bestDomainVerificationStatus;
7482    }
7483
7484    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7485            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7486        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7487                sourceUserId)) {
7488            return null;
7489        }
7490        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7491                resolvedType, flags, parentUserId);
7492
7493        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7494            return null;
7495        }
7496        CrossProfileDomainInfo result = null;
7497        int size = resultTargetUser.size();
7498        for (int i = 0; i < size; i++) {
7499            ResolveInfo riTargetUser = resultTargetUser.get(i);
7500            // Intent filter verification is only for filters that specify a host. So don't return
7501            // those that handle all web uris.
7502            if (riTargetUser.handleAllWebDataURI) {
7503                continue;
7504            }
7505            String packageName = riTargetUser.activityInfo.packageName;
7506            PackageSetting ps = mSettings.mPackages.get(packageName);
7507            if (ps == null) {
7508                continue;
7509            }
7510            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7511            int status = (int)(verificationState >> 32);
7512            if (result == null) {
7513                result = new CrossProfileDomainInfo();
7514                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7515                        sourceUserId, parentUserId);
7516                result.bestDomainVerificationStatus = status;
7517            } else {
7518                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7519                        result.bestDomainVerificationStatus);
7520            }
7521        }
7522        // Don't consider matches with status NEVER across profiles.
7523        if (result != null && result.bestDomainVerificationStatus
7524                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7525            return null;
7526        }
7527        return result;
7528    }
7529
7530    /**
7531     * Verification statuses are ordered from the worse to the best, except for
7532     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7533     */
7534    private int bestDomainVerificationStatus(int status1, int status2) {
7535        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7536            return status2;
7537        }
7538        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7539            return status1;
7540        }
7541        return (int) MathUtils.max(status1, status2);
7542    }
7543
7544    private boolean isUserEnabled(int userId) {
7545        long callingId = Binder.clearCallingIdentity();
7546        try {
7547            UserInfo userInfo = sUserManager.getUserInfo(userId);
7548            return userInfo != null && userInfo.isEnabled();
7549        } finally {
7550            Binder.restoreCallingIdentity(callingId);
7551        }
7552    }
7553
7554    /**
7555     * Filter out activities with systemUserOnly flag set, when current user is not System.
7556     *
7557     * @return filtered list
7558     */
7559    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7560        if (userId == UserHandle.USER_SYSTEM) {
7561            return resolveInfos;
7562        }
7563        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7564            ResolveInfo info = resolveInfos.get(i);
7565            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7566                resolveInfos.remove(i);
7567            }
7568        }
7569        return resolveInfos;
7570    }
7571
7572    /**
7573     * Filters out ephemeral activities.
7574     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7575     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7576     *
7577     * @param resolveInfos The pre-filtered list of resolved activities
7578     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7579     *          is performed.
7580     * @return A filtered list of resolved activities.
7581     */
7582    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7583            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7584        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7585            final ResolveInfo info = resolveInfos.get(i);
7586            // allow activities that are defined in the provided package
7587            if (allowDynamicSplits
7588                    && info.activityInfo.splitName != null
7589                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7590                            info.activityInfo.splitName)) {
7591                // requested activity is defined in a split that hasn't been installed yet.
7592                // add the installer to the resolve list
7593                if (DEBUG_INSTALL) {
7594                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7595                }
7596                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7597                final ComponentName installFailureActivity = findInstallFailureActivity(
7598                        info.activityInfo.packageName,  filterCallingUid, userId);
7599                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7600                        info.activityInfo.packageName, info.activityInfo.splitName,
7601                        installFailureActivity,
7602                        info.activityInfo.applicationInfo.versionCode,
7603                        null /*failureIntent*/);
7604                // make sure this resolver is the default
7605                installerInfo.isDefault = true;
7606                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7607                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7608                // add a non-generic filter
7609                installerInfo.filter = new IntentFilter();
7610                // load resources from the correct package
7611                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7612                resolveInfos.set(i, installerInfo);
7613                continue;
7614            }
7615            // caller is a full app, don't need to apply any other filtering
7616            if (ephemeralPkgName == null) {
7617                continue;
7618            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7619                // caller is same app; don't need to apply any other filtering
7620                continue;
7621            }
7622            // allow activities that have been explicitly exposed to ephemeral apps
7623            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7624            if (!isEphemeralApp
7625                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7626                continue;
7627            }
7628            resolveInfos.remove(i);
7629        }
7630        return resolveInfos;
7631    }
7632
7633    /**
7634     * Returns the activity component that can handle install failures.
7635     * <p>By default, the instant application installer handles failures. However, an
7636     * application may want to handle failures on its own. Applications do this by
7637     * creating an activity with an intent filter that handles the action
7638     * {@link Intent#ACTION_INSTALL_FAILURE}.
7639     */
7640    private @Nullable ComponentName findInstallFailureActivity(
7641            String packageName, int filterCallingUid, int userId) {
7642        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7643        failureActivityIntent.setPackage(packageName);
7644        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7645        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7646                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7647                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7648        final int NR = result.size();
7649        if (NR > 0) {
7650            for (int i = 0; i < NR; i++) {
7651                final ResolveInfo info = result.get(i);
7652                if (info.activityInfo.splitName != null) {
7653                    continue;
7654                }
7655                return new ComponentName(packageName, info.activityInfo.name);
7656            }
7657        }
7658        return null;
7659    }
7660
7661    /**
7662     * @param resolveInfos list of resolve infos in descending priority order
7663     * @return if the list contains a resolve info with non-negative priority
7664     */
7665    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7666        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7667    }
7668
7669    private static boolean hasWebURI(Intent intent) {
7670        if (intent.getData() == null) {
7671            return false;
7672        }
7673        final String scheme = intent.getScheme();
7674        if (TextUtils.isEmpty(scheme)) {
7675            return false;
7676        }
7677        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7678    }
7679
7680    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7681            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7682            int userId) {
7683        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7684
7685        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7686            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7687                    candidates.size());
7688        }
7689
7690        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7691        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7692        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7693        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7694        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7695        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7696
7697        synchronized (mPackages) {
7698            final int count = candidates.size();
7699            // First, try to use linked apps. Partition the candidates into four lists:
7700            // one for the final results, one for the "do not use ever", one for "undefined status"
7701            // and finally one for "browser app type".
7702            for (int n=0; n<count; n++) {
7703                ResolveInfo info = candidates.get(n);
7704                String packageName = info.activityInfo.packageName;
7705                PackageSetting ps = mSettings.mPackages.get(packageName);
7706                if (ps != null) {
7707                    // Add to the special match all list (Browser use case)
7708                    if (info.handleAllWebDataURI) {
7709                        matchAllList.add(info);
7710                        continue;
7711                    }
7712                    // Try to get the status from User settings first
7713                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7714                    int status = (int)(packedStatus >> 32);
7715                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7716                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7717                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7718                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7719                                    + " : linkgen=" + linkGeneration);
7720                        }
7721                        // Use link-enabled generation as preferredOrder, i.e.
7722                        // prefer newly-enabled over earlier-enabled.
7723                        info.preferredOrder = linkGeneration;
7724                        alwaysList.add(info);
7725                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7726                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7727                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7728                        }
7729                        neverList.add(info);
7730                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7731                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7732                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7733                        }
7734                        alwaysAskList.add(info);
7735                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7736                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7737                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7738                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7739                        }
7740                        undefinedList.add(info);
7741                    }
7742                }
7743            }
7744
7745            // We'll want to include browser possibilities in a few cases
7746            boolean includeBrowser = false;
7747
7748            // First try to add the "always" resolution(s) for the current user, if any
7749            if (alwaysList.size() > 0) {
7750                result.addAll(alwaysList);
7751            } else {
7752                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7753                result.addAll(undefinedList);
7754                // Maybe add one for the other profile.
7755                if (xpDomainInfo != null && (
7756                        xpDomainInfo.bestDomainVerificationStatus
7757                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7758                    result.add(xpDomainInfo.resolveInfo);
7759                }
7760                includeBrowser = true;
7761            }
7762
7763            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7764            // If there were 'always' entries their preferred order has been set, so we also
7765            // back that off to make the alternatives equivalent
7766            if (alwaysAskList.size() > 0) {
7767                for (ResolveInfo i : result) {
7768                    i.preferredOrder = 0;
7769                }
7770                result.addAll(alwaysAskList);
7771                includeBrowser = true;
7772            }
7773
7774            if (includeBrowser) {
7775                // Also add browsers (all of them or only the default one)
7776                if (DEBUG_DOMAIN_VERIFICATION) {
7777                    Slog.v(TAG, "   ...including browsers in candidate set");
7778                }
7779                if ((matchFlags & MATCH_ALL) != 0) {
7780                    result.addAll(matchAllList);
7781                } else {
7782                    // Browser/generic handling case.  If there's a default browser, go straight
7783                    // to that (but only if there is no other higher-priority match).
7784                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7785                    int maxMatchPrio = 0;
7786                    ResolveInfo defaultBrowserMatch = null;
7787                    final int numCandidates = matchAllList.size();
7788                    for (int n = 0; n < numCandidates; n++) {
7789                        ResolveInfo info = matchAllList.get(n);
7790                        // track the highest overall match priority...
7791                        if (info.priority > maxMatchPrio) {
7792                            maxMatchPrio = info.priority;
7793                        }
7794                        // ...and the highest-priority default browser match
7795                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7796                            if (defaultBrowserMatch == null
7797                                    || (defaultBrowserMatch.priority < info.priority)) {
7798                                if (debug) {
7799                                    Slog.v(TAG, "Considering default browser match " + info);
7800                                }
7801                                defaultBrowserMatch = info;
7802                            }
7803                        }
7804                    }
7805                    if (defaultBrowserMatch != null
7806                            && defaultBrowserMatch.priority >= maxMatchPrio
7807                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7808                    {
7809                        if (debug) {
7810                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7811                        }
7812                        result.add(defaultBrowserMatch);
7813                    } else {
7814                        result.addAll(matchAllList);
7815                    }
7816                }
7817
7818                // If there is nothing selected, add all candidates and remove the ones that the user
7819                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7820                if (result.size() == 0) {
7821                    result.addAll(candidates);
7822                    result.removeAll(neverList);
7823                }
7824            }
7825        }
7826        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7827            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7828                    result.size());
7829            for (ResolveInfo info : result) {
7830                Slog.v(TAG, "  + " + info.activityInfo);
7831            }
7832        }
7833        return result;
7834    }
7835
7836    // Returns a packed value as a long:
7837    //
7838    // high 'int'-sized word: link status: undefined/ask/never/always.
7839    // low 'int'-sized word: relative priority among 'always' results.
7840    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7841        long result = ps.getDomainVerificationStatusForUser(userId);
7842        // if none available, get the master status
7843        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7844            if (ps.getIntentFilterVerificationInfo() != null) {
7845                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7846            }
7847        }
7848        return result;
7849    }
7850
7851    private ResolveInfo querySkipCurrentProfileIntents(
7852            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7853            int flags, int sourceUserId) {
7854        if (matchingFilters != null) {
7855            int size = matchingFilters.size();
7856            for (int i = 0; i < size; i ++) {
7857                CrossProfileIntentFilter filter = matchingFilters.get(i);
7858                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7859                    // Checking if there are activities in the target user that can handle the
7860                    // intent.
7861                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7862                            resolvedType, flags, sourceUserId);
7863                    if (resolveInfo != null) {
7864                        return resolveInfo;
7865                    }
7866                }
7867            }
7868        }
7869        return null;
7870    }
7871
7872    // Return matching ResolveInfo in target user if any.
7873    private ResolveInfo queryCrossProfileIntents(
7874            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7875            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7876        if (matchingFilters != null) {
7877            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7878            // match the same intent. For performance reasons, it is better not to
7879            // run queryIntent twice for the same userId
7880            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7881            int size = matchingFilters.size();
7882            for (int i = 0; i < size; i++) {
7883                CrossProfileIntentFilter filter = matchingFilters.get(i);
7884                int targetUserId = filter.getTargetUserId();
7885                boolean skipCurrentProfile =
7886                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7887                boolean skipCurrentProfileIfNoMatchFound =
7888                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7889                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7890                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7891                    // Checking if there are activities in the target user that can handle the
7892                    // intent.
7893                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7894                            resolvedType, flags, sourceUserId);
7895                    if (resolveInfo != null) return resolveInfo;
7896                    alreadyTriedUserIds.put(targetUserId, true);
7897                }
7898            }
7899        }
7900        return null;
7901    }
7902
7903    /**
7904     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7905     * will forward the intent to the filter's target user.
7906     * Otherwise, returns null.
7907     */
7908    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7909            String resolvedType, int flags, int sourceUserId) {
7910        int targetUserId = filter.getTargetUserId();
7911        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7912                resolvedType, flags, targetUserId);
7913        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7914            // If all the matches in the target profile are suspended, return null.
7915            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7916                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7917                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7918                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7919                            targetUserId);
7920                }
7921            }
7922        }
7923        return null;
7924    }
7925
7926    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7927            int sourceUserId, int targetUserId) {
7928        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7929        long ident = Binder.clearCallingIdentity();
7930        boolean targetIsProfile;
7931        try {
7932            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7933        } finally {
7934            Binder.restoreCallingIdentity(ident);
7935        }
7936        String className;
7937        if (targetIsProfile) {
7938            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7939        } else {
7940            className = FORWARD_INTENT_TO_PARENT;
7941        }
7942        ComponentName forwardingActivityComponentName = new ComponentName(
7943                mAndroidApplication.packageName, className);
7944        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7945                sourceUserId);
7946        if (!targetIsProfile) {
7947            forwardingActivityInfo.showUserIcon = targetUserId;
7948            forwardingResolveInfo.noResourceId = true;
7949        }
7950        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7951        forwardingResolveInfo.priority = 0;
7952        forwardingResolveInfo.preferredOrder = 0;
7953        forwardingResolveInfo.match = 0;
7954        forwardingResolveInfo.isDefault = true;
7955        forwardingResolveInfo.filter = filter;
7956        forwardingResolveInfo.targetUserId = targetUserId;
7957        return forwardingResolveInfo;
7958    }
7959
7960    @Override
7961    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7962            Intent[] specifics, String[] specificTypes, Intent intent,
7963            String resolvedType, int flags, int userId) {
7964        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7965                specificTypes, intent, resolvedType, flags, userId));
7966    }
7967
7968    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7969            Intent[] specifics, String[] specificTypes, Intent intent,
7970            String resolvedType, int flags, int userId) {
7971        if (!sUserManager.exists(userId)) return Collections.emptyList();
7972        final int callingUid = Binder.getCallingUid();
7973        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7974                false /*includeInstantApps*/);
7975        enforceCrossUserPermission(callingUid, userId,
7976                false /*requireFullPermission*/, false /*checkShell*/,
7977                "query intent activity options");
7978        final String resultsAction = intent.getAction();
7979
7980        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7981                | PackageManager.GET_RESOLVED_FILTER, userId);
7982
7983        if (DEBUG_INTENT_MATCHING) {
7984            Log.v(TAG, "Query " + intent + ": " + results);
7985        }
7986
7987        int specificsPos = 0;
7988        int N;
7989
7990        // todo: note that the algorithm used here is O(N^2).  This
7991        // isn't a problem in our current environment, but if we start running
7992        // into situations where we have more than 5 or 10 matches then this
7993        // should probably be changed to something smarter...
7994
7995        // First we go through and resolve each of the specific items
7996        // that were supplied, taking care of removing any corresponding
7997        // duplicate items in the generic resolve list.
7998        if (specifics != null) {
7999            for (int i=0; i<specifics.length; i++) {
8000                final Intent sintent = specifics[i];
8001                if (sintent == null) {
8002                    continue;
8003                }
8004
8005                if (DEBUG_INTENT_MATCHING) {
8006                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8007                }
8008
8009                String action = sintent.getAction();
8010                if (resultsAction != null && resultsAction.equals(action)) {
8011                    // If this action was explicitly requested, then don't
8012                    // remove things that have it.
8013                    action = null;
8014                }
8015
8016                ResolveInfo ri = null;
8017                ActivityInfo ai = null;
8018
8019                ComponentName comp = sintent.getComponent();
8020                if (comp == null) {
8021                    ri = resolveIntent(
8022                        sintent,
8023                        specificTypes != null ? specificTypes[i] : null,
8024                            flags, userId);
8025                    if (ri == null) {
8026                        continue;
8027                    }
8028                    if (ri == mResolveInfo) {
8029                        // ACK!  Must do something better with this.
8030                    }
8031                    ai = ri.activityInfo;
8032                    comp = new ComponentName(ai.applicationInfo.packageName,
8033                            ai.name);
8034                } else {
8035                    ai = getActivityInfo(comp, flags, userId);
8036                    if (ai == null) {
8037                        continue;
8038                    }
8039                }
8040
8041                // Look for any generic query activities that are duplicates
8042                // of this specific one, and remove them from the results.
8043                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8044                N = results.size();
8045                int j;
8046                for (j=specificsPos; j<N; j++) {
8047                    ResolveInfo sri = results.get(j);
8048                    if ((sri.activityInfo.name.equals(comp.getClassName())
8049                            && sri.activityInfo.applicationInfo.packageName.equals(
8050                                    comp.getPackageName()))
8051                        || (action != null && sri.filter.matchAction(action))) {
8052                        results.remove(j);
8053                        if (DEBUG_INTENT_MATCHING) Log.v(
8054                            TAG, "Removing duplicate item from " + j
8055                            + " due to specific " + specificsPos);
8056                        if (ri == null) {
8057                            ri = sri;
8058                        }
8059                        j--;
8060                        N--;
8061                    }
8062                }
8063
8064                // Add this specific item to its proper place.
8065                if (ri == null) {
8066                    ri = new ResolveInfo();
8067                    ri.activityInfo = ai;
8068                }
8069                results.add(specificsPos, ri);
8070                ri.specificIndex = i;
8071                specificsPos++;
8072            }
8073        }
8074
8075        // Now we go through the remaining generic results and remove any
8076        // duplicate actions that are found here.
8077        N = results.size();
8078        for (int i=specificsPos; i<N-1; i++) {
8079            final ResolveInfo rii = results.get(i);
8080            if (rii.filter == null) {
8081                continue;
8082            }
8083
8084            // Iterate over all of the actions of this result's intent
8085            // filter...  typically this should be just one.
8086            final Iterator<String> it = rii.filter.actionsIterator();
8087            if (it == null) {
8088                continue;
8089            }
8090            while (it.hasNext()) {
8091                final String action = it.next();
8092                if (resultsAction != null && resultsAction.equals(action)) {
8093                    // If this action was explicitly requested, then don't
8094                    // remove things that have it.
8095                    continue;
8096                }
8097                for (int j=i+1; j<N; j++) {
8098                    final ResolveInfo rij = results.get(j);
8099                    if (rij.filter != null && rij.filter.hasAction(action)) {
8100                        results.remove(j);
8101                        if (DEBUG_INTENT_MATCHING) Log.v(
8102                            TAG, "Removing duplicate item from " + j
8103                            + " due to action " + action + " at " + i);
8104                        j--;
8105                        N--;
8106                    }
8107                }
8108            }
8109
8110            // If the caller didn't request filter information, drop it now
8111            // so we don't have to marshall/unmarshall it.
8112            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8113                rii.filter = null;
8114            }
8115        }
8116
8117        // Filter out the caller activity if so requested.
8118        if (caller != null) {
8119            N = results.size();
8120            for (int i=0; i<N; i++) {
8121                ActivityInfo ainfo = results.get(i).activityInfo;
8122                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8123                        && caller.getClassName().equals(ainfo.name)) {
8124                    results.remove(i);
8125                    break;
8126                }
8127            }
8128        }
8129
8130        // If the caller didn't request filter information,
8131        // drop them now so we don't have to
8132        // marshall/unmarshall it.
8133        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8134            N = results.size();
8135            for (int i=0; i<N; i++) {
8136                results.get(i).filter = null;
8137            }
8138        }
8139
8140        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8141        return results;
8142    }
8143
8144    @Override
8145    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8146            String resolvedType, int flags, int userId) {
8147        return new ParceledListSlice<>(
8148                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8149                        false /*allowDynamicSplits*/));
8150    }
8151
8152    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8153            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8154        if (!sUserManager.exists(userId)) return Collections.emptyList();
8155        final int callingUid = Binder.getCallingUid();
8156        enforceCrossUserPermission(callingUid, userId,
8157                false /*requireFullPermission*/, false /*checkShell*/,
8158                "query intent receivers");
8159        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8160        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8161                false /*includeInstantApps*/);
8162        ComponentName comp = intent.getComponent();
8163        if (comp == null) {
8164            if (intent.getSelector() != null) {
8165                intent = intent.getSelector();
8166                comp = intent.getComponent();
8167            }
8168        }
8169        if (comp != null) {
8170            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8171            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8172            if (ai != null) {
8173                // When specifying an explicit component, we prevent the activity from being
8174                // used when either 1) the calling package is normal and the activity is within
8175                // an instant application or 2) the calling package is ephemeral and the
8176                // activity is not visible to instant applications.
8177                final boolean matchInstantApp =
8178                        (flags & PackageManager.MATCH_INSTANT) != 0;
8179                final boolean matchVisibleToInstantAppOnly =
8180                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8181                final boolean matchExplicitlyVisibleOnly =
8182                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8183                final boolean isCallerInstantApp =
8184                        instantAppPkgName != null;
8185                final boolean isTargetSameInstantApp =
8186                        comp.getPackageName().equals(instantAppPkgName);
8187                final boolean isTargetInstantApp =
8188                        (ai.applicationInfo.privateFlags
8189                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8190                final boolean isTargetVisibleToInstantApp =
8191                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8192                final boolean isTargetExplicitlyVisibleToInstantApp =
8193                        isTargetVisibleToInstantApp
8194                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8195                final boolean isTargetHiddenFromInstantApp =
8196                        !isTargetVisibleToInstantApp
8197                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8198                final boolean blockResolution =
8199                        !isTargetSameInstantApp
8200                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8201                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8202                                        && isTargetHiddenFromInstantApp));
8203                if (!blockResolution) {
8204                    ResolveInfo ri = new ResolveInfo();
8205                    ri.activityInfo = ai;
8206                    list.add(ri);
8207                }
8208            }
8209            return applyPostResolutionFilter(
8210                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8211        }
8212
8213        // reader
8214        synchronized (mPackages) {
8215            String pkgName = intent.getPackage();
8216            if (pkgName == null) {
8217                final List<ResolveInfo> result =
8218                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8219                return applyPostResolutionFilter(
8220                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8221            }
8222            final PackageParser.Package pkg = mPackages.get(pkgName);
8223            if (pkg != null) {
8224                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8225                        intent, resolvedType, flags, pkg.receivers, userId);
8226                return applyPostResolutionFilter(
8227                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8228            }
8229            return Collections.emptyList();
8230        }
8231    }
8232
8233    @Override
8234    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8235        final int callingUid = Binder.getCallingUid();
8236        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8237    }
8238
8239    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8240            int userId, int callingUid) {
8241        if (!sUserManager.exists(userId)) return null;
8242        flags = updateFlagsForResolve(
8243                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8244        List<ResolveInfo> query = queryIntentServicesInternal(
8245                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8246        if (query != null) {
8247            if (query.size() >= 1) {
8248                // If there is more than one service with the same priority,
8249                // just arbitrarily pick the first one.
8250                return query.get(0);
8251            }
8252        }
8253        return null;
8254    }
8255
8256    @Override
8257    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8258            String resolvedType, int flags, int userId) {
8259        final int callingUid = Binder.getCallingUid();
8260        return new ParceledListSlice<>(queryIntentServicesInternal(
8261                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8262    }
8263
8264    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8265            String resolvedType, int flags, int userId, int callingUid,
8266            boolean includeInstantApps) {
8267        if (!sUserManager.exists(userId)) return Collections.emptyList();
8268        enforceCrossUserPermission(callingUid, userId,
8269                false /*requireFullPermission*/, false /*checkShell*/,
8270                "query intent receivers");
8271        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8272        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8273        ComponentName comp = intent.getComponent();
8274        if (comp == null) {
8275            if (intent.getSelector() != null) {
8276                intent = intent.getSelector();
8277                comp = intent.getComponent();
8278            }
8279        }
8280        if (comp != null) {
8281            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8282            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8283            if (si != null) {
8284                // When specifying an explicit component, we prevent the service from being
8285                // used when either 1) the service is in an instant application and the
8286                // caller is not the same instant application or 2) the calling package is
8287                // ephemeral and the activity is not visible to ephemeral applications.
8288                final boolean matchInstantApp =
8289                        (flags & PackageManager.MATCH_INSTANT) != 0;
8290                final boolean matchVisibleToInstantAppOnly =
8291                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8292                final boolean isCallerInstantApp =
8293                        instantAppPkgName != null;
8294                final boolean isTargetSameInstantApp =
8295                        comp.getPackageName().equals(instantAppPkgName);
8296                final boolean isTargetInstantApp =
8297                        (si.applicationInfo.privateFlags
8298                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8299                final boolean isTargetHiddenFromInstantApp =
8300                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8301                final boolean blockResolution =
8302                        !isTargetSameInstantApp
8303                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8304                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8305                                        && isTargetHiddenFromInstantApp));
8306                if (!blockResolution) {
8307                    final ResolveInfo ri = new ResolveInfo();
8308                    ri.serviceInfo = si;
8309                    list.add(ri);
8310                }
8311            }
8312            return list;
8313        }
8314
8315        // reader
8316        synchronized (mPackages) {
8317            String pkgName = intent.getPackage();
8318            if (pkgName == null) {
8319                return applyPostServiceResolutionFilter(
8320                        mServices.queryIntent(intent, resolvedType, flags, userId),
8321                        instantAppPkgName);
8322            }
8323            final PackageParser.Package pkg = mPackages.get(pkgName);
8324            if (pkg != null) {
8325                return applyPostServiceResolutionFilter(
8326                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8327                                userId),
8328                        instantAppPkgName);
8329            }
8330            return Collections.emptyList();
8331        }
8332    }
8333
8334    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8335            String instantAppPkgName) {
8336        if (instantAppPkgName == null) {
8337            return resolveInfos;
8338        }
8339        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8340            final ResolveInfo info = resolveInfos.get(i);
8341            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8342            // allow services that are defined in the provided package
8343            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8344                if (info.serviceInfo.splitName != null
8345                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8346                                info.serviceInfo.splitName)) {
8347                    // requested service is defined in a split that hasn't been installed yet.
8348                    // add the installer to the resolve list
8349                    if (DEBUG_EPHEMERAL) {
8350                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8351                    }
8352                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8353                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8354                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8355                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8356                            null /*failureIntent*/);
8357                    // make sure this resolver is the default
8358                    installerInfo.isDefault = true;
8359                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8360                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8361                    // add a non-generic filter
8362                    installerInfo.filter = new IntentFilter();
8363                    // load resources from the correct package
8364                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8365                    resolveInfos.set(i, installerInfo);
8366                }
8367                continue;
8368            }
8369            // allow services that have been explicitly exposed to ephemeral apps
8370            if (!isEphemeralApp
8371                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8372                continue;
8373            }
8374            resolveInfos.remove(i);
8375        }
8376        return resolveInfos;
8377    }
8378
8379    @Override
8380    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8381            String resolvedType, int flags, int userId) {
8382        return new ParceledListSlice<>(
8383                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8384    }
8385
8386    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8387            Intent intent, String resolvedType, int flags, int userId) {
8388        if (!sUserManager.exists(userId)) return Collections.emptyList();
8389        final int callingUid = Binder.getCallingUid();
8390        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8391        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8392                false /*includeInstantApps*/);
8393        ComponentName comp = intent.getComponent();
8394        if (comp == null) {
8395            if (intent.getSelector() != null) {
8396                intent = intent.getSelector();
8397                comp = intent.getComponent();
8398            }
8399        }
8400        if (comp != null) {
8401            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8402            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8403            if (pi != null) {
8404                // When specifying an explicit component, we prevent the provider from being
8405                // used when either 1) the provider is in an instant application and the
8406                // caller is not the same instant application or 2) the calling package is an
8407                // instant application and the provider is not visible to instant applications.
8408                final boolean matchInstantApp =
8409                        (flags & PackageManager.MATCH_INSTANT) != 0;
8410                final boolean matchVisibleToInstantAppOnly =
8411                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8412                final boolean isCallerInstantApp =
8413                        instantAppPkgName != null;
8414                final boolean isTargetSameInstantApp =
8415                        comp.getPackageName().equals(instantAppPkgName);
8416                final boolean isTargetInstantApp =
8417                        (pi.applicationInfo.privateFlags
8418                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8419                final boolean isTargetHiddenFromInstantApp =
8420                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8421                final boolean blockResolution =
8422                        !isTargetSameInstantApp
8423                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8424                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8425                                        && isTargetHiddenFromInstantApp));
8426                if (!blockResolution) {
8427                    final ResolveInfo ri = new ResolveInfo();
8428                    ri.providerInfo = pi;
8429                    list.add(ri);
8430                }
8431            }
8432            return list;
8433        }
8434
8435        // reader
8436        synchronized (mPackages) {
8437            String pkgName = intent.getPackage();
8438            if (pkgName == null) {
8439                return applyPostContentProviderResolutionFilter(
8440                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8441                        instantAppPkgName);
8442            }
8443            final PackageParser.Package pkg = mPackages.get(pkgName);
8444            if (pkg != null) {
8445                return applyPostContentProviderResolutionFilter(
8446                        mProviders.queryIntentForPackage(
8447                        intent, resolvedType, flags, pkg.providers, userId),
8448                        instantAppPkgName);
8449            }
8450            return Collections.emptyList();
8451        }
8452    }
8453
8454    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8455            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8456        if (instantAppPkgName == null) {
8457            return resolveInfos;
8458        }
8459        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8460            final ResolveInfo info = resolveInfos.get(i);
8461            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8462            // allow providers that are defined in the provided package
8463            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8464                if (info.providerInfo.splitName != null
8465                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8466                                info.providerInfo.splitName)) {
8467                    // requested provider is defined in a split that hasn't been installed yet.
8468                    // add the installer to the resolve list
8469                    if (DEBUG_EPHEMERAL) {
8470                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8471                    }
8472                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8473                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8474                            info.providerInfo.packageName, info.providerInfo.splitName,
8475                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8476                            null /*failureIntent*/);
8477                    // make sure this resolver is the default
8478                    installerInfo.isDefault = true;
8479                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8480                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8481                    // add a non-generic filter
8482                    installerInfo.filter = new IntentFilter();
8483                    // load resources from the correct package
8484                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8485                    resolveInfos.set(i, installerInfo);
8486                }
8487                continue;
8488            }
8489            // allow providers that have been explicitly exposed to instant applications
8490            if (!isEphemeralApp
8491                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8492                continue;
8493            }
8494            resolveInfos.remove(i);
8495        }
8496        return resolveInfos;
8497    }
8498
8499    @Override
8500    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8501        final int callingUid = Binder.getCallingUid();
8502        if (getInstantAppPackageName(callingUid) != null) {
8503            return ParceledListSlice.emptyList();
8504        }
8505        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8506        flags = updateFlagsForPackage(flags, userId, null);
8507        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8508        enforceCrossUserPermission(callingUid, userId,
8509                true /* requireFullPermission */, false /* checkShell */,
8510                "get installed packages");
8511
8512        // writer
8513        synchronized (mPackages) {
8514            ArrayList<PackageInfo> list;
8515            if (listUninstalled) {
8516                list = new ArrayList<>(mSettings.mPackages.size());
8517                for (PackageSetting ps : mSettings.mPackages.values()) {
8518                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8519                        continue;
8520                    }
8521                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8522                        continue;
8523                    }
8524                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8525                    if (pi != null) {
8526                        list.add(pi);
8527                    }
8528                }
8529            } else {
8530                list = new ArrayList<>(mPackages.size());
8531                for (PackageParser.Package p : mPackages.values()) {
8532                    final PackageSetting ps = (PackageSetting) p.mExtras;
8533                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8534                        continue;
8535                    }
8536                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8537                        continue;
8538                    }
8539                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8540                            p.mExtras, flags, userId);
8541                    if (pi != null) {
8542                        list.add(pi);
8543                    }
8544                }
8545            }
8546
8547            return new ParceledListSlice<>(list);
8548        }
8549    }
8550
8551    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8552            String[] permissions, boolean[] tmp, int flags, int userId) {
8553        int numMatch = 0;
8554        final PermissionsState permissionsState = ps.getPermissionsState();
8555        for (int i=0; i<permissions.length; i++) {
8556            final String permission = permissions[i];
8557            if (permissionsState.hasPermission(permission, userId)) {
8558                tmp[i] = true;
8559                numMatch++;
8560            } else {
8561                tmp[i] = false;
8562            }
8563        }
8564        if (numMatch == 0) {
8565            return;
8566        }
8567        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8568
8569        // The above might return null in cases of uninstalled apps or install-state
8570        // skew across users/profiles.
8571        if (pi != null) {
8572            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8573                if (numMatch == permissions.length) {
8574                    pi.requestedPermissions = permissions;
8575                } else {
8576                    pi.requestedPermissions = new String[numMatch];
8577                    numMatch = 0;
8578                    for (int i=0; i<permissions.length; i++) {
8579                        if (tmp[i]) {
8580                            pi.requestedPermissions[numMatch] = permissions[i];
8581                            numMatch++;
8582                        }
8583                    }
8584                }
8585            }
8586            list.add(pi);
8587        }
8588    }
8589
8590    @Override
8591    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8592            String[] permissions, int flags, int userId) {
8593        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8594        flags = updateFlagsForPackage(flags, userId, permissions);
8595        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8596                true /* requireFullPermission */, false /* checkShell */,
8597                "get packages holding permissions");
8598        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8599
8600        // writer
8601        synchronized (mPackages) {
8602            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8603            boolean[] tmpBools = new boolean[permissions.length];
8604            if (listUninstalled) {
8605                for (PackageSetting ps : mSettings.mPackages.values()) {
8606                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8607                            userId);
8608                }
8609            } else {
8610                for (PackageParser.Package pkg : mPackages.values()) {
8611                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8612                    if (ps != null) {
8613                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8614                                userId);
8615                    }
8616                }
8617            }
8618
8619            return new ParceledListSlice<PackageInfo>(list);
8620        }
8621    }
8622
8623    @Override
8624    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8625        final int callingUid = Binder.getCallingUid();
8626        if (getInstantAppPackageName(callingUid) != null) {
8627            return ParceledListSlice.emptyList();
8628        }
8629        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8630        flags = updateFlagsForApplication(flags, userId, null);
8631        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8632
8633        // writer
8634        synchronized (mPackages) {
8635            ArrayList<ApplicationInfo> list;
8636            if (listUninstalled) {
8637                list = new ArrayList<>(mSettings.mPackages.size());
8638                for (PackageSetting ps : mSettings.mPackages.values()) {
8639                    ApplicationInfo ai;
8640                    int effectiveFlags = flags;
8641                    if (ps.isSystem()) {
8642                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8643                    }
8644                    if (ps.pkg != null) {
8645                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8646                            continue;
8647                        }
8648                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8649                            continue;
8650                        }
8651                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8652                                ps.readUserState(userId), userId);
8653                        if (ai != null) {
8654                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8655                        }
8656                    } else {
8657                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8658                        // and already converts to externally visible package name
8659                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8660                                callingUid, effectiveFlags, userId);
8661                    }
8662                    if (ai != null) {
8663                        list.add(ai);
8664                    }
8665                }
8666            } else {
8667                list = new ArrayList<>(mPackages.size());
8668                for (PackageParser.Package p : mPackages.values()) {
8669                    if (p.mExtras != null) {
8670                        PackageSetting ps = (PackageSetting) p.mExtras;
8671                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8672                            continue;
8673                        }
8674                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8675                            continue;
8676                        }
8677                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8678                                ps.readUserState(userId), userId);
8679                        if (ai != null) {
8680                            ai.packageName = resolveExternalPackageNameLPr(p);
8681                            list.add(ai);
8682                        }
8683                    }
8684                }
8685            }
8686
8687            return new ParceledListSlice<>(list);
8688        }
8689    }
8690
8691    @Override
8692    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8693        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8694            return null;
8695        }
8696        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8697            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8698                    "getEphemeralApplications");
8699        }
8700        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8701                true /* requireFullPermission */, false /* checkShell */,
8702                "getEphemeralApplications");
8703        synchronized (mPackages) {
8704            List<InstantAppInfo> instantApps = mInstantAppRegistry
8705                    .getInstantAppsLPr(userId);
8706            if (instantApps != null) {
8707                return new ParceledListSlice<>(instantApps);
8708            }
8709        }
8710        return null;
8711    }
8712
8713    @Override
8714    public boolean isInstantApp(String packageName, int userId) {
8715        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8716                true /* requireFullPermission */, false /* checkShell */,
8717                "isInstantApp");
8718        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8719            return false;
8720        }
8721
8722        synchronized (mPackages) {
8723            int callingUid = Binder.getCallingUid();
8724            if (Process.isIsolated(callingUid)) {
8725                callingUid = mIsolatedOwners.get(callingUid);
8726            }
8727            final PackageSetting ps = mSettings.mPackages.get(packageName);
8728            PackageParser.Package pkg = mPackages.get(packageName);
8729            final boolean returnAllowed =
8730                    ps != null
8731                    && (isCallerSameApp(packageName, callingUid)
8732                            || canViewInstantApps(callingUid, userId)
8733                            || mInstantAppRegistry.isInstantAccessGranted(
8734                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8735            if (returnAllowed) {
8736                return ps.getInstantApp(userId);
8737            }
8738        }
8739        return false;
8740    }
8741
8742    @Override
8743    public byte[] getInstantAppCookie(String packageName, int userId) {
8744        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8745            return null;
8746        }
8747
8748        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8749                true /* requireFullPermission */, false /* checkShell */,
8750                "getInstantAppCookie");
8751        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8752            return null;
8753        }
8754        synchronized (mPackages) {
8755            return mInstantAppRegistry.getInstantAppCookieLPw(
8756                    packageName, userId);
8757        }
8758    }
8759
8760    @Override
8761    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8762        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8763            return true;
8764        }
8765
8766        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8767                true /* requireFullPermission */, true /* checkShell */,
8768                "setInstantAppCookie");
8769        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8770            return false;
8771        }
8772        synchronized (mPackages) {
8773            return mInstantAppRegistry.setInstantAppCookieLPw(
8774                    packageName, cookie, userId);
8775        }
8776    }
8777
8778    @Override
8779    public Bitmap getInstantAppIcon(String packageName, int userId) {
8780        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8781            return null;
8782        }
8783
8784        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8785            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8786                    "getInstantAppIcon");
8787        }
8788        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8789                true /* requireFullPermission */, false /* checkShell */,
8790                "getInstantAppIcon");
8791
8792        synchronized (mPackages) {
8793            return mInstantAppRegistry.getInstantAppIconLPw(
8794                    packageName, userId);
8795        }
8796    }
8797
8798    private boolean isCallerSameApp(String packageName, int uid) {
8799        PackageParser.Package pkg = mPackages.get(packageName);
8800        return pkg != null
8801                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8802    }
8803
8804    @Override
8805    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8806        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8807            return ParceledListSlice.emptyList();
8808        }
8809        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8810    }
8811
8812    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8813        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8814
8815        // reader
8816        synchronized (mPackages) {
8817            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8818            final int userId = UserHandle.getCallingUserId();
8819            while (i.hasNext()) {
8820                final PackageParser.Package p = i.next();
8821                if (p.applicationInfo == null) continue;
8822
8823                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8824                        && !p.applicationInfo.isDirectBootAware();
8825                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8826                        && p.applicationInfo.isDirectBootAware();
8827
8828                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8829                        && (!mSafeMode || isSystemApp(p))
8830                        && (matchesUnaware || matchesAware)) {
8831                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8832                    if (ps != null) {
8833                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8834                                ps.readUserState(userId), userId);
8835                        if (ai != null) {
8836                            finalList.add(ai);
8837                        }
8838                    }
8839                }
8840            }
8841        }
8842
8843        return finalList;
8844    }
8845
8846    @Override
8847    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8848        if (!sUserManager.exists(userId)) return null;
8849        flags = updateFlagsForComponent(flags, userId, name);
8850        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8851        // reader
8852        synchronized (mPackages) {
8853            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8854            PackageSetting ps = provider != null
8855                    ? mSettings.mPackages.get(provider.owner.packageName)
8856                    : null;
8857            if (ps != null) {
8858                final boolean isInstantApp = ps.getInstantApp(userId);
8859                // normal application; filter out instant application provider
8860                if (instantAppPkgName == null && isInstantApp) {
8861                    return null;
8862                }
8863                // instant application; filter out other instant applications
8864                if (instantAppPkgName != null
8865                        && isInstantApp
8866                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8867                    return null;
8868                }
8869                // instant application; filter out non-exposed provider
8870                if (instantAppPkgName != null
8871                        && !isInstantApp
8872                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8873                    return null;
8874                }
8875                // provider not enabled
8876                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8877                    return null;
8878                }
8879                return PackageParser.generateProviderInfo(
8880                        provider, flags, ps.readUserState(userId), userId);
8881            }
8882            return null;
8883        }
8884    }
8885
8886    /**
8887     * @deprecated
8888     */
8889    @Deprecated
8890    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8891        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8892            return;
8893        }
8894        // reader
8895        synchronized (mPackages) {
8896            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8897                    .entrySet().iterator();
8898            final int userId = UserHandle.getCallingUserId();
8899            while (i.hasNext()) {
8900                Map.Entry<String, PackageParser.Provider> entry = i.next();
8901                PackageParser.Provider p = entry.getValue();
8902                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8903
8904                if (ps != null && p.syncable
8905                        && (!mSafeMode || (p.info.applicationInfo.flags
8906                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8907                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8908                            ps.readUserState(userId), userId);
8909                    if (info != null) {
8910                        outNames.add(entry.getKey());
8911                        outInfo.add(info);
8912                    }
8913                }
8914            }
8915        }
8916    }
8917
8918    @Override
8919    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8920            int uid, int flags, String metaDataKey) {
8921        final int callingUid = Binder.getCallingUid();
8922        final int userId = processName != null ? UserHandle.getUserId(uid)
8923                : UserHandle.getCallingUserId();
8924        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8925        flags = updateFlagsForComponent(flags, userId, processName);
8926        ArrayList<ProviderInfo> finalList = null;
8927        // reader
8928        synchronized (mPackages) {
8929            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8930            while (i.hasNext()) {
8931                final PackageParser.Provider p = i.next();
8932                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8933                if (ps != null && p.info.authority != null
8934                        && (processName == null
8935                                || (p.info.processName.equals(processName)
8936                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8937                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8938
8939                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8940                    // parameter.
8941                    if (metaDataKey != null
8942                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8943                        continue;
8944                    }
8945                    final ComponentName component =
8946                            new ComponentName(p.info.packageName, p.info.name);
8947                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8948                        continue;
8949                    }
8950                    if (finalList == null) {
8951                        finalList = new ArrayList<ProviderInfo>(3);
8952                    }
8953                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8954                            ps.readUserState(userId), userId);
8955                    if (info != null) {
8956                        finalList.add(info);
8957                    }
8958                }
8959            }
8960        }
8961
8962        if (finalList != null) {
8963            Collections.sort(finalList, mProviderInitOrderSorter);
8964            return new ParceledListSlice<ProviderInfo>(finalList);
8965        }
8966
8967        return ParceledListSlice.emptyList();
8968    }
8969
8970    @Override
8971    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8972        // reader
8973        synchronized (mPackages) {
8974            final int callingUid = Binder.getCallingUid();
8975            final int callingUserId = UserHandle.getUserId(callingUid);
8976            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8977            if (ps == null) return null;
8978            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8979                return null;
8980            }
8981            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8982            return PackageParser.generateInstrumentationInfo(i, flags);
8983        }
8984    }
8985
8986    @Override
8987    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8988            String targetPackage, int flags) {
8989        final int callingUid = Binder.getCallingUid();
8990        final int callingUserId = UserHandle.getUserId(callingUid);
8991        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8992        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8993            return ParceledListSlice.emptyList();
8994        }
8995        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8996    }
8997
8998    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8999            int flags) {
9000        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
9001
9002        // reader
9003        synchronized (mPackages) {
9004            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
9005            while (i.hasNext()) {
9006                final PackageParser.Instrumentation p = i.next();
9007                if (targetPackage == null
9008                        || targetPackage.equals(p.info.targetPackage)) {
9009                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9010                            flags);
9011                    if (ii != null) {
9012                        finalList.add(ii);
9013                    }
9014                }
9015            }
9016        }
9017
9018        return finalList;
9019    }
9020
9021    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9022        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9023        try {
9024            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9025        } finally {
9026            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9027        }
9028    }
9029
9030    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9031        final File[] files = dir.listFiles();
9032        if (ArrayUtils.isEmpty(files)) {
9033            Log.d(TAG, "No files in app dir " + dir);
9034            return;
9035        }
9036
9037        if (DEBUG_PACKAGE_SCANNING) {
9038            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9039                    + " flags=0x" + Integer.toHexString(parseFlags));
9040        }
9041        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9042                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9043                mParallelPackageParserCallback);
9044
9045        // Submit files for parsing in parallel
9046        int fileCount = 0;
9047        for (File file : files) {
9048            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9049                    && !PackageInstallerService.isStageName(file.getName());
9050            if (!isPackage) {
9051                // Ignore entries which are not packages
9052                continue;
9053            }
9054            parallelPackageParser.submit(file, parseFlags);
9055            fileCount++;
9056        }
9057
9058        // Process results one by one
9059        for (; fileCount > 0; fileCount--) {
9060            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9061            Throwable throwable = parseResult.throwable;
9062            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9063
9064            if (throwable == null) {
9065                // Static shared libraries have synthetic package names
9066                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9067                    renameStaticSharedLibraryPackage(parseResult.pkg);
9068                }
9069                try {
9070                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9071                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9072                                currentTime, null);
9073                    }
9074                } catch (PackageManagerException e) {
9075                    errorCode = e.error;
9076                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9077                }
9078            } else if (throwable instanceof PackageParser.PackageParserException) {
9079                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9080                        throwable;
9081                errorCode = e.error;
9082                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9083            } else {
9084                throw new IllegalStateException("Unexpected exception occurred while parsing "
9085                        + parseResult.scanFile, throwable);
9086            }
9087
9088            // Delete invalid userdata apps
9089            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9090                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9091                logCriticalInfo(Log.WARN,
9092                        "Deleting invalid package at " + parseResult.scanFile);
9093                removeCodePathLI(parseResult.scanFile);
9094            }
9095        }
9096        parallelPackageParser.close();
9097    }
9098
9099    private static File getSettingsProblemFile() {
9100        File dataDir = Environment.getDataDirectory();
9101        File systemDir = new File(dataDir, "system");
9102        File fname = new File(systemDir, "uiderrors.txt");
9103        return fname;
9104    }
9105
9106    static void reportSettingsProblem(int priority, String msg) {
9107        logCriticalInfo(priority, msg);
9108    }
9109
9110    public static void logCriticalInfo(int priority, String msg) {
9111        Slog.println(priority, TAG, msg);
9112        EventLogTags.writePmCriticalInfo(msg);
9113        try {
9114            File fname = getSettingsProblemFile();
9115            FileOutputStream out = new FileOutputStream(fname, true);
9116            PrintWriter pw = new FastPrintWriter(out);
9117            SimpleDateFormat formatter = new SimpleDateFormat();
9118            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9119            pw.println(dateString + ": " + msg);
9120            pw.close();
9121            FileUtils.setPermissions(
9122                    fname.toString(),
9123                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9124                    -1, -1);
9125        } catch (java.io.IOException e) {
9126        }
9127    }
9128
9129    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9130        if (srcFile.isDirectory()) {
9131            final File baseFile = new File(pkg.baseCodePath);
9132            long maxModifiedTime = baseFile.lastModified();
9133            if (pkg.splitCodePaths != null) {
9134                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9135                    final File splitFile = new File(pkg.splitCodePaths[i]);
9136                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9137                }
9138            }
9139            return maxModifiedTime;
9140        }
9141        return srcFile.lastModified();
9142    }
9143
9144    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9145            final int policyFlags) throws PackageManagerException {
9146        // When upgrading from pre-N MR1, verify the package time stamp using the package
9147        // directory and not the APK file.
9148        final long lastModifiedTime = mIsPreNMR1Upgrade
9149                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9150        if (ps != null
9151                && ps.codePath.equals(srcFile)
9152                && ps.timeStamp == lastModifiedTime
9153                && !isCompatSignatureUpdateNeeded(pkg)
9154                && !isRecoverSignatureUpdateNeeded(pkg)) {
9155            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9156            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9157            ArraySet<PublicKey> signingKs;
9158            synchronized (mPackages) {
9159                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9160            }
9161            if (ps.signatures.mSignatures != null
9162                    && ps.signatures.mSignatures.length != 0
9163                    && signingKs != null) {
9164                // Optimization: reuse the existing cached certificates
9165                // if the package appears to be unchanged.
9166                pkg.mSignatures = ps.signatures.mSignatures;
9167                pkg.mSigningKeys = signingKs;
9168                return;
9169            }
9170
9171            Slog.w(TAG, "PackageSetting for " + ps.name
9172                    + " is missing signatures.  Collecting certs again to recover them.");
9173        } else {
9174            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9175        }
9176
9177        try {
9178            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9179            PackageParser.collectCertificates(pkg, policyFlags);
9180        } catch (PackageParserException e) {
9181            throw PackageManagerException.from(e);
9182        } finally {
9183            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9184        }
9185    }
9186
9187    /**
9188     *  Traces a package scan.
9189     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9190     */
9191    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9192            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9193        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9194        try {
9195            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9196        } finally {
9197            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9198        }
9199    }
9200
9201    /**
9202     *  Scans a package and returns the newly parsed package.
9203     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9204     */
9205    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9206            long currentTime, UserHandle user) throws PackageManagerException {
9207        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9208        PackageParser pp = new PackageParser();
9209        pp.setSeparateProcesses(mSeparateProcesses);
9210        pp.setOnlyCoreApps(mOnlyCore);
9211        pp.setDisplayMetrics(mMetrics);
9212        pp.setCallback(mPackageParserCallback);
9213
9214        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9215            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9216        }
9217
9218        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9219        final PackageParser.Package pkg;
9220        try {
9221            pkg = pp.parsePackage(scanFile, parseFlags);
9222        } catch (PackageParserException e) {
9223            throw PackageManagerException.from(e);
9224        } finally {
9225            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9226        }
9227
9228        // Static shared libraries have synthetic package names
9229        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9230            renameStaticSharedLibraryPackage(pkg);
9231        }
9232
9233        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9234    }
9235
9236    /**
9237     *  Scans a package and returns the newly parsed package.
9238     *  @throws PackageManagerException on a parse error.
9239     */
9240    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9241            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9242            throws PackageManagerException {
9243        // If the package has children and this is the first dive in the function
9244        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9245        // packages (parent and children) would be successfully scanned before the
9246        // actual scan since scanning mutates internal state and we want to atomically
9247        // install the package and its children.
9248        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9249            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9250                scanFlags |= SCAN_CHECK_ONLY;
9251            }
9252        } else {
9253            scanFlags &= ~SCAN_CHECK_ONLY;
9254        }
9255
9256        // Scan the parent
9257        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9258                scanFlags, currentTime, user);
9259
9260        // Scan the children
9261        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9262        for (int i = 0; i < childCount; i++) {
9263            PackageParser.Package childPackage = pkg.childPackages.get(i);
9264            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9265                    currentTime, user);
9266        }
9267
9268
9269        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9270            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9271        }
9272
9273        return scannedPkg;
9274    }
9275
9276    /**
9277     *  Scans a package and returns the newly parsed package.
9278     *  @throws PackageManagerException on a parse error.
9279     */
9280    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9281            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9282            throws PackageManagerException {
9283        PackageSetting ps = null;
9284        PackageSetting updatedPkg;
9285        // reader
9286        synchronized (mPackages) {
9287            // Look to see if we already know about this package.
9288            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9289            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9290                // This package has been renamed to its original name.  Let's
9291                // use that.
9292                ps = mSettings.getPackageLPr(oldName);
9293            }
9294            // If there was no original package, see one for the real package name.
9295            if (ps == null) {
9296                ps = mSettings.getPackageLPr(pkg.packageName);
9297            }
9298            // Check to see if this package could be hiding/updating a system
9299            // package.  Must look for it either under the original or real
9300            // package name depending on our state.
9301            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9302            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9303
9304            // If this is a package we don't know about on the system partition, we
9305            // may need to remove disabled child packages on the system partition
9306            // or may need to not add child packages if the parent apk is updated
9307            // on the data partition and no longer defines this child package.
9308            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9309                // If this is a parent package for an updated system app and this system
9310                // app got an OTA update which no longer defines some of the child packages
9311                // we have to prune them from the disabled system packages.
9312                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9313                if (disabledPs != null) {
9314                    final int scannedChildCount = (pkg.childPackages != null)
9315                            ? pkg.childPackages.size() : 0;
9316                    final int disabledChildCount = disabledPs.childPackageNames != null
9317                            ? disabledPs.childPackageNames.size() : 0;
9318                    for (int i = 0; i < disabledChildCount; i++) {
9319                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9320                        boolean disabledPackageAvailable = false;
9321                        for (int j = 0; j < scannedChildCount; j++) {
9322                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9323                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9324                                disabledPackageAvailable = true;
9325                                break;
9326                            }
9327                         }
9328                         if (!disabledPackageAvailable) {
9329                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9330                         }
9331                    }
9332                }
9333            }
9334        }
9335
9336        final boolean isUpdatedPkg = updatedPkg != null;
9337        final boolean isUpdatedSystemPkg = isUpdatedPkg
9338                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9339        boolean isUpdatedPkgBetter = false;
9340        // First check if this is a system package that may involve an update
9341        if (isUpdatedSystemPkg) {
9342            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9343            // it needs to drop FLAG_PRIVILEGED.
9344            if (locationIsPrivileged(scanFile)) {
9345                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9346            } else {
9347                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9348            }
9349
9350            if (ps != null && !ps.codePath.equals(scanFile)) {
9351                // The path has changed from what was last scanned...  check the
9352                // version of the new path against what we have stored to determine
9353                // what to do.
9354                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9355                if (pkg.mVersionCode <= ps.versionCode) {
9356                    // The system package has been updated and the code path does not match
9357                    // Ignore entry. Skip it.
9358                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9359                            + " ignored: updated version " + ps.versionCode
9360                            + " better than this " + pkg.mVersionCode);
9361                    if (!updatedPkg.codePath.equals(scanFile)) {
9362                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9363                                + ps.name + " changing from " + updatedPkg.codePathString
9364                                + " to " + scanFile);
9365                        updatedPkg.codePath = scanFile;
9366                        updatedPkg.codePathString = scanFile.toString();
9367                        updatedPkg.resourcePath = scanFile;
9368                        updatedPkg.resourcePathString = scanFile.toString();
9369                    }
9370                    updatedPkg.pkg = pkg;
9371                    updatedPkg.versionCode = pkg.mVersionCode;
9372
9373                    // Update the disabled system child packages to point to the package too.
9374                    final int childCount = updatedPkg.childPackageNames != null
9375                            ? updatedPkg.childPackageNames.size() : 0;
9376                    for (int i = 0; i < childCount; i++) {
9377                        String childPackageName = updatedPkg.childPackageNames.get(i);
9378                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9379                                childPackageName);
9380                        if (updatedChildPkg != null) {
9381                            updatedChildPkg.pkg = pkg;
9382                            updatedChildPkg.versionCode = pkg.mVersionCode;
9383                        }
9384                    }
9385                } else {
9386                    // The current app on the system partition is better than
9387                    // what we have updated to on the data partition; switch
9388                    // back to the system partition version.
9389                    // At this point, its safely assumed that package installation for
9390                    // apps in system partition will go through. If not there won't be a working
9391                    // version of the app
9392                    // writer
9393                    synchronized (mPackages) {
9394                        // Just remove the loaded entries from package lists.
9395                        mPackages.remove(ps.name);
9396                    }
9397
9398                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9399                            + " reverting from " + ps.codePathString
9400                            + ": new version " + pkg.mVersionCode
9401                            + " better than installed " + ps.versionCode);
9402
9403                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9404                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9405                    synchronized (mInstallLock) {
9406                        args.cleanUpResourcesLI();
9407                    }
9408                    synchronized (mPackages) {
9409                        mSettings.enableSystemPackageLPw(ps.name);
9410                    }
9411                    isUpdatedPkgBetter = true;
9412                }
9413            }
9414        }
9415
9416        String resourcePath = null;
9417        String baseResourcePath = null;
9418        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9419            if (ps != null && ps.resourcePathString != null) {
9420                resourcePath = ps.resourcePathString;
9421                baseResourcePath = ps.resourcePathString;
9422            } else {
9423                // Should not happen at all. Just log an error.
9424                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9425            }
9426        } else {
9427            resourcePath = pkg.codePath;
9428            baseResourcePath = pkg.baseCodePath;
9429        }
9430
9431        // Set application objects path explicitly.
9432        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9433        pkg.setApplicationInfoCodePath(pkg.codePath);
9434        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9435        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9436        pkg.setApplicationInfoResourcePath(resourcePath);
9437        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9438        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9439
9440        // throw an exception if we have an update to a system application, but, it's not more
9441        // recent than the package we've already scanned
9442        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9443            // Set CPU Abis to application info.
9444            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9445                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9446                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9447            } else {
9448                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9449                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9450            }
9451
9452            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9453                    + scanFile + " ignored: updated version " + ps.versionCode
9454                    + " better than this " + pkg.mVersionCode);
9455        }
9456
9457        if (isUpdatedPkg) {
9458            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9459            // initially
9460            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9461
9462            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9463            // flag set initially
9464            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9465                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9466            }
9467        }
9468
9469        // Verify certificates against what was last scanned
9470        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9471
9472        /*
9473         * A new system app appeared, but we already had a non-system one of the
9474         * same name installed earlier.
9475         */
9476        boolean shouldHideSystemApp = false;
9477        if (!isUpdatedPkg && ps != null
9478                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9479            /*
9480             * Check to make sure the signatures match first. If they don't,
9481             * wipe the installed application and its data.
9482             */
9483            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9484                    != PackageManager.SIGNATURE_MATCH) {
9485                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9486                        + " signatures don't match existing userdata copy; removing");
9487                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9488                        "scanPackageInternalLI")) {
9489                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9490                }
9491                ps = null;
9492            } else {
9493                /*
9494                 * If the newly-added system app is an older version than the
9495                 * already installed version, hide it. It will be scanned later
9496                 * and re-added like an update.
9497                 */
9498                if (pkg.mVersionCode <= ps.versionCode) {
9499                    shouldHideSystemApp = true;
9500                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9501                            + " but new version " + pkg.mVersionCode + " better than installed "
9502                            + ps.versionCode + "; hiding system");
9503                } else {
9504                    /*
9505                     * The newly found system app is a newer version that the
9506                     * one previously installed. Simply remove the
9507                     * already-installed application and replace it with our own
9508                     * while keeping the application data.
9509                     */
9510                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9511                            + " reverting from " + ps.codePathString + ": new version "
9512                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9513                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9514                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9515                    synchronized (mInstallLock) {
9516                        args.cleanUpResourcesLI();
9517                    }
9518                }
9519            }
9520        }
9521
9522        // The apk is forward locked (not public) if its code and resources
9523        // are kept in different files. (except for app in either system or
9524        // vendor path).
9525        // TODO grab this value from PackageSettings
9526        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9527            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9528                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9529            }
9530        }
9531
9532        final int userId = ((user == null) ? 0 : user.getIdentifier());
9533        if (ps != null && ps.getInstantApp(userId)) {
9534            scanFlags |= SCAN_AS_INSTANT_APP;
9535        }
9536        if (ps != null && ps.getVirtulalPreload(userId)) {
9537            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9538        }
9539
9540        // Note that we invoke the following method only if we are about to unpack an application
9541        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9542                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9543
9544        /*
9545         * If the system app should be overridden by a previously installed
9546         * data, hide the system app now and let the /data/app scan pick it up
9547         * again.
9548         */
9549        if (shouldHideSystemApp) {
9550            synchronized (mPackages) {
9551                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9552            }
9553        }
9554
9555        return scannedPkg;
9556    }
9557
9558    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9559        // Derive the new package synthetic package name
9560        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9561                + pkg.staticSharedLibVersion);
9562    }
9563
9564    private static String fixProcessName(String defProcessName,
9565            String processName) {
9566        if (processName == null) {
9567            return defProcessName;
9568        }
9569        return processName;
9570    }
9571
9572    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9573            throws PackageManagerException {
9574        if (pkgSetting.signatures.mSignatures != null) {
9575            // Already existing package. Make sure signatures match
9576            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9577                    == PackageManager.SIGNATURE_MATCH;
9578            if (!match) {
9579                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9580                        == PackageManager.SIGNATURE_MATCH;
9581            }
9582            if (!match) {
9583                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9584                        == PackageManager.SIGNATURE_MATCH;
9585            }
9586            if (!match) {
9587                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9588                        + pkg.packageName + " signatures do not match the "
9589                        + "previously installed version; ignoring!");
9590            }
9591        }
9592
9593        // Check for shared user signatures
9594        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9595            // Already existing package. Make sure signatures match
9596            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9597                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9598            if (!match) {
9599                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9600                        == PackageManager.SIGNATURE_MATCH;
9601            }
9602            if (!match) {
9603                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9604                        == PackageManager.SIGNATURE_MATCH;
9605            }
9606            if (!match) {
9607                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9608                        "Package " + pkg.packageName
9609                        + " has no signatures that match those in shared user "
9610                        + pkgSetting.sharedUser.name + "; ignoring!");
9611            }
9612        }
9613    }
9614
9615    /**
9616     * Enforces that only the system UID or root's UID can call a method exposed
9617     * via Binder.
9618     *
9619     * @param message used as message if SecurityException is thrown
9620     * @throws SecurityException if the caller is not system or root
9621     */
9622    private static final void enforceSystemOrRoot(String message) {
9623        final int uid = Binder.getCallingUid();
9624        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9625            throw new SecurityException(message);
9626        }
9627    }
9628
9629    @Override
9630    public void performFstrimIfNeeded() {
9631        enforceSystemOrRoot("Only the system can request fstrim");
9632
9633        // Before everything else, see whether we need to fstrim.
9634        try {
9635            IStorageManager sm = PackageHelper.getStorageManager();
9636            if (sm != null) {
9637                boolean doTrim = false;
9638                final long interval = android.provider.Settings.Global.getLong(
9639                        mContext.getContentResolver(),
9640                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9641                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9642                if (interval > 0) {
9643                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9644                    if (timeSinceLast > interval) {
9645                        doTrim = true;
9646                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9647                                + "; running immediately");
9648                    }
9649                }
9650                if (doTrim) {
9651                    final boolean dexOptDialogShown;
9652                    synchronized (mPackages) {
9653                        dexOptDialogShown = mDexOptDialogShown;
9654                    }
9655                    if (!isFirstBoot() && dexOptDialogShown) {
9656                        try {
9657                            ActivityManager.getService().showBootMessage(
9658                                    mContext.getResources().getString(
9659                                            R.string.android_upgrading_fstrim), true);
9660                        } catch (RemoteException e) {
9661                        }
9662                    }
9663                    sm.runMaintenance();
9664                }
9665            } else {
9666                Slog.e(TAG, "storageManager service unavailable!");
9667            }
9668        } catch (RemoteException e) {
9669            // Can't happen; StorageManagerService is local
9670        }
9671    }
9672
9673    @Override
9674    public void updatePackagesIfNeeded() {
9675        enforceSystemOrRoot("Only the system can request package update");
9676
9677        // We need to re-extract after an OTA.
9678        boolean causeUpgrade = isUpgrade();
9679
9680        // First boot or factory reset.
9681        // Note: we also handle devices that are upgrading to N right now as if it is their
9682        //       first boot, as they do not have profile data.
9683        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9684
9685        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9686        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9687
9688        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9689            return;
9690        }
9691
9692        List<PackageParser.Package> pkgs;
9693        synchronized (mPackages) {
9694            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9695        }
9696
9697        final long startTime = System.nanoTime();
9698        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9699                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9700                    false /* bootComplete */);
9701
9702        final int elapsedTimeSeconds =
9703                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9704
9705        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9706        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9707        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9708        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9709        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9710    }
9711
9712    /*
9713     * Return the prebuilt profile path given a package base code path.
9714     */
9715    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9716        return pkg.baseCodePath + ".prof";
9717    }
9718
9719    /**
9720     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9721     * containing statistics about the invocation. The array consists of three elements,
9722     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9723     * and {@code numberOfPackagesFailed}.
9724     */
9725    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9726            String compilerFilter, boolean bootComplete) {
9727
9728        int numberOfPackagesVisited = 0;
9729        int numberOfPackagesOptimized = 0;
9730        int numberOfPackagesSkipped = 0;
9731        int numberOfPackagesFailed = 0;
9732        final int numberOfPackagesToDexopt = pkgs.size();
9733
9734        for (PackageParser.Package pkg : pkgs) {
9735            numberOfPackagesVisited++;
9736
9737            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9738                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9739                // that are already compiled.
9740                File profileFile = new File(getPrebuildProfilePath(pkg));
9741                // Copy profile if it exists.
9742                if (profileFile.exists()) {
9743                    try {
9744                        // We could also do this lazily before calling dexopt in
9745                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9746                        // is that we don't have a good way to say "do this only once".
9747                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9748                                pkg.applicationInfo.uid, pkg.packageName)) {
9749                            Log.e(TAG, "Installer failed to copy system profile!");
9750                        }
9751                    } catch (Exception e) {
9752                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9753                                e);
9754                    }
9755                }
9756            }
9757
9758            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9759                if (DEBUG_DEXOPT) {
9760                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9761                }
9762                numberOfPackagesSkipped++;
9763                continue;
9764            }
9765
9766            if (DEBUG_DEXOPT) {
9767                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9768                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9769            }
9770
9771            if (showDialog) {
9772                try {
9773                    ActivityManager.getService().showBootMessage(
9774                            mContext.getResources().getString(R.string.android_upgrading_apk,
9775                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9776                } catch (RemoteException e) {
9777                }
9778                synchronized (mPackages) {
9779                    mDexOptDialogShown = true;
9780                }
9781            }
9782
9783            // If the OTA updates a system app which was previously preopted to a non-preopted state
9784            // the app might end up being verified at runtime. That's because by default the apps
9785            // are verify-profile but for preopted apps there's no profile.
9786            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9787            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9788            // filter (by default 'quicken').
9789            // Note that at this stage unused apps are already filtered.
9790            if (isSystemApp(pkg) &&
9791                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9792                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9793                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9794            }
9795
9796            // checkProfiles is false to avoid merging profiles during boot which
9797            // might interfere with background compilation (b/28612421).
9798            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9799            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9800            // trade-off worth doing to save boot time work.
9801            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9802            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9803                    pkg.packageName,
9804                    compilerFilter,
9805                    dexoptFlags));
9806
9807            if (pkg.isSystemApp()) {
9808                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9809                // too much boot after an OTA.
9810                int secondaryDexoptFlags = dexoptFlags |
9811                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9812                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9813                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9814                        pkg.packageName,
9815                        compilerFilter,
9816                        secondaryDexoptFlags));
9817            }
9818
9819            // TODO(shubhamajmera): Record secondary dexopt stats.
9820            switch (primaryDexOptStaus) {
9821                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9822                    numberOfPackagesOptimized++;
9823                    break;
9824                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9825                    numberOfPackagesSkipped++;
9826                    break;
9827                case PackageDexOptimizer.DEX_OPT_FAILED:
9828                    numberOfPackagesFailed++;
9829                    break;
9830                default:
9831                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9832                    break;
9833            }
9834        }
9835
9836        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9837                numberOfPackagesFailed };
9838    }
9839
9840    @Override
9841    public void notifyPackageUse(String packageName, int reason) {
9842        synchronized (mPackages) {
9843            final int callingUid = Binder.getCallingUid();
9844            final int callingUserId = UserHandle.getUserId(callingUid);
9845            if (getInstantAppPackageName(callingUid) != null) {
9846                if (!isCallerSameApp(packageName, callingUid)) {
9847                    return;
9848                }
9849            } else {
9850                if (isInstantApp(packageName, callingUserId)) {
9851                    return;
9852                }
9853            }
9854            notifyPackageUseLocked(packageName, reason);
9855        }
9856    }
9857
9858    private void notifyPackageUseLocked(String packageName, int reason) {
9859        final PackageParser.Package p = mPackages.get(packageName);
9860        if (p == null) {
9861            return;
9862        }
9863        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9864    }
9865
9866    @Override
9867    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9868            List<String> classPaths, String loaderIsa) {
9869        int userId = UserHandle.getCallingUserId();
9870        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9871        if (ai == null) {
9872            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9873                + loadingPackageName + ", user=" + userId);
9874            return;
9875        }
9876        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9877    }
9878
9879    @Override
9880    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9881            IDexModuleRegisterCallback callback) {
9882        int userId = UserHandle.getCallingUserId();
9883        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9884        DexManager.RegisterDexModuleResult result;
9885        if (ai == null) {
9886            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9887                     " calling user. package=" + packageName + ", user=" + userId);
9888            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9889        } else {
9890            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9891        }
9892
9893        if (callback != null) {
9894            mHandler.post(() -> {
9895                try {
9896                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9897                } catch (RemoteException e) {
9898                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9899                }
9900            });
9901        }
9902    }
9903
9904    /**
9905     * Ask the package manager to perform a dex-opt with the given compiler filter.
9906     *
9907     * Note: exposed only for the shell command to allow moving packages explicitly to a
9908     *       definite state.
9909     */
9910    @Override
9911    public boolean performDexOptMode(String packageName,
9912            boolean checkProfiles, String targetCompilerFilter, boolean force,
9913            boolean bootComplete, String splitName) {
9914        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9915                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9916                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9917        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9918                splitName, flags));
9919    }
9920
9921    /**
9922     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9923     * secondary dex files belonging to the given package.
9924     *
9925     * Note: exposed only for the shell command to allow moving packages explicitly to a
9926     *       definite state.
9927     */
9928    @Override
9929    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9930            boolean force) {
9931        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9932                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9933                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9934                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9935        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9936    }
9937
9938    /*package*/ boolean performDexOpt(DexoptOptions options) {
9939        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9940            return false;
9941        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9942            return false;
9943        }
9944
9945        if (options.isDexoptOnlySecondaryDex()) {
9946            return mDexManager.dexoptSecondaryDex(options);
9947        } else {
9948            int dexoptStatus = performDexOptWithStatus(options);
9949            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9950        }
9951    }
9952
9953    /**
9954     * Perform dexopt on the given package and return one of following result:
9955     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9956     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9957     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9958     */
9959    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9960        return performDexOptTraced(options);
9961    }
9962
9963    private int performDexOptTraced(DexoptOptions options) {
9964        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9965        try {
9966            return performDexOptInternal(options);
9967        } finally {
9968            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9969        }
9970    }
9971
9972    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9973    // if the package can now be considered up to date for the given filter.
9974    private int performDexOptInternal(DexoptOptions options) {
9975        PackageParser.Package p;
9976        synchronized (mPackages) {
9977            p = mPackages.get(options.getPackageName());
9978            if (p == null) {
9979                // Package could not be found. Report failure.
9980                return PackageDexOptimizer.DEX_OPT_FAILED;
9981            }
9982            mPackageUsage.maybeWriteAsync(mPackages);
9983            mCompilerStats.maybeWriteAsync();
9984        }
9985        long callingId = Binder.clearCallingIdentity();
9986        try {
9987            synchronized (mInstallLock) {
9988                return performDexOptInternalWithDependenciesLI(p, options);
9989            }
9990        } finally {
9991            Binder.restoreCallingIdentity(callingId);
9992        }
9993    }
9994
9995    public ArraySet<String> getOptimizablePackages() {
9996        ArraySet<String> pkgs = new ArraySet<String>();
9997        synchronized (mPackages) {
9998            for (PackageParser.Package p : mPackages.values()) {
9999                if (PackageDexOptimizer.canOptimizePackage(p)) {
10000                    pkgs.add(p.packageName);
10001                }
10002            }
10003        }
10004        return pkgs;
10005    }
10006
10007    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10008            DexoptOptions options) {
10009        // Select the dex optimizer based on the force parameter.
10010        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10011        //       allocate an object here.
10012        PackageDexOptimizer pdo = options.isForce()
10013                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10014                : mPackageDexOptimizer;
10015
10016        // Dexopt all dependencies first. Note: we ignore the return value and march on
10017        // on errors.
10018        // Note that we are going to call performDexOpt on those libraries as many times as
10019        // they are referenced in packages. When we do a batch of performDexOpt (for example
10020        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10021        // and the first package that uses the library will dexopt it. The
10022        // others will see that the compiled code for the library is up to date.
10023        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10024        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10025        if (!deps.isEmpty()) {
10026            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10027                    options.getCompilerFilter(), options.getSplitName(),
10028                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10029            for (PackageParser.Package depPackage : deps) {
10030                // TODO: Analyze and investigate if we (should) profile libraries.
10031                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10032                        getOrCreateCompilerPackageStats(depPackage),
10033                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10034            }
10035        }
10036        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10037                getOrCreateCompilerPackageStats(p),
10038                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10039    }
10040
10041    /**
10042     * Reconcile the information we have about the secondary dex files belonging to
10043     * {@code packagName} and the actual dex files. For all dex files that were
10044     * deleted, update the internal records and delete the generated oat files.
10045     */
10046    @Override
10047    public void reconcileSecondaryDexFiles(String packageName) {
10048        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10049            return;
10050        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10051            return;
10052        }
10053        mDexManager.reconcileSecondaryDexFiles(packageName);
10054    }
10055
10056    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10057    // a reference there.
10058    /*package*/ DexManager getDexManager() {
10059        return mDexManager;
10060    }
10061
10062    /**
10063     * Execute the background dexopt job immediately.
10064     */
10065    @Override
10066    public boolean runBackgroundDexoptJob() {
10067        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10068            return false;
10069        }
10070        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10071    }
10072
10073    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10074        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10075                || p.usesStaticLibraries != null) {
10076            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10077            Set<String> collectedNames = new HashSet<>();
10078            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10079
10080            retValue.remove(p);
10081
10082            return retValue;
10083        } else {
10084            return Collections.emptyList();
10085        }
10086    }
10087
10088    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10089            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10090        if (!collectedNames.contains(p.packageName)) {
10091            collectedNames.add(p.packageName);
10092            collected.add(p);
10093
10094            if (p.usesLibraries != null) {
10095                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10096                        null, collected, collectedNames);
10097            }
10098            if (p.usesOptionalLibraries != null) {
10099                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10100                        null, collected, collectedNames);
10101            }
10102            if (p.usesStaticLibraries != null) {
10103                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10104                        p.usesStaticLibrariesVersions, collected, collectedNames);
10105            }
10106        }
10107    }
10108
10109    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10110            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10111        final int libNameCount = libs.size();
10112        for (int i = 0; i < libNameCount; i++) {
10113            String libName = libs.get(i);
10114            int version = (versions != null && versions.length == libNameCount)
10115                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10116            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10117            if (libPkg != null) {
10118                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10119            }
10120        }
10121    }
10122
10123    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10124        synchronized (mPackages) {
10125            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10126            if (libEntry != null) {
10127                return mPackages.get(libEntry.apk);
10128            }
10129            return null;
10130        }
10131    }
10132
10133    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10134        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10135        if (versionedLib == null) {
10136            return null;
10137        }
10138        return versionedLib.get(version);
10139    }
10140
10141    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10142        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10143                pkg.staticSharedLibName);
10144        if (versionedLib == null) {
10145            return null;
10146        }
10147        int previousLibVersion = -1;
10148        final int versionCount = versionedLib.size();
10149        for (int i = 0; i < versionCount; i++) {
10150            final int libVersion = versionedLib.keyAt(i);
10151            if (libVersion < pkg.staticSharedLibVersion) {
10152                previousLibVersion = Math.max(previousLibVersion, libVersion);
10153            }
10154        }
10155        if (previousLibVersion >= 0) {
10156            return versionedLib.get(previousLibVersion);
10157        }
10158        return null;
10159    }
10160
10161    public void shutdown() {
10162        mPackageUsage.writeNow(mPackages);
10163        mCompilerStats.writeNow();
10164        mDexManager.writePackageDexUsageNow();
10165    }
10166
10167    @Override
10168    public void dumpProfiles(String packageName) {
10169        PackageParser.Package pkg;
10170        synchronized (mPackages) {
10171            pkg = mPackages.get(packageName);
10172            if (pkg == null) {
10173                throw new IllegalArgumentException("Unknown package: " + packageName);
10174            }
10175        }
10176        /* Only the shell, root, or the app user should be able to dump profiles. */
10177        int callingUid = Binder.getCallingUid();
10178        if (callingUid != Process.SHELL_UID &&
10179            callingUid != Process.ROOT_UID &&
10180            callingUid != pkg.applicationInfo.uid) {
10181            throw new SecurityException("dumpProfiles");
10182        }
10183
10184        synchronized (mInstallLock) {
10185            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10186            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10187            try {
10188                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10189                String codePaths = TextUtils.join(";", allCodePaths);
10190                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10191            } catch (InstallerException e) {
10192                Slog.w(TAG, "Failed to dump profiles", e);
10193            }
10194            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10195        }
10196    }
10197
10198    @Override
10199    public void forceDexOpt(String packageName) {
10200        enforceSystemOrRoot("forceDexOpt");
10201
10202        PackageParser.Package pkg;
10203        synchronized (mPackages) {
10204            pkg = mPackages.get(packageName);
10205            if (pkg == null) {
10206                throw new IllegalArgumentException("Unknown package: " + packageName);
10207            }
10208        }
10209
10210        synchronized (mInstallLock) {
10211            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10212
10213            // Whoever is calling forceDexOpt wants a compiled package.
10214            // Don't use profiles since that may cause compilation to be skipped.
10215            final int res = performDexOptInternalWithDependenciesLI(
10216                    pkg,
10217                    new DexoptOptions(packageName,
10218                            getDefaultCompilerFilter(),
10219                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10220
10221            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10222            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10223                throw new IllegalStateException("Failed to dexopt: " + res);
10224            }
10225        }
10226    }
10227
10228    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10229        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10230            Slog.w(TAG, "Unable to update from " + oldPkg.name
10231                    + " to " + newPkg.packageName
10232                    + ": old package not in system partition");
10233            return false;
10234        } else if (mPackages.get(oldPkg.name) != null) {
10235            Slog.w(TAG, "Unable to update from " + oldPkg.name
10236                    + " to " + newPkg.packageName
10237                    + ": old package still exists");
10238            return false;
10239        }
10240        return true;
10241    }
10242
10243    void removeCodePathLI(File codePath) {
10244        if (codePath.isDirectory()) {
10245            try {
10246                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10247            } catch (InstallerException e) {
10248                Slog.w(TAG, "Failed to remove code path", e);
10249            }
10250        } else {
10251            codePath.delete();
10252        }
10253    }
10254
10255    private int[] resolveUserIds(int userId) {
10256        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10257    }
10258
10259    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10260        if (pkg == null) {
10261            Slog.wtf(TAG, "Package was null!", new Throwable());
10262            return;
10263        }
10264        clearAppDataLeafLIF(pkg, userId, flags);
10265        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10266        for (int i = 0; i < childCount; i++) {
10267            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10268        }
10269    }
10270
10271    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10272        final PackageSetting ps;
10273        synchronized (mPackages) {
10274            ps = mSettings.mPackages.get(pkg.packageName);
10275        }
10276        for (int realUserId : resolveUserIds(userId)) {
10277            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10278            try {
10279                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10280                        ceDataInode);
10281            } catch (InstallerException e) {
10282                Slog.w(TAG, String.valueOf(e));
10283            }
10284        }
10285    }
10286
10287    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10288        if (pkg == null) {
10289            Slog.wtf(TAG, "Package was null!", new Throwable());
10290            return;
10291        }
10292        destroyAppDataLeafLIF(pkg, userId, flags);
10293        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10294        for (int i = 0; i < childCount; i++) {
10295            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10296        }
10297    }
10298
10299    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10300        final PackageSetting ps;
10301        synchronized (mPackages) {
10302            ps = mSettings.mPackages.get(pkg.packageName);
10303        }
10304        for (int realUserId : resolveUserIds(userId)) {
10305            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10306            try {
10307                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10308                        ceDataInode);
10309            } catch (InstallerException e) {
10310                Slog.w(TAG, String.valueOf(e));
10311            }
10312            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10313        }
10314    }
10315
10316    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10317        if (pkg == null) {
10318            Slog.wtf(TAG, "Package was null!", new Throwable());
10319            return;
10320        }
10321        destroyAppProfilesLeafLIF(pkg);
10322        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10323        for (int i = 0; i < childCount; i++) {
10324            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10325        }
10326    }
10327
10328    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10329        try {
10330            mInstaller.destroyAppProfiles(pkg.packageName);
10331        } catch (InstallerException e) {
10332            Slog.w(TAG, String.valueOf(e));
10333        }
10334    }
10335
10336    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10337        if (pkg == null) {
10338            Slog.wtf(TAG, "Package was null!", new Throwable());
10339            return;
10340        }
10341        clearAppProfilesLeafLIF(pkg);
10342        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10343        for (int i = 0; i < childCount; i++) {
10344            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10345        }
10346    }
10347
10348    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10349        try {
10350            mInstaller.clearAppProfiles(pkg.packageName);
10351        } catch (InstallerException e) {
10352            Slog.w(TAG, String.valueOf(e));
10353        }
10354    }
10355
10356    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10357            long lastUpdateTime) {
10358        // Set parent install/update time
10359        PackageSetting ps = (PackageSetting) pkg.mExtras;
10360        if (ps != null) {
10361            ps.firstInstallTime = firstInstallTime;
10362            ps.lastUpdateTime = lastUpdateTime;
10363        }
10364        // Set children install/update time
10365        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10366        for (int i = 0; i < childCount; i++) {
10367            PackageParser.Package childPkg = pkg.childPackages.get(i);
10368            ps = (PackageSetting) childPkg.mExtras;
10369            if (ps != null) {
10370                ps.firstInstallTime = firstInstallTime;
10371                ps.lastUpdateTime = lastUpdateTime;
10372            }
10373        }
10374    }
10375
10376    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10377            PackageParser.Package changingLib) {
10378        if (file.path != null) {
10379            usesLibraryFiles.add(file.path);
10380            return;
10381        }
10382        PackageParser.Package p = mPackages.get(file.apk);
10383        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10384            // If we are doing this while in the middle of updating a library apk,
10385            // then we need to make sure to use that new apk for determining the
10386            // dependencies here.  (We haven't yet finished committing the new apk
10387            // to the package manager state.)
10388            if (p == null || p.packageName.equals(changingLib.packageName)) {
10389                p = changingLib;
10390            }
10391        }
10392        if (p != null) {
10393            usesLibraryFiles.addAll(p.getAllCodePaths());
10394            if (p.usesLibraryFiles != null) {
10395                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10396            }
10397        }
10398    }
10399
10400    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10401            PackageParser.Package changingLib) throws PackageManagerException {
10402        if (pkg == null) {
10403            return;
10404        }
10405        ArraySet<String> usesLibraryFiles = null;
10406        if (pkg.usesLibraries != null) {
10407            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10408                    null, null, pkg.packageName, changingLib, true,
10409                    pkg.applicationInfo.targetSdkVersion, null);
10410        }
10411        if (pkg.usesStaticLibraries != null) {
10412            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10413                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10414                    pkg.packageName, changingLib, true,
10415                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10416        }
10417        if (pkg.usesOptionalLibraries != null) {
10418            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10419                    null, null, pkg.packageName, changingLib, false,
10420                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10421        }
10422        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10423            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10424        } else {
10425            pkg.usesLibraryFiles = null;
10426        }
10427    }
10428
10429    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10430            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10431            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10432            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10433            throws PackageManagerException {
10434        final int libCount = requestedLibraries.size();
10435        for (int i = 0; i < libCount; i++) {
10436            final String libName = requestedLibraries.get(i);
10437            final int libVersion = requiredVersions != null ? requiredVersions[i]
10438                    : SharedLibraryInfo.VERSION_UNDEFINED;
10439            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10440            if (libEntry == null) {
10441                if (required) {
10442                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10443                            "Package " + packageName + " requires unavailable shared library "
10444                                    + libName + "; failing!");
10445                } else if (DEBUG_SHARED_LIBRARIES) {
10446                    Slog.i(TAG, "Package " + packageName
10447                            + " desires unavailable shared library "
10448                            + libName + "; ignoring!");
10449                }
10450            } else {
10451                if (requiredVersions != null && requiredCertDigests != null) {
10452                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10453                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10454                            "Package " + packageName + " requires unavailable static shared"
10455                                    + " library " + libName + " version "
10456                                    + libEntry.info.getVersion() + "; failing!");
10457                    }
10458
10459                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10460                    if (libPkg == null) {
10461                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10462                                "Package " + packageName + " requires unavailable static shared"
10463                                        + " library; failing!");
10464                    }
10465
10466                    final String[] expectedCertDigests = requiredCertDigests[i];
10467                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10468                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10469                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10470                            : PackageUtils.computeSignaturesSha256Digests(
10471                                    new Signature[]{libPkg.mSignatures[0]});
10472
10473                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10474                    // target O we don't parse the "additional-certificate" tags similarly
10475                    // how we only consider all certs only for apps targeting O (see above).
10476                    // Therefore, the size check is safe to make.
10477                    if (expectedCertDigests.length != libCertDigests.length) {
10478                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10479                                "Package " + packageName + " requires differently signed" +
10480                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10481                    }
10482
10483                    // Use a predictable order as signature order may vary
10484                    Arrays.sort(libCertDigests);
10485                    Arrays.sort(expectedCertDigests);
10486
10487                    final int certCount = libCertDigests.length;
10488                    for (int j = 0; j < certCount; j++) {
10489                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10490                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10491                                    "Package " + packageName + " requires differently signed" +
10492                                            " static shared library; failing!");
10493                        }
10494                    }
10495                }
10496
10497                if (outUsedLibraries == null) {
10498                    outUsedLibraries = new ArraySet<>();
10499                }
10500                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10501            }
10502        }
10503        return outUsedLibraries;
10504    }
10505
10506    private static boolean hasString(List<String> list, List<String> which) {
10507        if (list == null) {
10508            return false;
10509        }
10510        for (int i=list.size()-1; i>=0; i--) {
10511            for (int j=which.size()-1; j>=0; j--) {
10512                if (which.get(j).equals(list.get(i))) {
10513                    return true;
10514                }
10515            }
10516        }
10517        return false;
10518    }
10519
10520    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10521            PackageParser.Package changingPkg) {
10522        ArrayList<PackageParser.Package> res = null;
10523        for (PackageParser.Package pkg : mPackages.values()) {
10524            if (changingPkg != null
10525                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10526                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10527                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10528                            changingPkg.staticSharedLibName)) {
10529                return null;
10530            }
10531            if (res == null) {
10532                res = new ArrayList<>();
10533            }
10534            res.add(pkg);
10535            try {
10536                updateSharedLibrariesLPr(pkg, changingPkg);
10537            } catch (PackageManagerException e) {
10538                // If a system app update or an app and a required lib missing we
10539                // delete the package and for updated system apps keep the data as
10540                // it is better for the user to reinstall than to be in an limbo
10541                // state. Also libs disappearing under an app should never happen
10542                // - just in case.
10543                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10544                    final int flags = pkg.isUpdatedSystemApp()
10545                            ? PackageManager.DELETE_KEEP_DATA : 0;
10546                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10547                            flags , null, true, null);
10548                }
10549                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10550            }
10551        }
10552        return res;
10553    }
10554
10555    /**
10556     * Derive the value of the {@code cpuAbiOverride} based on the provided
10557     * value and an optional stored value from the package settings.
10558     */
10559    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10560        String cpuAbiOverride = null;
10561
10562        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10563            cpuAbiOverride = null;
10564        } else if (abiOverride != null) {
10565            cpuAbiOverride = abiOverride;
10566        } else if (settings != null) {
10567            cpuAbiOverride = settings.cpuAbiOverrideString;
10568        }
10569
10570        return cpuAbiOverride;
10571    }
10572
10573    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10574            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10575                    throws PackageManagerException {
10576        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10577        // If the package has children and this is the first dive in the function
10578        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10579        // whether all packages (parent and children) would be successfully scanned
10580        // before the actual scan since scanning mutates internal state and we want
10581        // to atomically install the package and its children.
10582        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10583            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10584                scanFlags |= SCAN_CHECK_ONLY;
10585            }
10586        } else {
10587            scanFlags &= ~SCAN_CHECK_ONLY;
10588        }
10589
10590        final PackageParser.Package scannedPkg;
10591        try {
10592            // Scan the parent
10593            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10594            // Scan the children
10595            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10596            for (int i = 0; i < childCount; i++) {
10597                PackageParser.Package childPkg = pkg.childPackages.get(i);
10598                scanPackageLI(childPkg, policyFlags,
10599                        scanFlags, currentTime, user);
10600            }
10601        } finally {
10602            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10603        }
10604
10605        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10606            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10607        }
10608
10609        return scannedPkg;
10610    }
10611
10612    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10613            int scanFlags, long currentTime, @Nullable UserHandle user)
10614                    throws PackageManagerException {
10615        boolean success = false;
10616        try {
10617            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10618                    currentTime, user);
10619            success = true;
10620            return res;
10621        } finally {
10622            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10623                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10624                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10625                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10626                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10627            }
10628        }
10629    }
10630
10631    /**
10632     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10633     */
10634    private static boolean apkHasCode(String fileName) {
10635        StrictJarFile jarFile = null;
10636        try {
10637            jarFile = new StrictJarFile(fileName,
10638                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10639            return jarFile.findEntry("classes.dex") != null;
10640        } catch (IOException ignore) {
10641        } finally {
10642            try {
10643                if (jarFile != null) {
10644                    jarFile.close();
10645                }
10646            } catch (IOException ignore) {}
10647        }
10648        return false;
10649    }
10650
10651    /**
10652     * Enforces code policy for the package. This ensures that if an APK has
10653     * declared hasCode="true" in its manifest that the APK actually contains
10654     * code.
10655     *
10656     * @throws PackageManagerException If bytecode could not be found when it should exist
10657     */
10658    private static void assertCodePolicy(PackageParser.Package pkg)
10659            throws PackageManagerException {
10660        final boolean shouldHaveCode =
10661                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10662        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10663            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10664                    "Package " + pkg.baseCodePath + " code is missing");
10665        }
10666
10667        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10668            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10669                final boolean splitShouldHaveCode =
10670                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10671                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10672                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10673                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10674                }
10675            }
10676        }
10677    }
10678
10679    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10680            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10681                    throws PackageManagerException {
10682        if (DEBUG_PACKAGE_SCANNING) {
10683            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10684                Log.d(TAG, "Scanning package " + pkg.packageName);
10685        }
10686
10687        applyPolicy(pkg, policyFlags);
10688
10689        assertPackageIsValid(pkg, policyFlags, scanFlags);
10690
10691        // Initialize package source and resource directories
10692        final File scanFile = new File(pkg.codePath);
10693        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10694        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10695
10696        SharedUserSetting suid = null;
10697        PackageSetting pkgSetting = null;
10698
10699        // Getting the package setting may have a side-effect, so if we
10700        // are only checking if scan would succeed, stash a copy of the
10701        // old setting to restore at the end.
10702        PackageSetting nonMutatedPs = null;
10703
10704        // We keep references to the derived CPU Abis from settings in oder to reuse
10705        // them in the case where we're not upgrading or booting for the first time.
10706        String primaryCpuAbiFromSettings = null;
10707        String secondaryCpuAbiFromSettings = null;
10708
10709        // writer
10710        synchronized (mPackages) {
10711            if (pkg.mSharedUserId != null) {
10712                // SIDE EFFECTS; may potentially allocate a new shared user
10713                suid = mSettings.getSharedUserLPw(
10714                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10715                if (DEBUG_PACKAGE_SCANNING) {
10716                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10717                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10718                                + "): packages=" + suid.packages);
10719                }
10720            }
10721
10722            // Check if we are renaming from an original package name.
10723            PackageSetting origPackage = null;
10724            String realName = null;
10725            if (pkg.mOriginalPackages != null) {
10726                // This package may need to be renamed to a previously
10727                // installed name.  Let's check on that...
10728                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10729                if (pkg.mOriginalPackages.contains(renamed)) {
10730                    // This package had originally been installed as the
10731                    // original name, and we have already taken care of
10732                    // transitioning to the new one.  Just update the new
10733                    // one to continue using the old name.
10734                    realName = pkg.mRealPackage;
10735                    if (!pkg.packageName.equals(renamed)) {
10736                        // Callers into this function may have already taken
10737                        // care of renaming the package; only do it here if
10738                        // it is not already done.
10739                        pkg.setPackageName(renamed);
10740                    }
10741                } else {
10742                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10743                        if ((origPackage = mSettings.getPackageLPr(
10744                                pkg.mOriginalPackages.get(i))) != null) {
10745                            // We do have the package already installed under its
10746                            // original name...  should we use it?
10747                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10748                                // New package is not compatible with original.
10749                                origPackage = null;
10750                                continue;
10751                            } else if (origPackage.sharedUser != null) {
10752                                // Make sure uid is compatible between packages.
10753                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10754                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10755                                            + " to " + pkg.packageName + ": old uid "
10756                                            + origPackage.sharedUser.name
10757                                            + " differs from " + pkg.mSharedUserId);
10758                                    origPackage = null;
10759                                    continue;
10760                                }
10761                                // TODO: Add case when shared user id is added [b/28144775]
10762                            } else {
10763                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10764                                        + pkg.packageName + " to old name " + origPackage.name);
10765                            }
10766                            break;
10767                        }
10768                    }
10769                }
10770            }
10771
10772            if (mTransferedPackages.contains(pkg.packageName)) {
10773                Slog.w(TAG, "Package " + pkg.packageName
10774                        + " was transferred to another, but its .apk remains");
10775            }
10776
10777            // See comments in nonMutatedPs declaration
10778            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10779                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10780                if (foundPs != null) {
10781                    nonMutatedPs = new PackageSetting(foundPs);
10782                }
10783            }
10784
10785            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10786                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10787                if (foundPs != null) {
10788                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10789                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10790                }
10791            }
10792
10793            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10794            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10795                PackageManagerService.reportSettingsProblem(Log.WARN,
10796                        "Package " + pkg.packageName + " shared user changed from "
10797                                + (pkgSetting.sharedUser != null
10798                                        ? pkgSetting.sharedUser.name : "<nothing>")
10799                                + " to "
10800                                + (suid != null ? suid.name : "<nothing>")
10801                                + "; replacing with new");
10802                pkgSetting = null;
10803            }
10804            final PackageSetting oldPkgSetting =
10805                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10806            final PackageSetting disabledPkgSetting =
10807                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10808
10809            String[] usesStaticLibraries = null;
10810            if (pkg.usesStaticLibraries != null) {
10811                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10812                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10813            }
10814
10815            if (pkgSetting == null) {
10816                final String parentPackageName = (pkg.parentPackage != null)
10817                        ? pkg.parentPackage.packageName : null;
10818                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10819                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10820                // REMOVE SharedUserSetting from method; update in a separate call
10821                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10822                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10823                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10824                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10825                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10826                        true /*allowInstall*/, instantApp, virtualPreload,
10827                        parentPackageName, pkg.getChildPackageNames(),
10828                        UserManagerService.getInstance(), usesStaticLibraries,
10829                        pkg.usesStaticLibrariesVersions);
10830                // SIDE EFFECTS; updates system state; move elsewhere
10831                if (origPackage != null) {
10832                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10833                }
10834                mSettings.addUserToSettingLPw(pkgSetting);
10835            } else {
10836                // REMOVE SharedUserSetting from method; update in a separate call.
10837                //
10838                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10839                // secondaryCpuAbi are not known at this point so we always update them
10840                // to null here, only to reset them at a later point.
10841                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10842                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10843                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10844                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10845                        UserManagerService.getInstance(), usesStaticLibraries,
10846                        pkg.usesStaticLibrariesVersions);
10847            }
10848            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10849            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10850
10851            // SIDE EFFECTS; modifies system state; move elsewhere
10852            if (pkgSetting.origPackage != null) {
10853                // If we are first transitioning from an original package,
10854                // fix up the new package's name now.  We need to do this after
10855                // looking up the package under its new name, so getPackageLP
10856                // can take care of fiddling things correctly.
10857                pkg.setPackageName(origPackage.name);
10858
10859                // File a report about this.
10860                String msg = "New package " + pkgSetting.realName
10861                        + " renamed to replace old package " + pkgSetting.name;
10862                reportSettingsProblem(Log.WARN, msg);
10863
10864                // Make a note of it.
10865                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10866                    mTransferedPackages.add(origPackage.name);
10867                }
10868
10869                // No longer need to retain this.
10870                pkgSetting.origPackage = null;
10871            }
10872
10873            // SIDE EFFECTS; modifies system state; move elsewhere
10874            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10875                // Make a note of it.
10876                mTransferedPackages.add(pkg.packageName);
10877            }
10878
10879            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10880                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10881            }
10882
10883            if ((scanFlags & SCAN_BOOTING) == 0
10884                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10885                // Check all shared libraries and map to their actual file path.
10886                // We only do this here for apps not on a system dir, because those
10887                // are the only ones that can fail an install due to this.  We
10888                // will take care of the system apps by updating all of their
10889                // library paths after the scan is done. Also during the initial
10890                // scan don't update any libs as we do this wholesale after all
10891                // apps are scanned to avoid dependency based scanning.
10892                updateSharedLibrariesLPr(pkg, null);
10893            }
10894
10895            if (mFoundPolicyFile) {
10896                SELinuxMMAC.assignSeInfoValue(pkg);
10897            }
10898            pkg.applicationInfo.uid = pkgSetting.appId;
10899            pkg.mExtras = pkgSetting;
10900
10901
10902            // Static shared libs have same package with different versions where
10903            // we internally use a synthetic package name to allow multiple versions
10904            // of the same package, therefore we need to compare signatures against
10905            // the package setting for the latest library version.
10906            PackageSetting signatureCheckPs = pkgSetting;
10907            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10908                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10909                if (libraryEntry != null) {
10910                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10911                }
10912            }
10913
10914            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10915                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10916                    // We just determined the app is signed correctly, so bring
10917                    // over the latest parsed certs.
10918                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10919                } else {
10920                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10921                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10922                                "Package " + pkg.packageName + " upgrade keys do not match the "
10923                                + "previously installed version");
10924                    } else {
10925                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10926                        String msg = "System package " + pkg.packageName
10927                                + " signature changed; retaining data.";
10928                        reportSettingsProblem(Log.WARN, msg);
10929                    }
10930                }
10931            } else {
10932                try {
10933                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10934                    verifySignaturesLP(signatureCheckPs, pkg);
10935                    // We just determined the app is signed correctly, so bring
10936                    // over the latest parsed certs.
10937                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10938                } catch (PackageManagerException e) {
10939                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10940                        throw e;
10941                    }
10942                    // The signature has changed, but this package is in the system
10943                    // image...  let's recover!
10944                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10945                    // However...  if this package is part of a shared user, but it
10946                    // doesn't match the signature of the shared user, let's fail.
10947                    // What this means is that you can't change the signatures
10948                    // associated with an overall shared user, which doesn't seem all
10949                    // that unreasonable.
10950                    if (signatureCheckPs.sharedUser != null) {
10951                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10952                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10953                            throw new PackageManagerException(
10954                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10955                                    "Signature mismatch for shared user: "
10956                                            + pkgSetting.sharedUser);
10957                        }
10958                    }
10959                    // File a report about this.
10960                    String msg = "System package " + pkg.packageName
10961                            + " signature changed; retaining data.";
10962                    reportSettingsProblem(Log.WARN, msg);
10963                }
10964            }
10965
10966            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10967                // This package wants to adopt ownership of permissions from
10968                // another package.
10969                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10970                    final String origName = pkg.mAdoptPermissions.get(i);
10971                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10972                    if (orig != null) {
10973                        if (verifyPackageUpdateLPr(orig, pkg)) {
10974                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10975                                    + pkg.packageName);
10976                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10977                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10978                        }
10979                    }
10980                }
10981            }
10982        }
10983
10984        pkg.applicationInfo.processName = fixProcessName(
10985                pkg.applicationInfo.packageName,
10986                pkg.applicationInfo.processName);
10987
10988        if (pkg != mPlatformPackage) {
10989            // Get all of our default paths setup
10990            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10991        }
10992
10993        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10994
10995        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10996            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10997                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10998                final boolean extractNativeLibs = !pkg.isLibrary();
10999                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
11000                        mAppLib32InstallDir);
11001                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11002
11003                // Some system apps still use directory structure for native libraries
11004                // in which case we might end up not detecting abi solely based on apk
11005                // structure. Try to detect abi based on directory structure.
11006                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11007                        pkg.applicationInfo.primaryCpuAbi == null) {
11008                    setBundledAppAbisAndRoots(pkg, pkgSetting);
11009                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11010                }
11011            } else {
11012                // This is not a first boot or an upgrade, don't bother deriving the
11013                // ABI during the scan. Instead, trust the value that was stored in the
11014                // package setting.
11015                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11016                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11017
11018                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11019
11020                if (DEBUG_ABI_SELECTION) {
11021                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11022                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11023                        pkg.applicationInfo.secondaryCpuAbi);
11024                }
11025            }
11026        } else {
11027            if ((scanFlags & SCAN_MOVE) != 0) {
11028                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11029                // but we already have this packages package info in the PackageSetting. We just
11030                // use that and derive the native library path based on the new codepath.
11031                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11032                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11033            }
11034
11035            // Set native library paths again. For moves, the path will be updated based on the
11036            // ABIs we've determined above. For non-moves, the path will be updated based on the
11037            // ABIs we determined during compilation, but the path will depend on the final
11038            // package path (after the rename away from the stage path).
11039            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11040        }
11041
11042        // This is a special case for the "system" package, where the ABI is
11043        // dictated by the zygote configuration (and init.rc). We should keep track
11044        // of this ABI so that we can deal with "normal" applications that run under
11045        // the same UID correctly.
11046        if (mPlatformPackage == pkg) {
11047            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11048                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11049        }
11050
11051        // If there's a mismatch between the abi-override in the package setting
11052        // and the abiOverride specified for the install. Warn about this because we
11053        // would've already compiled the app without taking the package setting into
11054        // account.
11055        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11056            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11057                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11058                        " for package " + pkg.packageName);
11059            }
11060        }
11061
11062        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11063        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11064        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11065
11066        // Copy the derived override back to the parsed package, so that we can
11067        // update the package settings accordingly.
11068        pkg.cpuAbiOverride = cpuAbiOverride;
11069
11070        if (DEBUG_ABI_SELECTION) {
11071            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11072                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11073                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11074        }
11075
11076        // Push the derived path down into PackageSettings so we know what to
11077        // clean up at uninstall time.
11078        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11079
11080        if (DEBUG_ABI_SELECTION) {
11081            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11082                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11083                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11084        }
11085
11086        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11087        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11088            // We don't do this here during boot because we can do it all
11089            // at once after scanning all existing packages.
11090            //
11091            // We also do this *before* we perform dexopt on this package, so that
11092            // we can avoid redundant dexopts, and also to make sure we've got the
11093            // code and package path correct.
11094            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11095        }
11096
11097        if (mFactoryTest && pkg.requestedPermissions.contains(
11098                android.Manifest.permission.FACTORY_TEST)) {
11099            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11100        }
11101
11102        if (isSystemApp(pkg)) {
11103            pkgSetting.isOrphaned = true;
11104        }
11105
11106        // Take care of first install / last update times.
11107        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11108        if (currentTime != 0) {
11109            if (pkgSetting.firstInstallTime == 0) {
11110                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11111            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11112                pkgSetting.lastUpdateTime = currentTime;
11113            }
11114        } else if (pkgSetting.firstInstallTime == 0) {
11115            // We need *something*.  Take time time stamp of the file.
11116            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11117        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11118            if (scanFileTime != pkgSetting.timeStamp) {
11119                // A package on the system image has changed; consider this
11120                // to be an update.
11121                pkgSetting.lastUpdateTime = scanFileTime;
11122            }
11123        }
11124        pkgSetting.setTimeStamp(scanFileTime);
11125
11126        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11127            if (nonMutatedPs != null) {
11128                synchronized (mPackages) {
11129                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11130                }
11131            }
11132        } else {
11133            final int userId = user == null ? 0 : user.getIdentifier();
11134            // Modify state for the given package setting
11135            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11136                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11137            if (pkgSetting.getInstantApp(userId)) {
11138                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11139            }
11140        }
11141        return pkg;
11142    }
11143
11144    /**
11145     * Applies policy to the parsed package based upon the given policy flags.
11146     * Ensures the package is in a good state.
11147     * <p>
11148     * Implementation detail: This method must NOT have any side effect. It would
11149     * ideally be static, but, it requires locks to read system state.
11150     */
11151    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11152        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11153            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11154            if (pkg.applicationInfo.isDirectBootAware()) {
11155                // we're direct boot aware; set for all components
11156                for (PackageParser.Service s : pkg.services) {
11157                    s.info.encryptionAware = s.info.directBootAware = true;
11158                }
11159                for (PackageParser.Provider p : pkg.providers) {
11160                    p.info.encryptionAware = p.info.directBootAware = true;
11161                }
11162                for (PackageParser.Activity a : pkg.activities) {
11163                    a.info.encryptionAware = a.info.directBootAware = true;
11164                }
11165                for (PackageParser.Activity r : pkg.receivers) {
11166                    r.info.encryptionAware = r.info.directBootAware = true;
11167                }
11168            }
11169            if (compressedFileExists(pkg.codePath)) {
11170                pkg.isStub = true;
11171            }
11172        } else {
11173            // Only allow system apps to be flagged as core apps.
11174            pkg.coreApp = false;
11175            // clear flags not applicable to regular apps
11176            pkg.applicationInfo.privateFlags &=
11177                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11178            pkg.applicationInfo.privateFlags &=
11179                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11180        }
11181        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11182
11183        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11184            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11185        }
11186
11187        if (!isSystemApp(pkg)) {
11188            // Only system apps can use these features.
11189            pkg.mOriginalPackages = null;
11190            pkg.mRealPackage = null;
11191            pkg.mAdoptPermissions = null;
11192        }
11193    }
11194
11195    /**
11196     * Asserts the parsed package is valid according to the given policy. If the
11197     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11198     * <p>
11199     * Implementation detail: This method must NOT have any side effects. It would
11200     * ideally be static, but, it requires locks to read system state.
11201     *
11202     * @throws PackageManagerException If the package fails any of the validation checks
11203     */
11204    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11205            throws PackageManagerException {
11206        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11207            assertCodePolicy(pkg);
11208        }
11209
11210        if (pkg.applicationInfo.getCodePath() == null ||
11211                pkg.applicationInfo.getResourcePath() == null) {
11212            // Bail out. The resource and code paths haven't been set.
11213            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11214                    "Code and resource paths haven't been set correctly");
11215        }
11216
11217        // Make sure we're not adding any bogus keyset info
11218        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11219        ksms.assertScannedPackageValid(pkg);
11220
11221        synchronized (mPackages) {
11222            // The special "android" package can only be defined once
11223            if (pkg.packageName.equals("android")) {
11224                if (mAndroidApplication != null) {
11225                    Slog.w(TAG, "*************************************************");
11226                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11227                    Slog.w(TAG, " codePath=" + pkg.codePath);
11228                    Slog.w(TAG, "*************************************************");
11229                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11230                            "Core android package being redefined.  Skipping.");
11231                }
11232            }
11233
11234            // A package name must be unique; don't allow duplicates
11235            if (mPackages.containsKey(pkg.packageName)) {
11236                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11237                        "Application package " + pkg.packageName
11238                        + " already installed.  Skipping duplicate.");
11239            }
11240
11241            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11242                // Static libs have a synthetic package name containing the version
11243                // but we still want the base name to be unique.
11244                if (mPackages.containsKey(pkg.manifestPackageName)) {
11245                    throw new PackageManagerException(
11246                            "Duplicate static shared lib provider package");
11247                }
11248
11249                // Static shared libraries should have at least O target SDK
11250                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11251                    throw new PackageManagerException(
11252                            "Packages declaring static-shared libs must target O SDK or higher");
11253                }
11254
11255                // Package declaring static a shared lib cannot be instant apps
11256                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11257                    throw new PackageManagerException(
11258                            "Packages declaring static-shared libs cannot be instant apps");
11259                }
11260
11261                // Package declaring static a shared lib cannot be renamed since the package
11262                // name is synthetic and apps can't code around package manager internals.
11263                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11264                    throw new PackageManagerException(
11265                            "Packages declaring static-shared libs cannot be renamed");
11266                }
11267
11268                // Package declaring static a shared lib cannot declare child packages
11269                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11270                    throw new PackageManagerException(
11271                            "Packages declaring static-shared libs cannot have child packages");
11272                }
11273
11274                // Package declaring static a shared lib cannot declare dynamic libs
11275                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11276                    throw new PackageManagerException(
11277                            "Packages declaring static-shared libs cannot declare dynamic libs");
11278                }
11279
11280                // Package declaring static a shared lib cannot declare shared users
11281                if (pkg.mSharedUserId != null) {
11282                    throw new PackageManagerException(
11283                            "Packages declaring static-shared libs cannot declare shared users");
11284                }
11285
11286                // Static shared libs cannot declare activities
11287                if (!pkg.activities.isEmpty()) {
11288                    throw new PackageManagerException(
11289                            "Static shared libs cannot declare activities");
11290                }
11291
11292                // Static shared libs cannot declare services
11293                if (!pkg.services.isEmpty()) {
11294                    throw new PackageManagerException(
11295                            "Static shared libs cannot declare services");
11296                }
11297
11298                // Static shared libs cannot declare providers
11299                if (!pkg.providers.isEmpty()) {
11300                    throw new PackageManagerException(
11301                            "Static shared libs cannot declare content providers");
11302                }
11303
11304                // Static shared libs cannot declare receivers
11305                if (!pkg.receivers.isEmpty()) {
11306                    throw new PackageManagerException(
11307                            "Static shared libs cannot declare broadcast receivers");
11308                }
11309
11310                // Static shared libs cannot declare permission groups
11311                if (!pkg.permissionGroups.isEmpty()) {
11312                    throw new PackageManagerException(
11313                            "Static shared libs cannot declare permission groups");
11314                }
11315
11316                // Static shared libs cannot declare permissions
11317                if (!pkg.permissions.isEmpty()) {
11318                    throw new PackageManagerException(
11319                            "Static shared libs cannot declare permissions");
11320                }
11321
11322                // Static shared libs cannot declare protected broadcasts
11323                if (pkg.protectedBroadcasts != null) {
11324                    throw new PackageManagerException(
11325                            "Static shared libs cannot declare protected broadcasts");
11326                }
11327
11328                // Static shared libs cannot be overlay targets
11329                if (pkg.mOverlayTarget != null) {
11330                    throw new PackageManagerException(
11331                            "Static shared libs cannot be overlay targets");
11332                }
11333
11334                // The version codes must be ordered as lib versions
11335                int minVersionCode = Integer.MIN_VALUE;
11336                int maxVersionCode = Integer.MAX_VALUE;
11337
11338                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11339                        pkg.staticSharedLibName);
11340                if (versionedLib != null) {
11341                    final int versionCount = versionedLib.size();
11342                    for (int i = 0; i < versionCount; i++) {
11343                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11344                        final int libVersionCode = libInfo.getDeclaringPackage()
11345                                .getVersionCode();
11346                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11347                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11348                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11349                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11350                        } else {
11351                            minVersionCode = maxVersionCode = libVersionCode;
11352                            break;
11353                        }
11354                    }
11355                }
11356                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11357                    throw new PackageManagerException("Static shared"
11358                            + " lib version codes must be ordered as lib versions");
11359                }
11360            }
11361
11362            // Only privileged apps and updated privileged apps can add child packages.
11363            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11364                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11365                    throw new PackageManagerException("Only privileged apps can add child "
11366                            + "packages. Ignoring package " + pkg.packageName);
11367                }
11368                final int childCount = pkg.childPackages.size();
11369                for (int i = 0; i < childCount; i++) {
11370                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11371                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11372                            childPkg.packageName)) {
11373                        throw new PackageManagerException("Can't override child of "
11374                                + "another disabled app. Ignoring package " + pkg.packageName);
11375                    }
11376                }
11377            }
11378
11379            // If we're only installing presumed-existing packages, require that the
11380            // scanned APK is both already known and at the path previously established
11381            // for it.  Previously unknown packages we pick up normally, but if we have an
11382            // a priori expectation about this package's install presence, enforce it.
11383            // With a singular exception for new system packages. When an OTA contains
11384            // a new system package, we allow the codepath to change from a system location
11385            // to the user-installed location. If we don't allow this change, any newer,
11386            // user-installed version of the application will be ignored.
11387            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11388                if (mExpectingBetter.containsKey(pkg.packageName)) {
11389                    logCriticalInfo(Log.WARN,
11390                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11391                } else {
11392                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11393                    if (known != null) {
11394                        if (DEBUG_PACKAGE_SCANNING) {
11395                            Log.d(TAG, "Examining " + pkg.codePath
11396                                    + " and requiring known paths " + known.codePathString
11397                                    + " & " + known.resourcePathString);
11398                        }
11399                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11400                                || !pkg.applicationInfo.getResourcePath().equals(
11401                                        known.resourcePathString)) {
11402                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11403                                    "Application package " + pkg.packageName
11404                                    + " found at " + pkg.applicationInfo.getCodePath()
11405                                    + " but expected at " + known.codePathString
11406                                    + "; ignoring.");
11407                        }
11408                    } else {
11409                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11410                                "Application package " + pkg.packageName
11411                                + " not found; ignoring.");
11412                    }
11413                }
11414            }
11415
11416            // Verify that this new package doesn't have any content providers
11417            // that conflict with existing packages.  Only do this if the
11418            // package isn't already installed, since we don't want to break
11419            // things that are installed.
11420            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11421                final int N = pkg.providers.size();
11422                int i;
11423                for (i=0; i<N; i++) {
11424                    PackageParser.Provider p = pkg.providers.get(i);
11425                    if (p.info.authority != null) {
11426                        String names[] = p.info.authority.split(";");
11427                        for (int j = 0; j < names.length; j++) {
11428                            if (mProvidersByAuthority.containsKey(names[j])) {
11429                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11430                                final String otherPackageName =
11431                                        ((other != null && other.getComponentName() != null) ?
11432                                                other.getComponentName().getPackageName() : "?");
11433                                throw new PackageManagerException(
11434                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11435                                        "Can't install because provider name " + names[j]
11436                                                + " (in package " + pkg.applicationInfo.packageName
11437                                                + ") is already used by " + otherPackageName);
11438                            }
11439                        }
11440                    }
11441                }
11442            }
11443        }
11444    }
11445
11446    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11447            int type, String declaringPackageName, int declaringVersionCode) {
11448        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11449        if (versionedLib == null) {
11450            versionedLib = new SparseArray<>();
11451            mSharedLibraries.put(name, versionedLib);
11452            if (type == SharedLibraryInfo.TYPE_STATIC) {
11453                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11454            }
11455        } else if (versionedLib.indexOfKey(version) >= 0) {
11456            return false;
11457        }
11458        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11459                version, type, declaringPackageName, declaringVersionCode);
11460        versionedLib.put(version, libEntry);
11461        return true;
11462    }
11463
11464    private boolean removeSharedLibraryLPw(String name, int version) {
11465        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11466        if (versionedLib == null) {
11467            return false;
11468        }
11469        final int libIdx = versionedLib.indexOfKey(version);
11470        if (libIdx < 0) {
11471            return false;
11472        }
11473        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11474        versionedLib.remove(version);
11475        if (versionedLib.size() <= 0) {
11476            mSharedLibraries.remove(name);
11477            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11478                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11479                        .getPackageName());
11480            }
11481        }
11482        return true;
11483    }
11484
11485    /**
11486     * Adds a scanned package to the system. When this method is finished, the package will
11487     * be available for query, resolution, etc...
11488     */
11489    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11490            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11491        final String pkgName = pkg.packageName;
11492        if (mCustomResolverComponentName != null &&
11493                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11494            setUpCustomResolverActivity(pkg);
11495        }
11496
11497        if (pkg.packageName.equals("android")) {
11498            synchronized (mPackages) {
11499                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11500                    // Set up information for our fall-back user intent resolution activity.
11501                    mPlatformPackage = pkg;
11502                    pkg.mVersionCode = mSdkVersion;
11503                    mAndroidApplication = pkg.applicationInfo;
11504                    if (!mResolverReplaced) {
11505                        mResolveActivity.applicationInfo = mAndroidApplication;
11506                        mResolveActivity.name = ResolverActivity.class.getName();
11507                        mResolveActivity.packageName = mAndroidApplication.packageName;
11508                        mResolveActivity.processName = "system:ui";
11509                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11510                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11511                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11512                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11513                        mResolveActivity.exported = true;
11514                        mResolveActivity.enabled = true;
11515                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11516                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11517                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11518                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11519                                | ActivityInfo.CONFIG_ORIENTATION
11520                                | ActivityInfo.CONFIG_KEYBOARD
11521                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11522                        mResolveInfo.activityInfo = mResolveActivity;
11523                        mResolveInfo.priority = 0;
11524                        mResolveInfo.preferredOrder = 0;
11525                        mResolveInfo.match = 0;
11526                        mResolveComponentName = new ComponentName(
11527                                mAndroidApplication.packageName, mResolveActivity.name);
11528                    }
11529                }
11530            }
11531        }
11532
11533        ArrayList<PackageParser.Package> clientLibPkgs = null;
11534        // writer
11535        synchronized (mPackages) {
11536            boolean hasStaticSharedLibs = false;
11537
11538            // Any app can add new static shared libraries
11539            if (pkg.staticSharedLibName != null) {
11540                // Static shared libs don't allow renaming as they have synthetic package
11541                // names to allow install of multiple versions, so use name from manifest.
11542                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11543                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11544                        pkg.manifestPackageName, pkg.mVersionCode)) {
11545                    hasStaticSharedLibs = true;
11546                } else {
11547                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11548                                + pkg.staticSharedLibName + " already exists; skipping");
11549                }
11550                // Static shared libs cannot be updated once installed since they
11551                // use synthetic package name which includes the version code, so
11552                // not need to update other packages's shared lib dependencies.
11553            }
11554
11555            if (!hasStaticSharedLibs
11556                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11557                // Only system apps can add new dynamic shared libraries.
11558                if (pkg.libraryNames != null) {
11559                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11560                        String name = pkg.libraryNames.get(i);
11561                        boolean allowed = false;
11562                        if (pkg.isUpdatedSystemApp()) {
11563                            // New library entries can only be added through the
11564                            // system image.  This is important to get rid of a lot
11565                            // of nasty edge cases: for example if we allowed a non-
11566                            // system update of the app to add a library, then uninstalling
11567                            // the update would make the library go away, and assumptions
11568                            // we made such as through app install filtering would now
11569                            // have allowed apps on the device which aren't compatible
11570                            // with it.  Better to just have the restriction here, be
11571                            // conservative, and create many fewer cases that can negatively
11572                            // impact the user experience.
11573                            final PackageSetting sysPs = mSettings
11574                                    .getDisabledSystemPkgLPr(pkg.packageName);
11575                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11576                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11577                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11578                                        allowed = true;
11579                                        break;
11580                                    }
11581                                }
11582                            }
11583                        } else {
11584                            allowed = true;
11585                        }
11586                        if (allowed) {
11587                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11588                                    SharedLibraryInfo.VERSION_UNDEFINED,
11589                                    SharedLibraryInfo.TYPE_DYNAMIC,
11590                                    pkg.packageName, pkg.mVersionCode)) {
11591                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11592                                        + name + " already exists; skipping");
11593                            }
11594                        } else {
11595                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11596                                    + name + " that is not declared on system image; skipping");
11597                        }
11598                    }
11599
11600                    if ((scanFlags & SCAN_BOOTING) == 0) {
11601                        // If we are not booting, we need to update any applications
11602                        // that are clients of our shared library.  If we are booting,
11603                        // this will all be done once the scan is complete.
11604                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11605                    }
11606                }
11607            }
11608        }
11609
11610        if ((scanFlags & SCAN_BOOTING) != 0) {
11611            // No apps can run during boot scan, so they don't need to be frozen
11612        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11613            // Caller asked to not kill app, so it's probably not frozen
11614        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11615            // Caller asked us to ignore frozen check for some reason; they
11616            // probably didn't know the package name
11617        } else {
11618            // We're doing major surgery on this package, so it better be frozen
11619            // right now to keep it from launching
11620            checkPackageFrozen(pkgName);
11621        }
11622
11623        // Also need to kill any apps that are dependent on the library.
11624        if (clientLibPkgs != null) {
11625            for (int i=0; i<clientLibPkgs.size(); i++) {
11626                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11627                killApplication(clientPkg.applicationInfo.packageName,
11628                        clientPkg.applicationInfo.uid, "update lib");
11629            }
11630        }
11631
11632        // writer
11633        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11634
11635        synchronized (mPackages) {
11636            // We don't expect installation to fail beyond this point
11637
11638            // Add the new setting to mSettings
11639            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11640            // Add the new setting to mPackages
11641            mPackages.put(pkg.applicationInfo.packageName, pkg);
11642            // Make sure we don't accidentally delete its data.
11643            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11644            while (iter.hasNext()) {
11645                PackageCleanItem item = iter.next();
11646                if (pkgName.equals(item.packageName)) {
11647                    iter.remove();
11648                }
11649            }
11650
11651            // Add the package's KeySets to the global KeySetManagerService
11652            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11653            ksms.addScannedPackageLPw(pkg);
11654
11655            int N = pkg.providers.size();
11656            StringBuilder r = null;
11657            int i;
11658            for (i=0; i<N; i++) {
11659                PackageParser.Provider p = pkg.providers.get(i);
11660                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11661                        p.info.processName);
11662                mProviders.addProvider(p);
11663                p.syncable = p.info.isSyncable;
11664                if (p.info.authority != null) {
11665                    String names[] = p.info.authority.split(";");
11666                    p.info.authority = null;
11667                    for (int j = 0; j < names.length; j++) {
11668                        if (j == 1 && p.syncable) {
11669                            // We only want the first authority for a provider to possibly be
11670                            // syncable, so if we already added this provider using a different
11671                            // authority clear the syncable flag. We copy the provider before
11672                            // changing it because the mProviders object contains a reference
11673                            // to a provider that we don't want to change.
11674                            // Only do this for the second authority since the resulting provider
11675                            // object can be the same for all future authorities for this provider.
11676                            p = new PackageParser.Provider(p);
11677                            p.syncable = false;
11678                        }
11679                        if (!mProvidersByAuthority.containsKey(names[j])) {
11680                            mProvidersByAuthority.put(names[j], p);
11681                            if (p.info.authority == null) {
11682                                p.info.authority = names[j];
11683                            } else {
11684                                p.info.authority = p.info.authority + ";" + names[j];
11685                            }
11686                            if (DEBUG_PACKAGE_SCANNING) {
11687                                if (chatty)
11688                                    Log.d(TAG, "Registered content provider: " + names[j]
11689                                            + ", className = " + p.info.name + ", isSyncable = "
11690                                            + p.info.isSyncable);
11691                            }
11692                        } else {
11693                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11694                            Slog.w(TAG, "Skipping provider name " + names[j] +
11695                                    " (in package " + pkg.applicationInfo.packageName +
11696                                    "): name already used by "
11697                                    + ((other != null && other.getComponentName() != null)
11698                                            ? other.getComponentName().getPackageName() : "?"));
11699                        }
11700                    }
11701                }
11702                if (chatty) {
11703                    if (r == null) {
11704                        r = new StringBuilder(256);
11705                    } else {
11706                        r.append(' ');
11707                    }
11708                    r.append(p.info.name);
11709                }
11710            }
11711            if (r != null) {
11712                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11713            }
11714
11715            N = pkg.services.size();
11716            r = null;
11717            for (i=0; i<N; i++) {
11718                PackageParser.Service s = pkg.services.get(i);
11719                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11720                        s.info.processName);
11721                mServices.addService(s);
11722                if (chatty) {
11723                    if (r == null) {
11724                        r = new StringBuilder(256);
11725                    } else {
11726                        r.append(' ');
11727                    }
11728                    r.append(s.info.name);
11729                }
11730            }
11731            if (r != null) {
11732                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11733            }
11734
11735            N = pkg.receivers.size();
11736            r = null;
11737            for (i=0; i<N; i++) {
11738                PackageParser.Activity a = pkg.receivers.get(i);
11739                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11740                        a.info.processName);
11741                mReceivers.addActivity(a, "receiver");
11742                if (chatty) {
11743                    if (r == null) {
11744                        r = new StringBuilder(256);
11745                    } else {
11746                        r.append(' ');
11747                    }
11748                    r.append(a.info.name);
11749                }
11750            }
11751            if (r != null) {
11752                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11753            }
11754
11755            N = pkg.activities.size();
11756            r = null;
11757            for (i=0; i<N; i++) {
11758                PackageParser.Activity a = pkg.activities.get(i);
11759                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11760                        a.info.processName);
11761                mActivities.addActivity(a, "activity");
11762                if (chatty) {
11763                    if (r == null) {
11764                        r = new StringBuilder(256);
11765                    } else {
11766                        r.append(' ');
11767                    }
11768                    r.append(a.info.name);
11769                }
11770            }
11771            if (r != null) {
11772                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11773            }
11774
11775            N = pkg.permissionGroups.size();
11776            r = null;
11777            for (i=0; i<N; i++) {
11778                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11779                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11780                final String curPackageName = cur == null ? null : cur.info.packageName;
11781                // Dont allow ephemeral apps to define new permission groups.
11782                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11783                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11784                            + pg.info.packageName
11785                            + " ignored: instant apps cannot define new permission groups.");
11786                    continue;
11787                }
11788                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11789                if (cur == null || isPackageUpdate) {
11790                    mPermissionGroups.put(pg.info.name, pg);
11791                    if (chatty) {
11792                        if (r == null) {
11793                            r = new StringBuilder(256);
11794                        } else {
11795                            r.append(' ');
11796                        }
11797                        if (isPackageUpdate) {
11798                            r.append("UPD:");
11799                        }
11800                        r.append(pg.info.name);
11801                    }
11802                } else {
11803                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11804                            + pg.info.packageName + " ignored: original from "
11805                            + cur.info.packageName);
11806                    if (chatty) {
11807                        if (r == null) {
11808                            r = new StringBuilder(256);
11809                        } else {
11810                            r.append(' ');
11811                        }
11812                        r.append("DUP:");
11813                        r.append(pg.info.name);
11814                    }
11815                }
11816            }
11817            if (r != null) {
11818                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11819            }
11820
11821            N = pkg.permissions.size();
11822            r = null;
11823            for (i=0; i<N; i++) {
11824                PackageParser.Permission p = pkg.permissions.get(i);
11825
11826                // Dont allow ephemeral apps to define new permissions.
11827                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11828                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11829                            + p.info.packageName
11830                            + " ignored: instant apps cannot define new permissions.");
11831                    continue;
11832                }
11833
11834                // Assume by default that we did not install this permission into the system.
11835                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11836
11837                // Now that permission groups have a special meaning, we ignore permission
11838                // groups for legacy apps to prevent unexpected behavior. In particular,
11839                // permissions for one app being granted to someone just because they happen
11840                // to be in a group defined by another app (before this had no implications).
11841                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11842                    p.group = mPermissionGroups.get(p.info.group);
11843                    // Warn for a permission in an unknown group.
11844                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11845                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11846                                + p.info.packageName + " in an unknown group " + p.info.group);
11847                    }
11848                }
11849
11850                ArrayMap<String, BasePermission> permissionMap =
11851                        p.tree ? mSettings.mPermissionTrees
11852                                : mSettings.mPermissions;
11853                BasePermission bp = permissionMap.get(p.info.name);
11854
11855                // Allow system apps to redefine non-system permissions
11856                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11857                    final boolean currentOwnerIsSystem = (bp.perm != null
11858                            && isSystemApp(bp.perm.owner));
11859                    if (isSystemApp(p.owner)) {
11860                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11861                            // It's a built-in permission and no owner, take ownership now
11862                            bp.packageSetting = pkgSetting;
11863                            bp.perm = p;
11864                            bp.uid = pkg.applicationInfo.uid;
11865                            bp.sourcePackage = p.info.packageName;
11866                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11867                        } else if (!currentOwnerIsSystem) {
11868                            String msg = "New decl " + p.owner + " of permission  "
11869                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11870                            reportSettingsProblem(Log.WARN, msg);
11871                            bp = null;
11872                        }
11873                    }
11874                }
11875
11876                if (bp == null) {
11877                    bp = new BasePermission(p.info.name, p.info.packageName,
11878                            BasePermission.TYPE_NORMAL);
11879                    permissionMap.put(p.info.name, bp);
11880                }
11881
11882                if (bp.perm == null) {
11883                    if (bp.sourcePackage == null
11884                            || bp.sourcePackage.equals(p.info.packageName)) {
11885                        BasePermission tree = findPermissionTreeLP(p.info.name);
11886                        if (tree == null
11887                                || tree.sourcePackage.equals(p.info.packageName)) {
11888                            bp.packageSetting = pkgSetting;
11889                            bp.perm = p;
11890                            bp.uid = pkg.applicationInfo.uid;
11891                            bp.sourcePackage = p.info.packageName;
11892                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11893                            if (chatty) {
11894                                if (r == null) {
11895                                    r = new StringBuilder(256);
11896                                } else {
11897                                    r.append(' ');
11898                                }
11899                                r.append(p.info.name);
11900                            }
11901                        } else {
11902                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11903                                    + p.info.packageName + " ignored: base tree "
11904                                    + tree.name + " is from package "
11905                                    + tree.sourcePackage);
11906                        }
11907                    } else {
11908                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11909                                + p.info.packageName + " ignored: original from "
11910                                + bp.sourcePackage);
11911                    }
11912                } else if (chatty) {
11913                    if (r == null) {
11914                        r = new StringBuilder(256);
11915                    } else {
11916                        r.append(' ');
11917                    }
11918                    r.append("DUP:");
11919                    r.append(p.info.name);
11920                }
11921                if (bp.perm == p) {
11922                    bp.protectionLevel = p.info.protectionLevel;
11923                }
11924            }
11925
11926            if (r != null) {
11927                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11928            }
11929
11930            N = pkg.instrumentation.size();
11931            r = null;
11932            for (i=0; i<N; i++) {
11933                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11934                a.info.packageName = pkg.applicationInfo.packageName;
11935                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11936                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11937                a.info.splitNames = pkg.splitNames;
11938                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11939                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11940                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11941                a.info.dataDir = pkg.applicationInfo.dataDir;
11942                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11943                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11944                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11945                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11946                mInstrumentation.put(a.getComponentName(), a);
11947                if (chatty) {
11948                    if (r == null) {
11949                        r = new StringBuilder(256);
11950                    } else {
11951                        r.append(' ');
11952                    }
11953                    r.append(a.info.name);
11954                }
11955            }
11956            if (r != null) {
11957                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11958            }
11959
11960            if (pkg.protectedBroadcasts != null) {
11961                N = pkg.protectedBroadcasts.size();
11962                synchronized (mProtectedBroadcasts) {
11963                    for (i = 0; i < N; i++) {
11964                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11965                    }
11966                }
11967            }
11968        }
11969
11970        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11971    }
11972
11973    /**
11974     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11975     * is derived purely on the basis of the contents of {@code scanFile} and
11976     * {@code cpuAbiOverride}.
11977     *
11978     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11979     */
11980    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11981                                 String cpuAbiOverride, boolean extractLibs,
11982                                 File appLib32InstallDir)
11983            throws PackageManagerException {
11984        // Give ourselves some initial paths; we'll come back for another
11985        // pass once we've determined ABI below.
11986        setNativeLibraryPaths(pkg, appLib32InstallDir);
11987
11988        // We would never need to extract libs for forward-locked and external packages,
11989        // since the container service will do it for us. We shouldn't attempt to
11990        // extract libs from system app when it was not updated.
11991        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11992                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11993            extractLibs = false;
11994        }
11995
11996        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11997        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11998
11999        NativeLibraryHelper.Handle handle = null;
12000        try {
12001            handle = NativeLibraryHelper.Handle.create(pkg);
12002            // TODO(multiArch): This can be null for apps that didn't go through the
12003            // usual installation process. We can calculate it again, like we
12004            // do during install time.
12005            //
12006            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12007            // unnecessary.
12008            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12009
12010            // Null out the abis so that they can be recalculated.
12011            pkg.applicationInfo.primaryCpuAbi = null;
12012            pkg.applicationInfo.secondaryCpuAbi = null;
12013            if (isMultiArch(pkg.applicationInfo)) {
12014                // Warn if we've set an abiOverride for multi-lib packages..
12015                // By definition, we need to copy both 32 and 64 bit libraries for
12016                // such packages.
12017                if (pkg.cpuAbiOverride != null
12018                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12019                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12020                }
12021
12022                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12023                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12024                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12025                    if (extractLibs) {
12026                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12027                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12028                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12029                                useIsaSpecificSubdirs);
12030                    } else {
12031                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12032                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12033                    }
12034                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12035                }
12036
12037                // Shared library native code should be in the APK zip aligned
12038                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12039                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12040                            "Shared library native lib extraction not supported");
12041                }
12042
12043                maybeThrowExceptionForMultiArchCopy(
12044                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12045
12046                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12047                    if (extractLibs) {
12048                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12049                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12050                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12051                                useIsaSpecificSubdirs);
12052                    } else {
12053                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12054                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12055                    }
12056                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12057                }
12058
12059                maybeThrowExceptionForMultiArchCopy(
12060                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12061
12062                if (abi64 >= 0) {
12063                    // Shared library native libs should be in the APK zip aligned
12064                    if (extractLibs && pkg.isLibrary()) {
12065                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12066                                "Shared library native lib extraction not supported");
12067                    }
12068                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12069                }
12070
12071                if (abi32 >= 0) {
12072                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12073                    if (abi64 >= 0) {
12074                        if (pkg.use32bitAbi) {
12075                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12076                            pkg.applicationInfo.primaryCpuAbi = abi;
12077                        } else {
12078                            pkg.applicationInfo.secondaryCpuAbi = abi;
12079                        }
12080                    } else {
12081                        pkg.applicationInfo.primaryCpuAbi = abi;
12082                    }
12083                }
12084            } else {
12085                String[] abiList = (cpuAbiOverride != null) ?
12086                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12087
12088                // Enable gross and lame hacks for apps that are built with old
12089                // SDK tools. We must scan their APKs for renderscript bitcode and
12090                // not launch them if it's present. Don't bother checking on devices
12091                // that don't have 64 bit support.
12092                boolean needsRenderScriptOverride = false;
12093                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12094                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12095                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12096                    needsRenderScriptOverride = true;
12097                }
12098
12099                final int copyRet;
12100                if (extractLibs) {
12101                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12102                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12103                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12104                } else {
12105                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12106                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12107                }
12108                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12109
12110                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12111                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12112                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12113                }
12114
12115                if (copyRet >= 0) {
12116                    // Shared libraries that have native libs must be multi-architecture
12117                    if (pkg.isLibrary()) {
12118                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12119                                "Shared library with native libs must be multiarch");
12120                    }
12121                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12122                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12123                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12124                } else if (needsRenderScriptOverride) {
12125                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12126                }
12127            }
12128        } catch (IOException ioe) {
12129            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12130        } finally {
12131            IoUtils.closeQuietly(handle);
12132        }
12133
12134        // Now that we've calculated the ABIs and determined if it's an internal app,
12135        // we will go ahead and populate the nativeLibraryPath.
12136        setNativeLibraryPaths(pkg, appLib32InstallDir);
12137    }
12138
12139    /**
12140     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12141     * i.e, so that all packages can be run inside a single process if required.
12142     *
12143     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12144     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12145     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12146     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12147     * updating a package that belongs to a shared user.
12148     *
12149     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12150     * adds unnecessary complexity.
12151     */
12152    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12153            PackageParser.Package scannedPackage) {
12154        String requiredInstructionSet = null;
12155        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12156            requiredInstructionSet = VMRuntime.getInstructionSet(
12157                     scannedPackage.applicationInfo.primaryCpuAbi);
12158        }
12159
12160        PackageSetting requirer = null;
12161        for (PackageSetting ps : packagesForUser) {
12162            // If packagesForUser contains scannedPackage, we skip it. This will happen
12163            // when scannedPackage is an update of an existing package. Without this check,
12164            // we will never be able to change the ABI of any package belonging to a shared
12165            // user, even if it's compatible with other packages.
12166            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12167                if (ps.primaryCpuAbiString == null) {
12168                    continue;
12169                }
12170
12171                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12172                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12173                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12174                    // this but there's not much we can do.
12175                    String errorMessage = "Instruction set mismatch, "
12176                            + ((requirer == null) ? "[caller]" : requirer)
12177                            + " requires " + requiredInstructionSet + " whereas " + ps
12178                            + " requires " + instructionSet;
12179                    Slog.w(TAG, errorMessage);
12180                }
12181
12182                if (requiredInstructionSet == null) {
12183                    requiredInstructionSet = instructionSet;
12184                    requirer = ps;
12185                }
12186            }
12187        }
12188
12189        if (requiredInstructionSet != null) {
12190            String adjustedAbi;
12191            if (requirer != null) {
12192                // requirer != null implies that either scannedPackage was null or that scannedPackage
12193                // did not require an ABI, in which case we have to adjust scannedPackage to match
12194                // the ABI of the set (which is the same as requirer's ABI)
12195                adjustedAbi = requirer.primaryCpuAbiString;
12196                if (scannedPackage != null) {
12197                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12198                }
12199            } else {
12200                // requirer == null implies that we're updating all ABIs in the set to
12201                // match scannedPackage.
12202                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12203            }
12204
12205            for (PackageSetting ps : packagesForUser) {
12206                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12207                    if (ps.primaryCpuAbiString != null) {
12208                        continue;
12209                    }
12210
12211                    ps.primaryCpuAbiString = adjustedAbi;
12212                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12213                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12214                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12215                        if (DEBUG_ABI_SELECTION) {
12216                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12217                                    + " (requirer="
12218                                    + (requirer != null ? requirer.pkg : "null")
12219                                    + ", scannedPackage="
12220                                    + (scannedPackage != null ? scannedPackage : "null")
12221                                    + ")");
12222                        }
12223                        try {
12224                            mInstaller.rmdex(ps.codePathString,
12225                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12226                        } catch (InstallerException ignored) {
12227                        }
12228                    }
12229                }
12230            }
12231        }
12232    }
12233
12234    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12235        synchronized (mPackages) {
12236            mResolverReplaced = true;
12237            // Set up information for custom user intent resolution activity.
12238            mResolveActivity.applicationInfo = pkg.applicationInfo;
12239            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12240            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12241            mResolveActivity.processName = pkg.applicationInfo.packageName;
12242            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12243            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12244                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12245            mResolveActivity.theme = 0;
12246            mResolveActivity.exported = true;
12247            mResolveActivity.enabled = true;
12248            mResolveInfo.activityInfo = mResolveActivity;
12249            mResolveInfo.priority = 0;
12250            mResolveInfo.preferredOrder = 0;
12251            mResolveInfo.match = 0;
12252            mResolveComponentName = mCustomResolverComponentName;
12253            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12254                    mResolveComponentName);
12255        }
12256    }
12257
12258    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12259        if (installerActivity == null) {
12260            if (DEBUG_EPHEMERAL) {
12261                Slog.d(TAG, "Clear ephemeral installer activity");
12262            }
12263            mInstantAppInstallerActivity = null;
12264            return;
12265        }
12266
12267        if (DEBUG_EPHEMERAL) {
12268            Slog.d(TAG, "Set ephemeral installer activity: "
12269                    + installerActivity.getComponentName());
12270        }
12271        // Set up information for ephemeral installer activity
12272        mInstantAppInstallerActivity = installerActivity;
12273        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12274                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12275        mInstantAppInstallerActivity.exported = true;
12276        mInstantAppInstallerActivity.enabled = true;
12277        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12278        mInstantAppInstallerInfo.priority = 0;
12279        mInstantAppInstallerInfo.preferredOrder = 1;
12280        mInstantAppInstallerInfo.isDefault = true;
12281        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12282                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12283    }
12284
12285    private static String calculateBundledApkRoot(final String codePathString) {
12286        final File codePath = new File(codePathString);
12287        final File codeRoot;
12288        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12289            codeRoot = Environment.getRootDirectory();
12290        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12291            codeRoot = Environment.getOemDirectory();
12292        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12293            codeRoot = Environment.getVendorDirectory();
12294        } else {
12295            // Unrecognized code path; take its top real segment as the apk root:
12296            // e.g. /something/app/blah.apk => /something
12297            try {
12298                File f = codePath.getCanonicalFile();
12299                File parent = f.getParentFile();    // non-null because codePath is a file
12300                File tmp;
12301                while ((tmp = parent.getParentFile()) != null) {
12302                    f = parent;
12303                    parent = tmp;
12304                }
12305                codeRoot = f;
12306                Slog.w(TAG, "Unrecognized code path "
12307                        + codePath + " - using " + codeRoot);
12308            } catch (IOException e) {
12309                // Can't canonicalize the code path -- shenanigans?
12310                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12311                return Environment.getRootDirectory().getPath();
12312            }
12313        }
12314        return codeRoot.getPath();
12315    }
12316
12317    /**
12318     * Derive and set the location of native libraries for the given package,
12319     * which varies depending on where and how the package was installed.
12320     */
12321    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12322        final ApplicationInfo info = pkg.applicationInfo;
12323        final String codePath = pkg.codePath;
12324        final File codeFile = new File(codePath);
12325        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12326        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12327
12328        info.nativeLibraryRootDir = null;
12329        info.nativeLibraryRootRequiresIsa = false;
12330        info.nativeLibraryDir = null;
12331        info.secondaryNativeLibraryDir = null;
12332
12333        if (isApkFile(codeFile)) {
12334            // Monolithic install
12335            if (bundledApp) {
12336                // If "/system/lib64/apkname" exists, assume that is the per-package
12337                // native library directory to use; otherwise use "/system/lib/apkname".
12338                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12339                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12340                        getPrimaryInstructionSet(info));
12341
12342                // This is a bundled system app so choose the path based on the ABI.
12343                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12344                // is just the default path.
12345                final String apkName = deriveCodePathName(codePath);
12346                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12347                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12348                        apkName).getAbsolutePath();
12349
12350                if (info.secondaryCpuAbi != null) {
12351                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12352                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12353                            secondaryLibDir, apkName).getAbsolutePath();
12354                }
12355            } else if (asecApp) {
12356                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12357                        .getAbsolutePath();
12358            } else {
12359                final String apkName = deriveCodePathName(codePath);
12360                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12361                        .getAbsolutePath();
12362            }
12363
12364            info.nativeLibraryRootRequiresIsa = false;
12365            info.nativeLibraryDir = info.nativeLibraryRootDir;
12366        } else {
12367            // Cluster install
12368            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12369            info.nativeLibraryRootRequiresIsa = true;
12370
12371            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12372                    getPrimaryInstructionSet(info)).getAbsolutePath();
12373
12374            if (info.secondaryCpuAbi != null) {
12375                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12376                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12377            }
12378        }
12379    }
12380
12381    /**
12382     * Calculate the abis and roots for a bundled app. These can uniquely
12383     * be determined from the contents of the system partition, i.e whether
12384     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12385     * of this information, and instead assume that the system was built
12386     * sensibly.
12387     */
12388    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12389                                           PackageSetting pkgSetting) {
12390        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12391
12392        // If "/system/lib64/apkname" exists, assume that is the per-package
12393        // native library directory to use; otherwise use "/system/lib/apkname".
12394        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12395        setBundledAppAbi(pkg, apkRoot, apkName);
12396        // pkgSetting might be null during rescan following uninstall of updates
12397        // to a bundled app, so accommodate that possibility.  The settings in
12398        // that case will be established later from the parsed package.
12399        //
12400        // If the settings aren't null, sync them up with what we've just derived.
12401        // note that apkRoot isn't stored in the package settings.
12402        if (pkgSetting != null) {
12403            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12404            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12405        }
12406    }
12407
12408    /**
12409     * Deduces the ABI of a bundled app and sets the relevant fields on the
12410     * parsed pkg object.
12411     *
12412     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12413     *        under which system libraries are installed.
12414     * @param apkName the name of the installed package.
12415     */
12416    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12417        final File codeFile = new File(pkg.codePath);
12418
12419        final boolean has64BitLibs;
12420        final boolean has32BitLibs;
12421        if (isApkFile(codeFile)) {
12422            // Monolithic install
12423            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12424            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12425        } else {
12426            // Cluster install
12427            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12428            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12429                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12430                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12431                has64BitLibs = (new File(rootDir, isa)).exists();
12432            } else {
12433                has64BitLibs = false;
12434            }
12435            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12436                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12437                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12438                has32BitLibs = (new File(rootDir, isa)).exists();
12439            } else {
12440                has32BitLibs = false;
12441            }
12442        }
12443
12444        if (has64BitLibs && !has32BitLibs) {
12445            // The package has 64 bit libs, but not 32 bit libs. Its primary
12446            // ABI should be 64 bit. We can safely assume here that the bundled
12447            // native libraries correspond to the most preferred ABI in the list.
12448
12449            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12450            pkg.applicationInfo.secondaryCpuAbi = null;
12451        } else if (has32BitLibs && !has64BitLibs) {
12452            // The package has 32 bit libs but not 64 bit libs. Its primary
12453            // ABI should be 32 bit.
12454
12455            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12456            pkg.applicationInfo.secondaryCpuAbi = null;
12457        } else if (has32BitLibs && has64BitLibs) {
12458            // The application has both 64 and 32 bit bundled libraries. We check
12459            // here that the app declares multiArch support, and warn if it doesn't.
12460            //
12461            // We will be lenient here and record both ABIs. The primary will be the
12462            // ABI that's higher on the list, i.e, a device that's configured to prefer
12463            // 64 bit apps will see a 64 bit primary ABI,
12464
12465            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12466                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12467            }
12468
12469            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12470                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12471                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12472            } else {
12473                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12474                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12475            }
12476        } else {
12477            pkg.applicationInfo.primaryCpuAbi = null;
12478            pkg.applicationInfo.secondaryCpuAbi = null;
12479        }
12480    }
12481
12482    private void killApplication(String pkgName, int appId, String reason) {
12483        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12484    }
12485
12486    private void killApplication(String pkgName, int appId, int userId, String reason) {
12487        // Request the ActivityManager to kill the process(only for existing packages)
12488        // so that we do not end up in a confused state while the user is still using the older
12489        // version of the application while the new one gets installed.
12490        final long token = Binder.clearCallingIdentity();
12491        try {
12492            IActivityManager am = ActivityManager.getService();
12493            if (am != null) {
12494                try {
12495                    am.killApplication(pkgName, appId, userId, reason);
12496                } catch (RemoteException e) {
12497                }
12498            }
12499        } finally {
12500            Binder.restoreCallingIdentity(token);
12501        }
12502    }
12503
12504    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12505        // Remove the parent package setting
12506        PackageSetting ps = (PackageSetting) pkg.mExtras;
12507        if (ps != null) {
12508            removePackageLI(ps, chatty);
12509        }
12510        // Remove the child package setting
12511        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12512        for (int i = 0; i < childCount; i++) {
12513            PackageParser.Package childPkg = pkg.childPackages.get(i);
12514            ps = (PackageSetting) childPkg.mExtras;
12515            if (ps != null) {
12516                removePackageLI(ps, chatty);
12517            }
12518        }
12519    }
12520
12521    void removePackageLI(PackageSetting ps, boolean chatty) {
12522        if (DEBUG_INSTALL) {
12523            if (chatty)
12524                Log.d(TAG, "Removing package " + ps.name);
12525        }
12526
12527        // writer
12528        synchronized (mPackages) {
12529            mPackages.remove(ps.name);
12530            final PackageParser.Package pkg = ps.pkg;
12531            if (pkg != null) {
12532                cleanPackageDataStructuresLILPw(pkg, chatty);
12533            }
12534        }
12535    }
12536
12537    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12538        if (DEBUG_INSTALL) {
12539            if (chatty)
12540                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12541        }
12542
12543        // writer
12544        synchronized (mPackages) {
12545            // Remove the parent package
12546            mPackages.remove(pkg.applicationInfo.packageName);
12547            cleanPackageDataStructuresLILPw(pkg, chatty);
12548
12549            // Remove the child packages
12550            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12551            for (int i = 0; i < childCount; i++) {
12552                PackageParser.Package childPkg = pkg.childPackages.get(i);
12553                mPackages.remove(childPkg.applicationInfo.packageName);
12554                cleanPackageDataStructuresLILPw(childPkg, chatty);
12555            }
12556        }
12557    }
12558
12559    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12560        int N = pkg.providers.size();
12561        StringBuilder r = null;
12562        int i;
12563        for (i=0; i<N; i++) {
12564            PackageParser.Provider p = pkg.providers.get(i);
12565            mProviders.removeProvider(p);
12566            if (p.info.authority == null) {
12567
12568                /* There was another ContentProvider with this authority when
12569                 * this app was installed so this authority is null,
12570                 * Ignore it as we don't have to unregister the provider.
12571                 */
12572                continue;
12573            }
12574            String names[] = p.info.authority.split(";");
12575            for (int j = 0; j < names.length; j++) {
12576                if (mProvidersByAuthority.get(names[j]) == p) {
12577                    mProvidersByAuthority.remove(names[j]);
12578                    if (DEBUG_REMOVE) {
12579                        if (chatty)
12580                            Log.d(TAG, "Unregistered content provider: " + names[j]
12581                                    + ", className = " + p.info.name + ", isSyncable = "
12582                                    + p.info.isSyncable);
12583                    }
12584                }
12585            }
12586            if (DEBUG_REMOVE && chatty) {
12587                if (r == null) {
12588                    r = new StringBuilder(256);
12589                } else {
12590                    r.append(' ');
12591                }
12592                r.append(p.info.name);
12593            }
12594        }
12595        if (r != null) {
12596            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12597        }
12598
12599        N = pkg.services.size();
12600        r = null;
12601        for (i=0; i<N; i++) {
12602            PackageParser.Service s = pkg.services.get(i);
12603            mServices.removeService(s);
12604            if (chatty) {
12605                if (r == null) {
12606                    r = new StringBuilder(256);
12607                } else {
12608                    r.append(' ');
12609                }
12610                r.append(s.info.name);
12611            }
12612        }
12613        if (r != null) {
12614            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12615        }
12616
12617        N = pkg.receivers.size();
12618        r = null;
12619        for (i=0; i<N; i++) {
12620            PackageParser.Activity a = pkg.receivers.get(i);
12621            mReceivers.removeActivity(a, "receiver");
12622            if (DEBUG_REMOVE && chatty) {
12623                if (r == null) {
12624                    r = new StringBuilder(256);
12625                } else {
12626                    r.append(' ');
12627                }
12628                r.append(a.info.name);
12629            }
12630        }
12631        if (r != null) {
12632            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12633        }
12634
12635        N = pkg.activities.size();
12636        r = null;
12637        for (i=0; i<N; i++) {
12638            PackageParser.Activity a = pkg.activities.get(i);
12639            mActivities.removeActivity(a, "activity");
12640            if (DEBUG_REMOVE && chatty) {
12641                if (r == null) {
12642                    r = new StringBuilder(256);
12643                } else {
12644                    r.append(' ');
12645                }
12646                r.append(a.info.name);
12647            }
12648        }
12649        if (r != null) {
12650            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12651        }
12652
12653        N = pkg.permissions.size();
12654        r = null;
12655        for (i=0; i<N; i++) {
12656            PackageParser.Permission p = pkg.permissions.get(i);
12657            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12658            if (bp == null) {
12659                bp = mSettings.mPermissionTrees.get(p.info.name);
12660            }
12661            if (bp != null && bp.perm == p) {
12662                bp.perm = null;
12663                if (DEBUG_REMOVE && chatty) {
12664                    if (r == null) {
12665                        r = new StringBuilder(256);
12666                    } else {
12667                        r.append(' ');
12668                    }
12669                    r.append(p.info.name);
12670                }
12671            }
12672            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12673                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12674                if (appOpPkgs != null) {
12675                    appOpPkgs.remove(pkg.packageName);
12676                }
12677            }
12678        }
12679        if (r != null) {
12680            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12681        }
12682
12683        N = pkg.requestedPermissions.size();
12684        r = null;
12685        for (i=0; i<N; i++) {
12686            String perm = pkg.requestedPermissions.get(i);
12687            BasePermission bp = mSettings.mPermissions.get(perm);
12688            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12689                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12690                if (appOpPkgs != null) {
12691                    appOpPkgs.remove(pkg.packageName);
12692                    if (appOpPkgs.isEmpty()) {
12693                        mAppOpPermissionPackages.remove(perm);
12694                    }
12695                }
12696            }
12697        }
12698        if (r != null) {
12699            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12700        }
12701
12702        N = pkg.instrumentation.size();
12703        r = null;
12704        for (i=0; i<N; i++) {
12705            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12706            mInstrumentation.remove(a.getComponentName());
12707            if (DEBUG_REMOVE && chatty) {
12708                if (r == null) {
12709                    r = new StringBuilder(256);
12710                } else {
12711                    r.append(' ');
12712                }
12713                r.append(a.info.name);
12714            }
12715        }
12716        if (r != null) {
12717            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12718        }
12719
12720        r = null;
12721        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12722            // Only system apps can hold shared libraries.
12723            if (pkg.libraryNames != null) {
12724                for (i = 0; i < pkg.libraryNames.size(); i++) {
12725                    String name = pkg.libraryNames.get(i);
12726                    if (removeSharedLibraryLPw(name, 0)) {
12727                        if (DEBUG_REMOVE && chatty) {
12728                            if (r == null) {
12729                                r = new StringBuilder(256);
12730                            } else {
12731                                r.append(' ');
12732                            }
12733                            r.append(name);
12734                        }
12735                    }
12736                }
12737            }
12738        }
12739
12740        r = null;
12741
12742        // Any package can hold static shared libraries.
12743        if (pkg.staticSharedLibName != null) {
12744            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12745                if (DEBUG_REMOVE && chatty) {
12746                    if (r == null) {
12747                        r = new StringBuilder(256);
12748                    } else {
12749                        r.append(' ');
12750                    }
12751                    r.append(pkg.staticSharedLibName);
12752                }
12753            }
12754        }
12755
12756        if (r != null) {
12757            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12758        }
12759    }
12760
12761    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12762        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12763            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12764                return true;
12765            }
12766        }
12767        return false;
12768    }
12769
12770    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12771    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12772    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12773
12774    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12775        // Update the parent permissions
12776        updatePermissionsLPw(pkg.packageName, pkg, flags);
12777        // Update the child permissions
12778        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12779        for (int i = 0; i < childCount; i++) {
12780            PackageParser.Package childPkg = pkg.childPackages.get(i);
12781            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12782        }
12783    }
12784
12785    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12786            int flags) {
12787        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12788        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12789    }
12790
12791    private void updatePermissionsLPw(String changingPkg,
12792            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12793        // Make sure there are no dangling permission trees.
12794        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12795        while (it.hasNext()) {
12796            final BasePermission bp = it.next();
12797            if (bp.packageSetting == null) {
12798                // We may not yet have parsed the package, so just see if
12799                // we still know about its settings.
12800                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12801            }
12802            if (bp.packageSetting == null) {
12803                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12804                        + " from package " + bp.sourcePackage);
12805                it.remove();
12806            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12807                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12808                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12809                            + " from package " + bp.sourcePackage);
12810                    flags |= UPDATE_PERMISSIONS_ALL;
12811                    it.remove();
12812                }
12813            }
12814        }
12815
12816        // Make sure all dynamic permissions have been assigned to a package,
12817        // and make sure there are no dangling permissions.
12818        it = mSettings.mPermissions.values().iterator();
12819        while (it.hasNext()) {
12820            final BasePermission bp = it.next();
12821            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12822                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12823                        + bp.name + " pkg=" + bp.sourcePackage
12824                        + " info=" + bp.pendingInfo);
12825                if (bp.packageSetting == null && bp.pendingInfo != null) {
12826                    final BasePermission tree = findPermissionTreeLP(bp.name);
12827                    if (tree != null && tree.perm != null) {
12828                        bp.packageSetting = tree.packageSetting;
12829                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12830                                new PermissionInfo(bp.pendingInfo));
12831                        bp.perm.info.packageName = tree.perm.info.packageName;
12832                        bp.perm.info.name = bp.name;
12833                        bp.uid = tree.uid;
12834                    }
12835                }
12836            }
12837            if (bp.packageSetting == null) {
12838                // We may not yet have parsed the package, so just see if
12839                // we still know about its settings.
12840                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12841            }
12842            if (bp.packageSetting == null) {
12843                Slog.w(TAG, "Removing dangling permission: " + bp.name
12844                        + " from package " + bp.sourcePackage);
12845                it.remove();
12846            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12847                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12848                    Slog.i(TAG, "Removing old permission: " + bp.name
12849                            + " from package " + bp.sourcePackage);
12850                    flags |= UPDATE_PERMISSIONS_ALL;
12851                    it.remove();
12852                }
12853            }
12854        }
12855
12856        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12857        // Now update the permissions for all packages, in particular
12858        // replace the granted permissions of the system packages.
12859        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12860            for (PackageParser.Package pkg : mPackages.values()) {
12861                if (pkg != pkgInfo) {
12862                    // Only replace for packages on requested volume
12863                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12864                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12865                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12866                    grantPermissionsLPw(pkg, replace, changingPkg);
12867                }
12868            }
12869        }
12870
12871        if (pkgInfo != null) {
12872            // Only replace for packages on requested volume
12873            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12874            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12875                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12876            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12877        }
12878        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12879    }
12880
12881    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12882            String packageOfInterest) {
12883        // IMPORTANT: There are two types of permissions: install and runtime.
12884        // Install time permissions are granted when the app is installed to
12885        // all device users and users added in the future. Runtime permissions
12886        // are granted at runtime explicitly to specific users. Normal and signature
12887        // protected permissions are install time permissions. Dangerous permissions
12888        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12889        // otherwise they are runtime permissions. This function does not manage
12890        // runtime permissions except for the case an app targeting Lollipop MR1
12891        // being upgraded to target a newer SDK, in which case dangerous permissions
12892        // are transformed from install time to runtime ones.
12893
12894        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12895        if (ps == null) {
12896            return;
12897        }
12898
12899        PermissionsState permissionsState = ps.getPermissionsState();
12900        PermissionsState origPermissions = permissionsState;
12901
12902        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12903
12904        boolean runtimePermissionsRevoked = false;
12905        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12906
12907        boolean changedInstallPermission = false;
12908
12909        if (replace) {
12910            ps.installPermissionsFixed = false;
12911            if (!ps.isSharedUser()) {
12912                origPermissions = new PermissionsState(permissionsState);
12913                permissionsState.reset();
12914            } else {
12915                // We need to know only about runtime permission changes since the
12916                // calling code always writes the install permissions state but
12917                // the runtime ones are written only if changed. The only cases of
12918                // changed runtime permissions here are promotion of an install to
12919                // runtime and revocation of a runtime from a shared user.
12920                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12921                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12922                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12923                    runtimePermissionsRevoked = true;
12924                }
12925            }
12926        }
12927
12928        permissionsState.setGlobalGids(mGlobalGids);
12929
12930        final int N = pkg.requestedPermissions.size();
12931        for (int i=0; i<N; i++) {
12932            final String name = pkg.requestedPermissions.get(i);
12933            final BasePermission bp = mSettings.mPermissions.get(name);
12934            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12935                    >= Build.VERSION_CODES.M;
12936
12937            if (DEBUG_INSTALL) {
12938                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12939            }
12940
12941            if (bp == null || bp.packageSetting == null) {
12942                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12943                    if (DEBUG_PERMISSIONS) {
12944                        Slog.i(TAG, "Unknown permission " + name
12945                                + " in package " + pkg.packageName);
12946                    }
12947                }
12948                continue;
12949            }
12950
12951
12952            // Limit ephemeral apps to ephemeral allowed permissions.
12953            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12954                if (DEBUG_PERMISSIONS) {
12955                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12956                            + pkg.packageName);
12957                }
12958                continue;
12959            }
12960
12961            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12962                if (DEBUG_PERMISSIONS) {
12963                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12964                            + pkg.packageName);
12965                }
12966                continue;
12967            }
12968
12969            final String perm = bp.name;
12970            boolean allowedSig = false;
12971            int grant = GRANT_DENIED;
12972
12973            // Keep track of app op permissions.
12974            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12975                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12976                if (pkgs == null) {
12977                    pkgs = new ArraySet<>();
12978                    mAppOpPermissionPackages.put(bp.name, pkgs);
12979                }
12980                pkgs.add(pkg.packageName);
12981            }
12982
12983            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12984            switch (level) {
12985                case PermissionInfo.PROTECTION_NORMAL: {
12986                    // For all apps normal permissions are install time ones.
12987                    grant = GRANT_INSTALL;
12988                } break;
12989
12990                case PermissionInfo.PROTECTION_DANGEROUS: {
12991                    // If a permission review is required for legacy apps we represent
12992                    // their permissions as always granted runtime ones since we need
12993                    // to keep the review required permission flag per user while an
12994                    // install permission's state is shared across all users.
12995                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12996                        // For legacy apps dangerous permissions are install time ones.
12997                        grant = GRANT_INSTALL;
12998                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12999                        // For legacy apps that became modern, install becomes runtime.
13000                        grant = GRANT_UPGRADE;
13001                    } else if (mPromoteSystemApps
13002                            && isSystemApp(ps)
13003                            && mExistingSystemPackages.contains(ps.name)) {
13004                        // For legacy system apps, install becomes runtime.
13005                        // We cannot check hasInstallPermission() for system apps since those
13006                        // permissions were granted implicitly and not persisted pre-M.
13007                        grant = GRANT_UPGRADE;
13008                    } else {
13009                        // For modern apps keep runtime permissions unchanged.
13010                        grant = GRANT_RUNTIME;
13011                    }
13012                } break;
13013
13014                case PermissionInfo.PROTECTION_SIGNATURE: {
13015                    // For all apps signature permissions are install time ones.
13016                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13017                    if (allowedSig) {
13018                        grant = GRANT_INSTALL;
13019                    }
13020                } break;
13021            }
13022
13023            if (DEBUG_PERMISSIONS) {
13024                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13025            }
13026
13027            if (grant != GRANT_DENIED) {
13028                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13029                    // If this is an existing, non-system package, then
13030                    // we can't add any new permissions to it.
13031                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13032                        // Except...  if this is a permission that was added
13033                        // to the platform (note: need to only do this when
13034                        // updating the platform).
13035                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13036                            grant = GRANT_DENIED;
13037                        }
13038                    }
13039                }
13040
13041                switch (grant) {
13042                    case GRANT_INSTALL: {
13043                        // Revoke this as runtime permission to handle the case of
13044                        // a runtime permission being downgraded to an install one.
13045                        // Also in permission review mode we keep dangerous permissions
13046                        // for legacy apps
13047                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13048                            if (origPermissions.getRuntimePermissionState(
13049                                    bp.name, userId) != null) {
13050                                // Revoke the runtime permission and clear the flags.
13051                                origPermissions.revokeRuntimePermission(bp, userId);
13052                                origPermissions.updatePermissionFlags(bp, userId,
13053                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13054                                // If we revoked a permission permission, we have to write.
13055                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13056                                        changedRuntimePermissionUserIds, userId);
13057                            }
13058                        }
13059                        // Grant an install permission.
13060                        if (permissionsState.grantInstallPermission(bp) !=
13061                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13062                            changedInstallPermission = true;
13063                        }
13064                    } break;
13065
13066                    case GRANT_RUNTIME: {
13067                        // Grant previously granted runtime permissions.
13068                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13069                            PermissionState permissionState = origPermissions
13070                                    .getRuntimePermissionState(bp.name, userId);
13071                            int flags = permissionState != null
13072                                    ? permissionState.getFlags() : 0;
13073                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13074                                // Don't propagate the permission in a permission review mode if
13075                                // the former was revoked, i.e. marked to not propagate on upgrade.
13076                                // Note that in a permission review mode install permissions are
13077                                // represented as constantly granted runtime ones since we need to
13078                                // keep a per user state associated with the permission. Also the
13079                                // revoke on upgrade flag is no longer applicable and is reset.
13080                                final boolean revokeOnUpgrade = (flags & PackageManager
13081                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13082                                if (revokeOnUpgrade) {
13083                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13084                                    // Since we changed the flags, we have to write.
13085                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13086                                            changedRuntimePermissionUserIds, userId);
13087                                }
13088                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13089                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13090                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13091                                        // If we cannot put the permission as it was,
13092                                        // we have to write.
13093                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13094                                                changedRuntimePermissionUserIds, userId);
13095                                    }
13096                                }
13097
13098                                // If the app supports runtime permissions no need for a review.
13099                                if (mPermissionReviewRequired
13100                                        && appSupportsRuntimePermissions
13101                                        && (flags & PackageManager
13102                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13103                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13104                                    // Since we changed the flags, we have to write.
13105                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13106                                            changedRuntimePermissionUserIds, userId);
13107                                }
13108                            } else if (mPermissionReviewRequired
13109                                    && !appSupportsRuntimePermissions) {
13110                                // For legacy apps that need a permission review, every new
13111                                // runtime permission is granted but it is pending a review.
13112                                // We also need to review only platform defined runtime
13113                                // permissions as these are the only ones the platform knows
13114                                // how to disable the API to simulate revocation as legacy
13115                                // apps don't expect to run with revoked permissions.
13116                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13117                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13118                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13119                                        // We changed the flags, hence have to write.
13120                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13121                                                changedRuntimePermissionUserIds, userId);
13122                                    }
13123                                }
13124                                if (permissionsState.grantRuntimePermission(bp, userId)
13125                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13126                                    // We changed the permission, hence have to write.
13127                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13128                                            changedRuntimePermissionUserIds, userId);
13129                                }
13130                            }
13131                            // Propagate the permission flags.
13132                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13133                        }
13134                    } break;
13135
13136                    case GRANT_UPGRADE: {
13137                        // Grant runtime permissions for a previously held install permission.
13138                        PermissionState permissionState = origPermissions
13139                                .getInstallPermissionState(bp.name);
13140                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13141
13142                        if (origPermissions.revokeInstallPermission(bp)
13143                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13144                            // We will be transferring the permission flags, so clear them.
13145                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13146                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13147                            changedInstallPermission = true;
13148                        }
13149
13150                        // If the permission is not to be promoted to runtime we ignore it and
13151                        // also its other flags as they are not applicable to install permissions.
13152                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13153                            for (int userId : currentUserIds) {
13154                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13155                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13156                                    // Transfer the permission flags.
13157                                    permissionsState.updatePermissionFlags(bp, userId,
13158                                            flags, flags);
13159                                    // If we granted the permission, we have to write.
13160                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13161                                            changedRuntimePermissionUserIds, userId);
13162                                }
13163                            }
13164                        }
13165                    } break;
13166
13167                    default: {
13168                        if (packageOfInterest == null
13169                                || packageOfInterest.equals(pkg.packageName)) {
13170                            if (DEBUG_PERMISSIONS) {
13171                                Slog.i(TAG, "Not granting permission " + perm
13172                                        + " to package " + pkg.packageName
13173                                        + " because it was previously installed without");
13174                            }
13175                        }
13176                    } break;
13177                }
13178            } else {
13179                if (permissionsState.revokeInstallPermission(bp) !=
13180                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13181                    // Also drop the permission flags.
13182                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13183                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13184                    changedInstallPermission = true;
13185                    Slog.i(TAG, "Un-granting permission " + perm
13186                            + " from package " + pkg.packageName
13187                            + " (protectionLevel=" + bp.protectionLevel
13188                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13189                            + ")");
13190                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13191                    // Don't print warning for app op permissions, since it is fine for them
13192                    // not to be granted, there is a UI for the user to decide.
13193                    if (DEBUG_PERMISSIONS
13194                            && (packageOfInterest == null
13195                                    || packageOfInterest.equals(pkg.packageName))) {
13196                        Slog.i(TAG, "Not granting permission " + perm
13197                                + " to package " + pkg.packageName
13198                                + " (protectionLevel=" + bp.protectionLevel
13199                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13200                                + ")");
13201                    }
13202                }
13203            }
13204        }
13205
13206        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13207                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13208            // This is the first that we have heard about this package, so the
13209            // permissions we have now selected are fixed until explicitly
13210            // changed.
13211            ps.installPermissionsFixed = true;
13212        }
13213
13214        // Persist the runtime permissions state for users with changes. If permissions
13215        // were revoked because no app in the shared user declares them we have to
13216        // write synchronously to avoid losing runtime permissions state.
13217        for (int userId : changedRuntimePermissionUserIds) {
13218            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13219        }
13220    }
13221
13222    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13223        boolean allowed = false;
13224        final int NP = PackageParser.NEW_PERMISSIONS.length;
13225        for (int ip=0; ip<NP; ip++) {
13226            final PackageParser.NewPermissionInfo npi
13227                    = PackageParser.NEW_PERMISSIONS[ip];
13228            if (npi.name.equals(perm)
13229                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13230                allowed = true;
13231                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13232                        + pkg.packageName);
13233                break;
13234            }
13235        }
13236        return allowed;
13237    }
13238
13239    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13240            BasePermission bp, PermissionsState origPermissions) {
13241        boolean privilegedPermission = (bp.protectionLevel
13242                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13243        boolean privappPermissionsDisable =
13244                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13245        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13246        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13247        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13248                && !platformPackage && platformPermission) {
13249            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13250                    .getPrivAppPermissions(pkg.packageName);
13251            final boolean whitelisted =
13252                    allowedPermissions != null && allowedPermissions.contains(perm);
13253            if (!whitelisted) {
13254                Slog.w(TAG, "Privileged permission " + perm + " for package "
13255                        + pkg.packageName + " - not in privapp-permissions whitelist");
13256                // Only report violations for apps on system image
13257                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13258                    // it's only a reportable violation if the permission isn't explicitly denied
13259                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13260                            .getPrivAppDenyPermissions(pkg.packageName);
13261                    final boolean permissionViolation =
13262                            deniedPermissions == null || !deniedPermissions.contains(perm);
13263                    if (permissionViolation) {
13264                        if (mPrivappPermissionsViolations == null) {
13265                            mPrivappPermissionsViolations = new ArraySet<>();
13266                        }
13267                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13268                    } else {
13269                        return false;
13270                    }
13271                }
13272                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13273                    return false;
13274                }
13275            }
13276        }
13277        boolean allowed = (compareSignatures(
13278                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13279                        == PackageManager.SIGNATURE_MATCH)
13280                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13281                        == PackageManager.SIGNATURE_MATCH);
13282        if (!allowed && privilegedPermission) {
13283            if (isSystemApp(pkg)) {
13284                // For updated system applications, a system permission
13285                // is granted only if it had been defined by the original application.
13286                if (pkg.isUpdatedSystemApp()) {
13287                    final PackageSetting sysPs = mSettings
13288                            .getDisabledSystemPkgLPr(pkg.packageName);
13289                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13290                        // If the original was granted this permission, we take
13291                        // that grant decision as read and propagate it to the
13292                        // update.
13293                        if (sysPs.isPrivileged()) {
13294                            allowed = true;
13295                        }
13296                    } else {
13297                        // The system apk may have been updated with an older
13298                        // version of the one on the data partition, but which
13299                        // granted a new system permission that it didn't have
13300                        // before.  In this case we do want to allow the app to
13301                        // now get the new permission if the ancestral apk is
13302                        // privileged to get it.
13303                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13304                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13305                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13306                                    allowed = true;
13307                                    break;
13308                                }
13309                            }
13310                        }
13311                        // Also if a privileged parent package on the system image or any of
13312                        // its children requested a privileged permission, the updated child
13313                        // packages can also get the permission.
13314                        if (pkg.parentPackage != null) {
13315                            final PackageSetting disabledSysParentPs = mSettings
13316                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13317                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13318                                    && disabledSysParentPs.isPrivileged()) {
13319                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13320                                    allowed = true;
13321                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13322                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13323                                    for (int i = 0; i < count; i++) {
13324                                        PackageParser.Package disabledSysChildPkg =
13325                                                disabledSysParentPs.pkg.childPackages.get(i);
13326                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13327                                                perm)) {
13328                                            allowed = true;
13329                                            break;
13330                                        }
13331                                    }
13332                                }
13333                            }
13334                        }
13335                    }
13336                } else {
13337                    allowed = isPrivilegedApp(pkg);
13338                }
13339            }
13340        }
13341        if (!allowed) {
13342            if (!allowed && (bp.protectionLevel
13343                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13344                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13345                // If this was a previously normal/dangerous permission that got moved
13346                // to a system permission as part of the runtime permission redesign, then
13347                // we still want to blindly grant it to old apps.
13348                allowed = true;
13349            }
13350            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13351                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13352                // If this permission is to be granted to the system installer and
13353                // this app is an installer, then it gets the permission.
13354                allowed = true;
13355            }
13356            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13357                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13358                // If this permission is to be granted to the system verifier and
13359                // this app is a verifier, then it gets the permission.
13360                allowed = true;
13361            }
13362            if (!allowed && (bp.protectionLevel
13363                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13364                    && isSystemApp(pkg)) {
13365                // Any pre-installed system app is allowed to get this permission.
13366                allowed = true;
13367            }
13368            if (!allowed && (bp.protectionLevel
13369                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13370                // For development permissions, a development permission
13371                // is granted only if it was already granted.
13372                allowed = origPermissions.hasInstallPermission(perm);
13373            }
13374            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13375                    && pkg.packageName.equals(mSetupWizardPackage)) {
13376                // If this permission is to be granted to the system setup wizard and
13377                // this app is a setup wizard, then it gets the permission.
13378                allowed = true;
13379            }
13380        }
13381        return allowed;
13382    }
13383
13384    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13385        final int permCount = pkg.requestedPermissions.size();
13386        for (int j = 0; j < permCount; j++) {
13387            String requestedPermission = pkg.requestedPermissions.get(j);
13388            if (permission.equals(requestedPermission)) {
13389                return true;
13390            }
13391        }
13392        return false;
13393    }
13394
13395    final class ActivityIntentResolver
13396            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13397        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13398                boolean defaultOnly, int userId) {
13399            if (!sUserManager.exists(userId)) return null;
13400            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13401            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13402        }
13403
13404        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13405                int userId) {
13406            if (!sUserManager.exists(userId)) return null;
13407            mFlags = flags;
13408            return super.queryIntent(intent, resolvedType,
13409                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13410                    userId);
13411        }
13412
13413        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13414                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13415            if (!sUserManager.exists(userId)) return null;
13416            if (packageActivities == null) {
13417                return null;
13418            }
13419            mFlags = flags;
13420            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13421            final int N = packageActivities.size();
13422            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13423                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13424
13425            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13426            for (int i = 0; i < N; ++i) {
13427                intentFilters = packageActivities.get(i).intents;
13428                if (intentFilters != null && intentFilters.size() > 0) {
13429                    PackageParser.ActivityIntentInfo[] array =
13430                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13431                    intentFilters.toArray(array);
13432                    listCut.add(array);
13433                }
13434            }
13435            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13436        }
13437
13438        /**
13439         * Finds a privileged activity that matches the specified activity names.
13440         */
13441        private PackageParser.Activity findMatchingActivity(
13442                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13443            for (PackageParser.Activity sysActivity : activityList) {
13444                if (sysActivity.info.name.equals(activityInfo.name)) {
13445                    return sysActivity;
13446                }
13447                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13448                    return sysActivity;
13449                }
13450                if (sysActivity.info.targetActivity != null) {
13451                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13452                        return sysActivity;
13453                    }
13454                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13455                        return sysActivity;
13456                    }
13457                }
13458            }
13459            return null;
13460        }
13461
13462        public class IterGenerator<E> {
13463            public Iterator<E> generate(ActivityIntentInfo info) {
13464                return null;
13465            }
13466        }
13467
13468        public class ActionIterGenerator extends IterGenerator<String> {
13469            @Override
13470            public Iterator<String> generate(ActivityIntentInfo info) {
13471                return info.actionsIterator();
13472            }
13473        }
13474
13475        public class CategoriesIterGenerator extends IterGenerator<String> {
13476            @Override
13477            public Iterator<String> generate(ActivityIntentInfo info) {
13478                return info.categoriesIterator();
13479            }
13480        }
13481
13482        public class SchemesIterGenerator extends IterGenerator<String> {
13483            @Override
13484            public Iterator<String> generate(ActivityIntentInfo info) {
13485                return info.schemesIterator();
13486            }
13487        }
13488
13489        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13490            @Override
13491            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13492                return info.authoritiesIterator();
13493            }
13494        }
13495
13496        /**
13497         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13498         * MODIFIED. Do not pass in a list that should not be changed.
13499         */
13500        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13501                IterGenerator<T> generator, Iterator<T> searchIterator) {
13502            // loop through the set of actions; every one must be found in the intent filter
13503            while (searchIterator.hasNext()) {
13504                // we must have at least one filter in the list to consider a match
13505                if (intentList.size() == 0) {
13506                    break;
13507                }
13508
13509                final T searchAction = searchIterator.next();
13510
13511                // loop through the set of intent filters
13512                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13513                while (intentIter.hasNext()) {
13514                    final ActivityIntentInfo intentInfo = intentIter.next();
13515                    boolean selectionFound = false;
13516
13517                    // loop through the intent filter's selection criteria; at least one
13518                    // of them must match the searched criteria
13519                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13520                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13521                        final T intentSelection = intentSelectionIter.next();
13522                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13523                            selectionFound = true;
13524                            break;
13525                        }
13526                    }
13527
13528                    // the selection criteria wasn't found in this filter's set; this filter
13529                    // is not a potential match
13530                    if (!selectionFound) {
13531                        intentIter.remove();
13532                    }
13533                }
13534            }
13535        }
13536
13537        private boolean isProtectedAction(ActivityIntentInfo filter) {
13538            final Iterator<String> actionsIter = filter.actionsIterator();
13539            while (actionsIter != null && actionsIter.hasNext()) {
13540                final String filterAction = actionsIter.next();
13541                if (PROTECTED_ACTIONS.contains(filterAction)) {
13542                    return true;
13543                }
13544            }
13545            return false;
13546        }
13547
13548        /**
13549         * Adjusts the priority of the given intent filter according to policy.
13550         * <p>
13551         * <ul>
13552         * <li>The priority for non privileged applications is capped to '0'</li>
13553         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13554         * <li>The priority for unbundled updates to privileged applications is capped to the
13555         *      priority defined on the system partition</li>
13556         * </ul>
13557         * <p>
13558         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13559         * allowed to obtain any priority on any action.
13560         */
13561        private void adjustPriority(
13562                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13563            // nothing to do; priority is fine as-is
13564            if (intent.getPriority() <= 0) {
13565                return;
13566            }
13567
13568            final ActivityInfo activityInfo = intent.activity.info;
13569            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13570
13571            final boolean privilegedApp =
13572                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13573            if (!privilegedApp) {
13574                // non-privileged applications can never define a priority >0
13575                if (DEBUG_FILTERS) {
13576                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13577                            + " package: " + applicationInfo.packageName
13578                            + " activity: " + intent.activity.className
13579                            + " origPrio: " + intent.getPriority());
13580                }
13581                intent.setPriority(0);
13582                return;
13583            }
13584
13585            if (systemActivities == null) {
13586                // the system package is not disabled; we're parsing the system partition
13587                if (isProtectedAction(intent)) {
13588                    if (mDeferProtectedFilters) {
13589                        // We can't deal with these just yet. No component should ever obtain a
13590                        // >0 priority for a protected actions, with ONE exception -- the setup
13591                        // wizard. The setup wizard, however, cannot be known until we're able to
13592                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13593                        // until all intent filters have been processed. Chicken, meet egg.
13594                        // Let the filter temporarily have a high priority and rectify the
13595                        // priorities after all system packages have been scanned.
13596                        mProtectedFilters.add(intent);
13597                        if (DEBUG_FILTERS) {
13598                            Slog.i(TAG, "Protected action; save for later;"
13599                                    + " package: " + applicationInfo.packageName
13600                                    + " activity: " + intent.activity.className
13601                                    + " origPrio: " + intent.getPriority());
13602                        }
13603                        return;
13604                    } else {
13605                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13606                            Slog.i(TAG, "No setup wizard;"
13607                                + " All protected intents capped to priority 0");
13608                        }
13609                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13610                            if (DEBUG_FILTERS) {
13611                                Slog.i(TAG, "Found setup wizard;"
13612                                    + " allow priority " + intent.getPriority() + ";"
13613                                    + " package: " + intent.activity.info.packageName
13614                                    + " activity: " + intent.activity.className
13615                                    + " priority: " + intent.getPriority());
13616                            }
13617                            // setup wizard gets whatever it wants
13618                            return;
13619                        }
13620                        if (DEBUG_FILTERS) {
13621                            Slog.i(TAG, "Protected action; cap priority to 0;"
13622                                    + " package: " + intent.activity.info.packageName
13623                                    + " activity: " + intent.activity.className
13624                                    + " origPrio: " + intent.getPriority());
13625                        }
13626                        intent.setPriority(0);
13627                        return;
13628                    }
13629                }
13630                // privileged apps on the system image get whatever priority they request
13631                return;
13632            }
13633
13634            // privileged app unbundled update ... try to find the same activity
13635            final PackageParser.Activity foundActivity =
13636                    findMatchingActivity(systemActivities, activityInfo);
13637            if (foundActivity == null) {
13638                // this is a new activity; it cannot obtain >0 priority
13639                if (DEBUG_FILTERS) {
13640                    Slog.i(TAG, "New activity; cap priority to 0;"
13641                            + " package: " + applicationInfo.packageName
13642                            + " activity: " + intent.activity.className
13643                            + " origPrio: " + intent.getPriority());
13644                }
13645                intent.setPriority(0);
13646                return;
13647            }
13648
13649            // found activity, now check for filter equivalence
13650
13651            // a shallow copy is enough; we modify the list, not its contents
13652            final List<ActivityIntentInfo> intentListCopy =
13653                    new ArrayList<>(foundActivity.intents);
13654            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13655
13656            // find matching action subsets
13657            final Iterator<String> actionsIterator = intent.actionsIterator();
13658            if (actionsIterator != null) {
13659                getIntentListSubset(
13660                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13661                if (intentListCopy.size() == 0) {
13662                    // no more intents to match; we're not equivalent
13663                    if (DEBUG_FILTERS) {
13664                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13665                                + " package: " + applicationInfo.packageName
13666                                + " activity: " + intent.activity.className
13667                                + " origPrio: " + intent.getPriority());
13668                    }
13669                    intent.setPriority(0);
13670                    return;
13671                }
13672            }
13673
13674            // find matching category subsets
13675            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13676            if (categoriesIterator != null) {
13677                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13678                        categoriesIterator);
13679                if (intentListCopy.size() == 0) {
13680                    // no more intents to match; we're not equivalent
13681                    if (DEBUG_FILTERS) {
13682                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13683                                + " package: " + applicationInfo.packageName
13684                                + " activity: " + intent.activity.className
13685                                + " origPrio: " + intent.getPriority());
13686                    }
13687                    intent.setPriority(0);
13688                    return;
13689                }
13690            }
13691
13692            // find matching schemes subsets
13693            final Iterator<String> schemesIterator = intent.schemesIterator();
13694            if (schemesIterator != null) {
13695                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13696                        schemesIterator);
13697                if (intentListCopy.size() == 0) {
13698                    // no more intents to match; we're not equivalent
13699                    if (DEBUG_FILTERS) {
13700                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13701                                + " package: " + applicationInfo.packageName
13702                                + " activity: " + intent.activity.className
13703                                + " origPrio: " + intent.getPriority());
13704                    }
13705                    intent.setPriority(0);
13706                    return;
13707                }
13708            }
13709
13710            // find matching authorities subsets
13711            final Iterator<IntentFilter.AuthorityEntry>
13712                    authoritiesIterator = intent.authoritiesIterator();
13713            if (authoritiesIterator != null) {
13714                getIntentListSubset(intentListCopy,
13715                        new AuthoritiesIterGenerator(),
13716                        authoritiesIterator);
13717                if (intentListCopy.size() == 0) {
13718                    // no more intents to match; we're not equivalent
13719                    if (DEBUG_FILTERS) {
13720                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13721                                + " package: " + applicationInfo.packageName
13722                                + " activity: " + intent.activity.className
13723                                + " origPrio: " + intent.getPriority());
13724                    }
13725                    intent.setPriority(0);
13726                    return;
13727                }
13728            }
13729
13730            // we found matching filter(s); app gets the max priority of all intents
13731            int cappedPriority = 0;
13732            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13733                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13734            }
13735            if (intent.getPriority() > cappedPriority) {
13736                if (DEBUG_FILTERS) {
13737                    Slog.i(TAG, "Found matching filter(s);"
13738                            + " cap priority to " + cappedPriority + ";"
13739                            + " package: " + applicationInfo.packageName
13740                            + " activity: " + intent.activity.className
13741                            + " origPrio: " + intent.getPriority());
13742                }
13743                intent.setPriority(cappedPriority);
13744                return;
13745            }
13746            // all this for nothing; the requested priority was <= what was on the system
13747        }
13748
13749        public final void addActivity(PackageParser.Activity a, String type) {
13750            mActivities.put(a.getComponentName(), a);
13751            if (DEBUG_SHOW_INFO)
13752                Log.v(
13753                TAG, "  " + type + " " +
13754                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13755            if (DEBUG_SHOW_INFO)
13756                Log.v(TAG, "    Class=" + a.info.name);
13757            final int NI = a.intents.size();
13758            for (int j=0; j<NI; j++) {
13759                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13760                if ("activity".equals(type)) {
13761                    final PackageSetting ps =
13762                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13763                    final List<PackageParser.Activity> systemActivities =
13764                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13765                    adjustPriority(systemActivities, intent);
13766                }
13767                if (DEBUG_SHOW_INFO) {
13768                    Log.v(TAG, "    IntentFilter:");
13769                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13770                }
13771                if (!intent.debugCheck()) {
13772                    Log.w(TAG, "==> For Activity " + a.info.name);
13773                }
13774                addFilter(intent);
13775            }
13776        }
13777
13778        public final void removeActivity(PackageParser.Activity a, String type) {
13779            mActivities.remove(a.getComponentName());
13780            if (DEBUG_SHOW_INFO) {
13781                Log.v(TAG, "  " + type + " "
13782                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13783                                : a.info.name) + ":");
13784                Log.v(TAG, "    Class=" + a.info.name);
13785            }
13786            final int NI = a.intents.size();
13787            for (int j=0; j<NI; j++) {
13788                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13789                if (DEBUG_SHOW_INFO) {
13790                    Log.v(TAG, "    IntentFilter:");
13791                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13792                }
13793                removeFilter(intent);
13794            }
13795        }
13796
13797        @Override
13798        protected boolean allowFilterResult(
13799                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13800            ActivityInfo filterAi = filter.activity.info;
13801            for (int i=dest.size()-1; i>=0; i--) {
13802                ActivityInfo destAi = dest.get(i).activityInfo;
13803                if (destAi.name == filterAi.name
13804                        && destAi.packageName == filterAi.packageName) {
13805                    return false;
13806                }
13807            }
13808            return true;
13809        }
13810
13811        @Override
13812        protected ActivityIntentInfo[] newArray(int size) {
13813            return new ActivityIntentInfo[size];
13814        }
13815
13816        @Override
13817        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13818            if (!sUserManager.exists(userId)) return true;
13819            PackageParser.Package p = filter.activity.owner;
13820            if (p != null) {
13821                PackageSetting ps = (PackageSetting)p.mExtras;
13822                if (ps != null) {
13823                    // System apps are never considered stopped for purposes of
13824                    // filtering, because there may be no way for the user to
13825                    // actually re-launch them.
13826                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13827                            && ps.getStopped(userId);
13828                }
13829            }
13830            return false;
13831        }
13832
13833        @Override
13834        protected boolean isPackageForFilter(String packageName,
13835                PackageParser.ActivityIntentInfo info) {
13836            return packageName.equals(info.activity.owner.packageName);
13837        }
13838
13839        @Override
13840        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13841                int match, int userId) {
13842            if (!sUserManager.exists(userId)) return null;
13843            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13844                return null;
13845            }
13846            final PackageParser.Activity activity = info.activity;
13847            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13848            if (ps == null) {
13849                return null;
13850            }
13851            final PackageUserState userState = ps.readUserState(userId);
13852            ActivityInfo ai =
13853                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13854            if (ai == null) {
13855                return null;
13856            }
13857            final boolean matchExplicitlyVisibleOnly =
13858                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13859            final boolean matchVisibleToInstantApp =
13860                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13861            final boolean componentVisible =
13862                    matchVisibleToInstantApp
13863                    && info.isVisibleToInstantApp()
13864                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13865            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13866            // throw out filters that aren't visible to ephemeral apps
13867            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13868                return null;
13869            }
13870            // throw out instant app filters if we're not explicitly requesting them
13871            if (!matchInstantApp && userState.instantApp) {
13872                return null;
13873            }
13874            // throw out instant app filters if updates are available; will trigger
13875            // instant app resolution
13876            if (userState.instantApp && ps.isUpdateAvailable()) {
13877                return null;
13878            }
13879            final ResolveInfo res = new ResolveInfo();
13880            res.activityInfo = ai;
13881            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13882                res.filter = info;
13883            }
13884            if (info != null) {
13885                res.handleAllWebDataURI = info.handleAllWebDataURI();
13886            }
13887            res.priority = info.getPriority();
13888            res.preferredOrder = activity.owner.mPreferredOrder;
13889            //System.out.println("Result: " + res.activityInfo.className +
13890            //                   " = " + res.priority);
13891            res.match = match;
13892            res.isDefault = info.hasDefault;
13893            res.labelRes = info.labelRes;
13894            res.nonLocalizedLabel = info.nonLocalizedLabel;
13895            if (userNeedsBadging(userId)) {
13896                res.noResourceId = true;
13897            } else {
13898                res.icon = info.icon;
13899            }
13900            res.iconResourceId = info.icon;
13901            res.system = res.activityInfo.applicationInfo.isSystemApp();
13902            res.isInstantAppAvailable = userState.instantApp;
13903            return res;
13904        }
13905
13906        @Override
13907        protected void sortResults(List<ResolveInfo> results) {
13908            Collections.sort(results, mResolvePrioritySorter);
13909        }
13910
13911        @Override
13912        protected void dumpFilter(PrintWriter out, String prefix,
13913                PackageParser.ActivityIntentInfo filter) {
13914            out.print(prefix); out.print(
13915                    Integer.toHexString(System.identityHashCode(filter.activity)));
13916                    out.print(' ');
13917                    filter.activity.printComponentShortName(out);
13918                    out.print(" filter ");
13919                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13920        }
13921
13922        @Override
13923        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13924            return filter.activity;
13925        }
13926
13927        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13928            PackageParser.Activity activity = (PackageParser.Activity)label;
13929            out.print(prefix); out.print(
13930                    Integer.toHexString(System.identityHashCode(activity)));
13931                    out.print(' ');
13932                    activity.printComponentShortName(out);
13933            if (count > 1) {
13934                out.print(" ("); out.print(count); out.print(" filters)");
13935            }
13936            out.println();
13937        }
13938
13939        // Keys are String (activity class name), values are Activity.
13940        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13941                = new ArrayMap<ComponentName, PackageParser.Activity>();
13942        private int mFlags;
13943    }
13944
13945    private final class ServiceIntentResolver
13946            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13947        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13948                boolean defaultOnly, int userId) {
13949            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13950            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13951        }
13952
13953        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13954                int userId) {
13955            if (!sUserManager.exists(userId)) return null;
13956            mFlags = flags;
13957            return super.queryIntent(intent, resolvedType,
13958                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13959                    userId);
13960        }
13961
13962        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13963                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13964            if (!sUserManager.exists(userId)) return null;
13965            if (packageServices == null) {
13966                return null;
13967            }
13968            mFlags = flags;
13969            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13970            final int N = packageServices.size();
13971            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13972                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13973
13974            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13975            for (int i = 0; i < N; ++i) {
13976                intentFilters = packageServices.get(i).intents;
13977                if (intentFilters != null && intentFilters.size() > 0) {
13978                    PackageParser.ServiceIntentInfo[] array =
13979                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13980                    intentFilters.toArray(array);
13981                    listCut.add(array);
13982                }
13983            }
13984            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13985        }
13986
13987        public final void addService(PackageParser.Service s) {
13988            mServices.put(s.getComponentName(), s);
13989            if (DEBUG_SHOW_INFO) {
13990                Log.v(TAG, "  "
13991                        + (s.info.nonLocalizedLabel != null
13992                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13993                Log.v(TAG, "    Class=" + s.info.name);
13994            }
13995            final int NI = s.intents.size();
13996            int j;
13997            for (j=0; j<NI; j++) {
13998                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13999                if (DEBUG_SHOW_INFO) {
14000                    Log.v(TAG, "    IntentFilter:");
14001                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14002                }
14003                if (!intent.debugCheck()) {
14004                    Log.w(TAG, "==> For Service " + s.info.name);
14005                }
14006                addFilter(intent);
14007            }
14008        }
14009
14010        public final void removeService(PackageParser.Service s) {
14011            mServices.remove(s.getComponentName());
14012            if (DEBUG_SHOW_INFO) {
14013                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14014                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14015                Log.v(TAG, "    Class=" + s.info.name);
14016            }
14017            final int NI = s.intents.size();
14018            int j;
14019            for (j=0; j<NI; j++) {
14020                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14021                if (DEBUG_SHOW_INFO) {
14022                    Log.v(TAG, "    IntentFilter:");
14023                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14024                }
14025                removeFilter(intent);
14026            }
14027        }
14028
14029        @Override
14030        protected boolean allowFilterResult(
14031                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14032            ServiceInfo filterSi = filter.service.info;
14033            for (int i=dest.size()-1; i>=0; i--) {
14034                ServiceInfo destAi = dest.get(i).serviceInfo;
14035                if (destAi.name == filterSi.name
14036                        && destAi.packageName == filterSi.packageName) {
14037                    return false;
14038                }
14039            }
14040            return true;
14041        }
14042
14043        @Override
14044        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14045            return new PackageParser.ServiceIntentInfo[size];
14046        }
14047
14048        @Override
14049        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14050            if (!sUserManager.exists(userId)) return true;
14051            PackageParser.Package p = filter.service.owner;
14052            if (p != null) {
14053                PackageSetting ps = (PackageSetting)p.mExtras;
14054                if (ps != null) {
14055                    // System apps are never considered stopped for purposes of
14056                    // filtering, because there may be no way for the user to
14057                    // actually re-launch them.
14058                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14059                            && ps.getStopped(userId);
14060                }
14061            }
14062            return false;
14063        }
14064
14065        @Override
14066        protected boolean isPackageForFilter(String packageName,
14067                PackageParser.ServiceIntentInfo info) {
14068            return packageName.equals(info.service.owner.packageName);
14069        }
14070
14071        @Override
14072        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14073                int match, int userId) {
14074            if (!sUserManager.exists(userId)) return null;
14075            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14076            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14077                return null;
14078            }
14079            final PackageParser.Service service = info.service;
14080            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14081            if (ps == null) {
14082                return null;
14083            }
14084            final PackageUserState userState = ps.readUserState(userId);
14085            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14086                    userState, userId);
14087            if (si == null) {
14088                return null;
14089            }
14090            final boolean matchVisibleToInstantApp =
14091                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14092            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14093            // throw out filters that aren't visible to ephemeral apps
14094            if (matchVisibleToInstantApp
14095                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14096                return null;
14097            }
14098            // throw out ephemeral filters if we're not explicitly requesting them
14099            if (!isInstantApp && userState.instantApp) {
14100                return null;
14101            }
14102            // throw out instant app filters if updates are available; will trigger
14103            // instant app resolution
14104            if (userState.instantApp && ps.isUpdateAvailable()) {
14105                return null;
14106            }
14107            final ResolveInfo res = new ResolveInfo();
14108            res.serviceInfo = si;
14109            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14110                res.filter = filter;
14111            }
14112            res.priority = info.getPriority();
14113            res.preferredOrder = service.owner.mPreferredOrder;
14114            res.match = match;
14115            res.isDefault = info.hasDefault;
14116            res.labelRes = info.labelRes;
14117            res.nonLocalizedLabel = info.nonLocalizedLabel;
14118            res.icon = info.icon;
14119            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14120            return res;
14121        }
14122
14123        @Override
14124        protected void sortResults(List<ResolveInfo> results) {
14125            Collections.sort(results, mResolvePrioritySorter);
14126        }
14127
14128        @Override
14129        protected void dumpFilter(PrintWriter out, String prefix,
14130                PackageParser.ServiceIntentInfo filter) {
14131            out.print(prefix); out.print(
14132                    Integer.toHexString(System.identityHashCode(filter.service)));
14133                    out.print(' ');
14134                    filter.service.printComponentShortName(out);
14135                    out.print(" filter ");
14136                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14137        }
14138
14139        @Override
14140        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14141            return filter.service;
14142        }
14143
14144        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14145            PackageParser.Service service = (PackageParser.Service)label;
14146            out.print(prefix); out.print(
14147                    Integer.toHexString(System.identityHashCode(service)));
14148                    out.print(' ');
14149                    service.printComponentShortName(out);
14150            if (count > 1) {
14151                out.print(" ("); out.print(count); out.print(" filters)");
14152            }
14153            out.println();
14154        }
14155
14156//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14157//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14158//            final List<ResolveInfo> retList = Lists.newArrayList();
14159//            while (i.hasNext()) {
14160//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14161//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14162//                    retList.add(resolveInfo);
14163//                }
14164//            }
14165//            return retList;
14166//        }
14167
14168        // Keys are String (activity class name), values are Activity.
14169        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14170                = new ArrayMap<ComponentName, PackageParser.Service>();
14171        private int mFlags;
14172    }
14173
14174    private final class ProviderIntentResolver
14175            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14176        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14177                boolean defaultOnly, int userId) {
14178            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14179            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14180        }
14181
14182        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14183                int userId) {
14184            if (!sUserManager.exists(userId))
14185                return null;
14186            mFlags = flags;
14187            return super.queryIntent(intent, resolvedType,
14188                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14189                    userId);
14190        }
14191
14192        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14193                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14194            if (!sUserManager.exists(userId))
14195                return null;
14196            if (packageProviders == null) {
14197                return null;
14198            }
14199            mFlags = flags;
14200            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14201            final int N = packageProviders.size();
14202            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14203                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14204
14205            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14206            for (int i = 0; i < N; ++i) {
14207                intentFilters = packageProviders.get(i).intents;
14208                if (intentFilters != null && intentFilters.size() > 0) {
14209                    PackageParser.ProviderIntentInfo[] array =
14210                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14211                    intentFilters.toArray(array);
14212                    listCut.add(array);
14213                }
14214            }
14215            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14216        }
14217
14218        public final void addProvider(PackageParser.Provider p) {
14219            if (mProviders.containsKey(p.getComponentName())) {
14220                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14221                return;
14222            }
14223
14224            mProviders.put(p.getComponentName(), p);
14225            if (DEBUG_SHOW_INFO) {
14226                Log.v(TAG, "  "
14227                        + (p.info.nonLocalizedLabel != null
14228                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14229                Log.v(TAG, "    Class=" + p.info.name);
14230            }
14231            final int NI = p.intents.size();
14232            int j;
14233            for (j = 0; j < NI; j++) {
14234                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14235                if (DEBUG_SHOW_INFO) {
14236                    Log.v(TAG, "    IntentFilter:");
14237                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14238                }
14239                if (!intent.debugCheck()) {
14240                    Log.w(TAG, "==> For Provider " + p.info.name);
14241                }
14242                addFilter(intent);
14243            }
14244        }
14245
14246        public final void removeProvider(PackageParser.Provider p) {
14247            mProviders.remove(p.getComponentName());
14248            if (DEBUG_SHOW_INFO) {
14249                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14250                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14251                Log.v(TAG, "    Class=" + p.info.name);
14252            }
14253            final int NI = p.intents.size();
14254            int j;
14255            for (j = 0; j < NI; j++) {
14256                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14257                if (DEBUG_SHOW_INFO) {
14258                    Log.v(TAG, "    IntentFilter:");
14259                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14260                }
14261                removeFilter(intent);
14262            }
14263        }
14264
14265        @Override
14266        protected boolean allowFilterResult(
14267                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14268            ProviderInfo filterPi = filter.provider.info;
14269            for (int i = dest.size() - 1; i >= 0; i--) {
14270                ProviderInfo destPi = dest.get(i).providerInfo;
14271                if (destPi.name == filterPi.name
14272                        && destPi.packageName == filterPi.packageName) {
14273                    return false;
14274                }
14275            }
14276            return true;
14277        }
14278
14279        @Override
14280        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14281            return new PackageParser.ProviderIntentInfo[size];
14282        }
14283
14284        @Override
14285        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14286            if (!sUserManager.exists(userId))
14287                return true;
14288            PackageParser.Package p = filter.provider.owner;
14289            if (p != null) {
14290                PackageSetting ps = (PackageSetting) p.mExtras;
14291                if (ps != null) {
14292                    // System apps are never considered stopped for purposes of
14293                    // filtering, because there may be no way for the user to
14294                    // actually re-launch them.
14295                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14296                            && ps.getStopped(userId);
14297                }
14298            }
14299            return false;
14300        }
14301
14302        @Override
14303        protected boolean isPackageForFilter(String packageName,
14304                PackageParser.ProviderIntentInfo info) {
14305            return packageName.equals(info.provider.owner.packageName);
14306        }
14307
14308        @Override
14309        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14310                int match, int userId) {
14311            if (!sUserManager.exists(userId))
14312                return null;
14313            final PackageParser.ProviderIntentInfo info = filter;
14314            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14315                return null;
14316            }
14317            final PackageParser.Provider provider = info.provider;
14318            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14319            if (ps == null) {
14320                return null;
14321            }
14322            final PackageUserState userState = ps.readUserState(userId);
14323            final boolean matchVisibleToInstantApp =
14324                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14325            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14326            // throw out filters that aren't visible to instant applications
14327            if (matchVisibleToInstantApp
14328                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14329                return null;
14330            }
14331            // throw out instant application filters if we're not explicitly requesting them
14332            if (!isInstantApp && userState.instantApp) {
14333                return null;
14334            }
14335            // throw out instant application filters if updates are available; will trigger
14336            // instant application resolution
14337            if (userState.instantApp && ps.isUpdateAvailable()) {
14338                return null;
14339            }
14340            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14341                    userState, userId);
14342            if (pi == null) {
14343                return null;
14344            }
14345            final ResolveInfo res = new ResolveInfo();
14346            res.providerInfo = pi;
14347            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14348                res.filter = filter;
14349            }
14350            res.priority = info.getPriority();
14351            res.preferredOrder = provider.owner.mPreferredOrder;
14352            res.match = match;
14353            res.isDefault = info.hasDefault;
14354            res.labelRes = info.labelRes;
14355            res.nonLocalizedLabel = info.nonLocalizedLabel;
14356            res.icon = info.icon;
14357            res.system = res.providerInfo.applicationInfo.isSystemApp();
14358            return res;
14359        }
14360
14361        @Override
14362        protected void sortResults(List<ResolveInfo> results) {
14363            Collections.sort(results, mResolvePrioritySorter);
14364        }
14365
14366        @Override
14367        protected void dumpFilter(PrintWriter out, String prefix,
14368                PackageParser.ProviderIntentInfo filter) {
14369            out.print(prefix);
14370            out.print(
14371                    Integer.toHexString(System.identityHashCode(filter.provider)));
14372            out.print(' ');
14373            filter.provider.printComponentShortName(out);
14374            out.print(" filter ");
14375            out.println(Integer.toHexString(System.identityHashCode(filter)));
14376        }
14377
14378        @Override
14379        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14380            return filter.provider;
14381        }
14382
14383        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14384            PackageParser.Provider provider = (PackageParser.Provider)label;
14385            out.print(prefix); out.print(
14386                    Integer.toHexString(System.identityHashCode(provider)));
14387                    out.print(' ');
14388                    provider.printComponentShortName(out);
14389            if (count > 1) {
14390                out.print(" ("); out.print(count); out.print(" filters)");
14391            }
14392            out.println();
14393        }
14394
14395        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14396                = new ArrayMap<ComponentName, PackageParser.Provider>();
14397        private int mFlags;
14398    }
14399
14400    static final class EphemeralIntentResolver
14401            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14402        /**
14403         * The result that has the highest defined order. Ordering applies on a
14404         * per-package basis. Mapping is from package name to Pair of order and
14405         * EphemeralResolveInfo.
14406         * <p>
14407         * NOTE: This is implemented as a field variable for convenience and efficiency.
14408         * By having a field variable, we're able to track filter ordering as soon as
14409         * a non-zero order is defined. Otherwise, multiple loops across the result set
14410         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14411         * this needs to be contained entirely within {@link #filterResults}.
14412         */
14413        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14414
14415        @Override
14416        protected AuxiliaryResolveInfo[] newArray(int size) {
14417            return new AuxiliaryResolveInfo[size];
14418        }
14419
14420        @Override
14421        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14422            return true;
14423        }
14424
14425        @Override
14426        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14427                int userId) {
14428            if (!sUserManager.exists(userId)) {
14429                return null;
14430            }
14431            final String packageName = responseObj.resolveInfo.getPackageName();
14432            final Integer order = responseObj.getOrder();
14433            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14434                    mOrderResult.get(packageName);
14435            // ordering is enabled and this item's order isn't high enough
14436            if (lastOrderResult != null && lastOrderResult.first >= order) {
14437                return null;
14438            }
14439            final InstantAppResolveInfo res = responseObj.resolveInfo;
14440            if (order > 0) {
14441                // non-zero order, enable ordering
14442                mOrderResult.put(packageName, new Pair<>(order, res));
14443            }
14444            return responseObj;
14445        }
14446
14447        @Override
14448        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14449            // only do work if ordering is enabled [most of the time it won't be]
14450            if (mOrderResult.size() == 0) {
14451                return;
14452            }
14453            int resultSize = results.size();
14454            for (int i = 0; i < resultSize; i++) {
14455                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14456                final String packageName = info.getPackageName();
14457                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14458                if (savedInfo == null) {
14459                    // package doesn't having ordering
14460                    continue;
14461                }
14462                if (savedInfo.second == info) {
14463                    // circled back to the highest ordered item; remove from order list
14464                    mOrderResult.remove(packageName);
14465                    if (mOrderResult.size() == 0) {
14466                        // no more ordered items
14467                        break;
14468                    }
14469                    continue;
14470                }
14471                // item has a worse order, remove it from the result list
14472                results.remove(i);
14473                resultSize--;
14474                i--;
14475            }
14476        }
14477    }
14478
14479    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14480            new Comparator<ResolveInfo>() {
14481        public int compare(ResolveInfo r1, ResolveInfo r2) {
14482            int v1 = r1.priority;
14483            int v2 = r2.priority;
14484            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14485            if (v1 != v2) {
14486                return (v1 > v2) ? -1 : 1;
14487            }
14488            v1 = r1.preferredOrder;
14489            v2 = r2.preferredOrder;
14490            if (v1 != v2) {
14491                return (v1 > v2) ? -1 : 1;
14492            }
14493            if (r1.isDefault != r2.isDefault) {
14494                return r1.isDefault ? -1 : 1;
14495            }
14496            v1 = r1.match;
14497            v2 = r2.match;
14498            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14499            if (v1 != v2) {
14500                return (v1 > v2) ? -1 : 1;
14501            }
14502            if (r1.system != r2.system) {
14503                return r1.system ? -1 : 1;
14504            }
14505            if (r1.activityInfo != null) {
14506                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14507            }
14508            if (r1.serviceInfo != null) {
14509                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14510            }
14511            if (r1.providerInfo != null) {
14512                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14513            }
14514            return 0;
14515        }
14516    };
14517
14518    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14519            new Comparator<ProviderInfo>() {
14520        public int compare(ProviderInfo p1, ProviderInfo p2) {
14521            final int v1 = p1.initOrder;
14522            final int v2 = p2.initOrder;
14523            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14524        }
14525    };
14526
14527    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14528            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14529            final int[] userIds) {
14530        mHandler.post(new Runnable() {
14531            @Override
14532            public void run() {
14533                try {
14534                    final IActivityManager am = ActivityManager.getService();
14535                    if (am == null) return;
14536                    final int[] resolvedUserIds;
14537                    if (userIds == null) {
14538                        resolvedUserIds = am.getRunningUserIds();
14539                    } else {
14540                        resolvedUserIds = userIds;
14541                    }
14542                    for (int id : resolvedUserIds) {
14543                        final Intent intent = new Intent(action,
14544                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14545                        if (extras != null) {
14546                            intent.putExtras(extras);
14547                        }
14548                        if (targetPkg != null) {
14549                            intent.setPackage(targetPkg);
14550                        }
14551                        // Modify the UID when posting to other users
14552                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14553                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14554                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14555                            intent.putExtra(Intent.EXTRA_UID, uid);
14556                        }
14557                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14558                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14559                        if (DEBUG_BROADCASTS) {
14560                            RuntimeException here = new RuntimeException("here");
14561                            here.fillInStackTrace();
14562                            Slog.d(TAG, "Sending to user " + id + ": "
14563                                    + intent.toShortString(false, true, false, false)
14564                                    + " " + intent.getExtras(), here);
14565                        }
14566                        am.broadcastIntent(null, intent, null, finishedReceiver,
14567                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14568                                null, finishedReceiver != null, false, id);
14569                    }
14570                } catch (RemoteException ex) {
14571                }
14572            }
14573        });
14574    }
14575
14576    /**
14577     * Check if the external storage media is available. This is true if there
14578     * is a mounted external storage medium or if the external storage is
14579     * emulated.
14580     */
14581    private boolean isExternalMediaAvailable() {
14582        return mMediaMounted || Environment.isExternalStorageEmulated();
14583    }
14584
14585    @Override
14586    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14587        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14588            return null;
14589        }
14590        // writer
14591        synchronized (mPackages) {
14592            if (!isExternalMediaAvailable()) {
14593                // If the external storage is no longer mounted at this point,
14594                // the caller may not have been able to delete all of this
14595                // packages files and can not delete any more.  Bail.
14596                return null;
14597            }
14598            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14599            if (lastPackage != null) {
14600                pkgs.remove(lastPackage);
14601            }
14602            if (pkgs.size() > 0) {
14603                return pkgs.get(0);
14604            }
14605        }
14606        return null;
14607    }
14608
14609    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14610        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14611                userId, andCode ? 1 : 0, packageName);
14612        if (mSystemReady) {
14613            msg.sendToTarget();
14614        } else {
14615            if (mPostSystemReadyMessages == null) {
14616                mPostSystemReadyMessages = new ArrayList<>();
14617            }
14618            mPostSystemReadyMessages.add(msg);
14619        }
14620    }
14621
14622    void startCleaningPackages() {
14623        // reader
14624        if (!isExternalMediaAvailable()) {
14625            return;
14626        }
14627        synchronized (mPackages) {
14628            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14629                return;
14630            }
14631        }
14632        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14633        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14634        IActivityManager am = ActivityManager.getService();
14635        if (am != null) {
14636            int dcsUid = -1;
14637            synchronized (mPackages) {
14638                if (!mDefaultContainerWhitelisted) {
14639                    mDefaultContainerWhitelisted = true;
14640                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14641                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14642                }
14643            }
14644            try {
14645                if (dcsUid > 0) {
14646                    am.backgroundWhitelistUid(dcsUid);
14647                }
14648                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14649                        UserHandle.USER_SYSTEM);
14650            } catch (RemoteException e) {
14651            }
14652        }
14653    }
14654
14655    @Override
14656    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14657            int installFlags, String installerPackageName, int userId) {
14658        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14659
14660        final int callingUid = Binder.getCallingUid();
14661        enforceCrossUserPermission(callingUid, userId,
14662                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14663
14664        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14665            try {
14666                if (observer != null) {
14667                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14668                }
14669            } catch (RemoteException re) {
14670            }
14671            return;
14672        }
14673
14674        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14675            installFlags |= PackageManager.INSTALL_FROM_ADB;
14676
14677        } else {
14678            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14679            // about installerPackageName.
14680
14681            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14682            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14683        }
14684
14685        UserHandle user;
14686        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14687            user = UserHandle.ALL;
14688        } else {
14689            user = new UserHandle(userId);
14690        }
14691
14692        // Only system components can circumvent runtime permissions when installing.
14693        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14694                && mContext.checkCallingOrSelfPermission(Manifest.permission
14695                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14696            throw new SecurityException("You need the "
14697                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14698                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14699        }
14700
14701        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14702                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14703            throw new IllegalArgumentException(
14704                    "New installs into ASEC containers no longer supported");
14705        }
14706
14707        final File originFile = new File(originPath);
14708        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14709
14710        final Message msg = mHandler.obtainMessage(INIT_COPY);
14711        final VerificationInfo verificationInfo = new VerificationInfo(
14712                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14713        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14714                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14715                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14716                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14717        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14718        msg.obj = params;
14719
14720        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14721                System.identityHashCode(msg.obj));
14722        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14723                System.identityHashCode(msg.obj));
14724
14725        mHandler.sendMessage(msg);
14726    }
14727
14728
14729    /**
14730     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14731     * it is acting on behalf on an enterprise or the user).
14732     *
14733     * Note that the ordering of the conditionals in this method is important. The checks we perform
14734     * are as follows, in this order:
14735     *
14736     * 1) If the install is being performed by a system app, we can trust the app to have set the
14737     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14738     *    what it is.
14739     * 2) If the install is being performed by a device or profile owner app, the install reason
14740     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14741     *    set the install reason correctly. If the app targets an older SDK version where install
14742     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14743     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14744     * 3) In all other cases, the install is being performed by a regular app that is neither part
14745     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14746     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14747     *    set to enterprise policy and if so, change it to unknown instead.
14748     */
14749    private int fixUpInstallReason(String installerPackageName, int installerUid,
14750            int installReason) {
14751        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14752                == PERMISSION_GRANTED) {
14753            // If the install is being performed by a system app, we trust that app to have set the
14754            // install reason correctly.
14755            return installReason;
14756        }
14757
14758        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14759            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14760        if (dpm != null) {
14761            ComponentName owner = null;
14762            try {
14763                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14764                if (owner == null) {
14765                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14766                }
14767            } catch (RemoteException e) {
14768            }
14769            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14770                // If the install is being performed by a device or profile owner, the install
14771                // reason should be enterprise policy.
14772                return PackageManager.INSTALL_REASON_POLICY;
14773            }
14774        }
14775
14776        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14777            // If the install is being performed by a regular app (i.e. neither system app nor
14778            // device or profile owner), we have no reason to believe that the app is acting on
14779            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14780            // change it to unknown instead.
14781            return PackageManager.INSTALL_REASON_UNKNOWN;
14782        }
14783
14784        // If the install is being performed by a regular app and the install reason was set to any
14785        // value but enterprise policy, leave the install reason unchanged.
14786        return installReason;
14787    }
14788
14789    void installStage(String packageName, File stagedDir, String stagedCid,
14790            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14791            String installerPackageName, int installerUid, UserHandle user,
14792            Certificate[][] certificates) {
14793        if (DEBUG_EPHEMERAL) {
14794            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14795                Slog.d(TAG, "Ephemeral install of " + packageName);
14796            }
14797        }
14798        final VerificationInfo verificationInfo = new VerificationInfo(
14799                sessionParams.originatingUri, sessionParams.referrerUri,
14800                sessionParams.originatingUid, installerUid);
14801
14802        final OriginInfo origin;
14803        if (stagedDir != null) {
14804            origin = OriginInfo.fromStagedFile(stagedDir);
14805        } else {
14806            origin = OriginInfo.fromStagedContainer(stagedCid);
14807        }
14808
14809        final Message msg = mHandler.obtainMessage(INIT_COPY);
14810        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14811                sessionParams.installReason);
14812        final InstallParams params = new InstallParams(origin, null, observer,
14813                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14814                verificationInfo, user, sessionParams.abiOverride,
14815                sessionParams.grantedRuntimePermissions, certificates, installReason);
14816        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14817        msg.obj = params;
14818
14819        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14820                System.identityHashCode(msg.obj));
14821        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14822                System.identityHashCode(msg.obj));
14823
14824        mHandler.sendMessage(msg);
14825    }
14826
14827    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14828            int userId) {
14829        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14830        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14831                false /*startReceiver*/, pkgSetting.appId, userId);
14832
14833        // Send a session commit broadcast
14834        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14835        info.installReason = pkgSetting.getInstallReason(userId);
14836        info.appPackageName = packageName;
14837        sendSessionCommitBroadcast(info, userId);
14838    }
14839
14840    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14841            boolean includeStopped, int appId, int... userIds) {
14842        if (ArrayUtils.isEmpty(userIds)) {
14843            return;
14844        }
14845        Bundle extras = new Bundle(1);
14846        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14847        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14848
14849        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14850                packageName, extras, 0, null, null, userIds);
14851        if (sendBootCompleted) {
14852            mHandler.post(() -> {
14853                        for (int userId : userIds) {
14854                            sendBootCompletedBroadcastToSystemApp(
14855                                    packageName, includeStopped, userId);
14856                        }
14857                    }
14858            );
14859        }
14860    }
14861
14862    /**
14863     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14864     * automatically without needing an explicit launch.
14865     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14866     */
14867    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14868            int userId) {
14869        // If user is not running, the app didn't miss any broadcast
14870        if (!mUserManagerInternal.isUserRunning(userId)) {
14871            return;
14872        }
14873        final IActivityManager am = ActivityManager.getService();
14874        try {
14875            // Deliver LOCKED_BOOT_COMPLETED first
14876            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14877                    .setPackage(packageName);
14878            if (includeStopped) {
14879                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14880            }
14881            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14882            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14883                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14884
14885            // Deliver BOOT_COMPLETED only if user is unlocked
14886            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14887                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14888                if (includeStopped) {
14889                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14890                }
14891                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14892                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14893            }
14894        } catch (RemoteException e) {
14895            throw e.rethrowFromSystemServer();
14896        }
14897    }
14898
14899    @Override
14900    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14901            int userId) {
14902        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14903        PackageSetting pkgSetting;
14904        final int callingUid = Binder.getCallingUid();
14905        enforceCrossUserPermission(callingUid, userId,
14906                true /* requireFullPermission */, true /* checkShell */,
14907                "setApplicationHiddenSetting for user " + userId);
14908
14909        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14910            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14911            return false;
14912        }
14913
14914        long callingId = Binder.clearCallingIdentity();
14915        try {
14916            boolean sendAdded = false;
14917            boolean sendRemoved = false;
14918            // writer
14919            synchronized (mPackages) {
14920                pkgSetting = mSettings.mPackages.get(packageName);
14921                if (pkgSetting == null) {
14922                    return false;
14923                }
14924                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14925                    return false;
14926                }
14927                // Do not allow "android" is being disabled
14928                if ("android".equals(packageName)) {
14929                    Slog.w(TAG, "Cannot hide package: android");
14930                    return false;
14931                }
14932                // Cannot hide static shared libs as they are considered
14933                // a part of the using app (emulating static linking). Also
14934                // static libs are installed always on internal storage.
14935                PackageParser.Package pkg = mPackages.get(packageName);
14936                if (pkg != null && pkg.staticSharedLibName != null) {
14937                    Slog.w(TAG, "Cannot hide package: " + packageName
14938                            + " providing static shared library: "
14939                            + pkg.staticSharedLibName);
14940                    return false;
14941                }
14942                // Only allow protected packages to hide themselves.
14943                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14944                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14945                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14946                    return false;
14947                }
14948
14949                if (pkgSetting.getHidden(userId) != hidden) {
14950                    pkgSetting.setHidden(hidden, userId);
14951                    mSettings.writePackageRestrictionsLPr(userId);
14952                    if (hidden) {
14953                        sendRemoved = true;
14954                    } else {
14955                        sendAdded = true;
14956                    }
14957                }
14958            }
14959            if (sendAdded) {
14960                sendPackageAddedForUser(packageName, pkgSetting, userId);
14961                return true;
14962            }
14963            if (sendRemoved) {
14964                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14965                        "hiding pkg");
14966                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14967                return true;
14968            }
14969        } finally {
14970            Binder.restoreCallingIdentity(callingId);
14971        }
14972        return false;
14973    }
14974
14975    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14976            int userId) {
14977        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14978        info.removedPackage = packageName;
14979        info.installerPackageName = pkgSetting.installerPackageName;
14980        info.removedUsers = new int[] {userId};
14981        info.broadcastUsers = new int[] {userId};
14982        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14983        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14984    }
14985
14986    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14987        if (pkgList.length > 0) {
14988            Bundle extras = new Bundle(1);
14989            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14990
14991            sendPackageBroadcast(
14992                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14993                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14994                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14995                    new int[] {userId});
14996        }
14997    }
14998
14999    /**
15000     * Returns true if application is not found or there was an error. Otherwise it returns
15001     * the hidden state of the package for the given user.
15002     */
15003    @Override
15004    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
15005        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15006        final int callingUid = Binder.getCallingUid();
15007        enforceCrossUserPermission(callingUid, userId,
15008                true /* requireFullPermission */, false /* checkShell */,
15009                "getApplicationHidden for user " + userId);
15010        PackageSetting ps;
15011        long callingId = Binder.clearCallingIdentity();
15012        try {
15013            // writer
15014            synchronized (mPackages) {
15015                ps = mSettings.mPackages.get(packageName);
15016                if (ps == null) {
15017                    return true;
15018                }
15019                if (filterAppAccessLPr(ps, callingUid, userId)) {
15020                    return true;
15021                }
15022                return ps.getHidden(userId);
15023            }
15024        } finally {
15025            Binder.restoreCallingIdentity(callingId);
15026        }
15027    }
15028
15029    /**
15030     * @hide
15031     */
15032    @Override
15033    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15034            int installReason) {
15035        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15036                null);
15037        PackageSetting pkgSetting;
15038        final int callingUid = Binder.getCallingUid();
15039        enforceCrossUserPermission(callingUid, userId,
15040                true /* requireFullPermission */, true /* checkShell */,
15041                "installExistingPackage for user " + userId);
15042        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15043            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15044        }
15045
15046        long callingId = Binder.clearCallingIdentity();
15047        try {
15048            boolean installed = false;
15049            final boolean instantApp =
15050                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15051            final boolean fullApp =
15052                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15053
15054            // writer
15055            synchronized (mPackages) {
15056                pkgSetting = mSettings.mPackages.get(packageName);
15057                if (pkgSetting == null) {
15058                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15059                }
15060                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15061                    // only allow the existing package to be used if it's installed as a full
15062                    // application for at least one user
15063                    boolean installAllowed = false;
15064                    for (int checkUserId : sUserManager.getUserIds()) {
15065                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15066                        if (installAllowed) {
15067                            break;
15068                        }
15069                    }
15070                    if (!installAllowed) {
15071                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15072                    }
15073                }
15074                if (!pkgSetting.getInstalled(userId)) {
15075                    pkgSetting.setInstalled(true, userId);
15076                    pkgSetting.setHidden(false, userId);
15077                    pkgSetting.setInstallReason(installReason, userId);
15078                    mSettings.writePackageRestrictionsLPr(userId);
15079                    mSettings.writeKernelMappingLPr(pkgSetting);
15080                    installed = true;
15081                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15082                    // upgrade app from instant to full; we don't allow app downgrade
15083                    installed = true;
15084                }
15085                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15086            }
15087
15088            if (installed) {
15089                if (pkgSetting.pkg != null) {
15090                    synchronized (mInstallLock) {
15091                        // We don't need to freeze for a brand new install
15092                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15093                    }
15094                }
15095                sendPackageAddedForUser(packageName, pkgSetting, userId);
15096                synchronized (mPackages) {
15097                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15098                }
15099            }
15100        } finally {
15101            Binder.restoreCallingIdentity(callingId);
15102        }
15103
15104        return PackageManager.INSTALL_SUCCEEDED;
15105    }
15106
15107    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15108            boolean instantApp, boolean fullApp) {
15109        // no state specified; do nothing
15110        if (!instantApp && !fullApp) {
15111            return;
15112        }
15113        if (userId != UserHandle.USER_ALL) {
15114            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15115                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15116            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15117                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15118            }
15119        } else {
15120            for (int currentUserId : sUserManager.getUserIds()) {
15121                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15122                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15123                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15124                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15125                }
15126            }
15127        }
15128    }
15129
15130    boolean isUserRestricted(int userId, String restrictionKey) {
15131        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15132        if (restrictions.getBoolean(restrictionKey, false)) {
15133            Log.w(TAG, "User is restricted: " + restrictionKey);
15134            return true;
15135        }
15136        return false;
15137    }
15138
15139    @Override
15140    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15141            int userId) {
15142        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15143        final int callingUid = Binder.getCallingUid();
15144        enforceCrossUserPermission(callingUid, userId,
15145                true /* requireFullPermission */, true /* checkShell */,
15146                "setPackagesSuspended for user " + userId);
15147
15148        if (ArrayUtils.isEmpty(packageNames)) {
15149            return packageNames;
15150        }
15151
15152        // List of package names for whom the suspended state has changed.
15153        List<String> changedPackages = new ArrayList<>(packageNames.length);
15154        // List of package names for whom the suspended state is not set as requested in this
15155        // method.
15156        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15157        long callingId = Binder.clearCallingIdentity();
15158        try {
15159            for (int i = 0; i < packageNames.length; i++) {
15160                String packageName = packageNames[i];
15161                boolean changed = false;
15162                final int appId;
15163                synchronized (mPackages) {
15164                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15165                    if (pkgSetting == null
15166                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15167                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15168                                + "\". Skipping suspending/un-suspending.");
15169                        unactionedPackages.add(packageName);
15170                        continue;
15171                    }
15172                    appId = pkgSetting.appId;
15173                    if (pkgSetting.getSuspended(userId) != suspended) {
15174                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15175                            unactionedPackages.add(packageName);
15176                            continue;
15177                        }
15178                        pkgSetting.setSuspended(suspended, userId);
15179                        mSettings.writePackageRestrictionsLPr(userId);
15180                        changed = true;
15181                        changedPackages.add(packageName);
15182                    }
15183                }
15184
15185                if (changed && suspended) {
15186                    killApplication(packageName, UserHandle.getUid(userId, appId),
15187                            "suspending package");
15188                }
15189            }
15190        } finally {
15191            Binder.restoreCallingIdentity(callingId);
15192        }
15193
15194        if (!changedPackages.isEmpty()) {
15195            sendPackagesSuspendedForUser(changedPackages.toArray(
15196                    new String[changedPackages.size()]), userId, suspended);
15197        }
15198
15199        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15200    }
15201
15202    @Override
15203    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15204        final int callingUid = Binder.getCallingUid();
15205        enforceCrossUserPermission(callingUid, userId,
15206                true /* requireFullPermission */, false /* checkShell */,
15207                "isPackageSuspendedForUser for user " + userId);
15208        synchronized (mPackages) {
15209            final PackageSetting ps = mSettings.mPackages.get(packageName);
15210            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15211                throw new IllegalArgumentException("Unknown target package: " + packageName);
15212            }
15213            return ps.getSuspended(userId);
15214        }
15215    }
15216
15217    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15218        if (isPackageDeviceAdmin(packageName, userId)) {
15219            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15220                    + "\": has an active device admin");
15221            return false;
15222        }
15223
15224        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15225        if (packageName.equals(activeLauncherPackageName)) {
15226            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15227                    + "\": contains the active launcher");
15228            return false;
15229        }
15230
15231        if (packageName.equals(mRequiredInstallerPackage)) {
15232            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15233                    + "\": required for package installation");
15234            return false;
15235        }
15236
15237        if (packageName.equals(mRequiredUninstallerPackage)) {
15238            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15239                    + "\": required for package uninstallation");
15240            return false;
15241        }
15242
15243        if (packageName.equals(mRequiredVerifierPackage)) {
15244            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15245                    + "\": required for package verification");
15246            return false;
15247        }
15248
15249        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15250            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15251                    + "\": is the default dialer");
15252            return false;
15253        }
15254
15255        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15256            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15257                    + "\": protected package");
15258            return false;
15259        }
15260
15261        // Cannot suspend static shared libs as they are considered
15262        // a part of the using app (emulating static linking). Also
15263        // static libs are installed always on internal storage.
15264        PackageParser.Package pkg = mPackages.get(packageName);
15265        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15266            Slog.w(TAG, "Cannot suspend package: " + packageName
15267                    + " providing static shared library: "
15268                    + pkg.staticSharedLibName);
15269            return false;
15270        }
15271
15272        return true;
15273    }
15274
15275    private String getActiveLauncherPackageName(int userId) {
15276        Intent intent = new Intent(Intent.ACTION_MAIN);
15277        intent.addCategory(Intent.CATEGORY_HOME);
15278        ResolveInfo resolveInfo = resolveIntent(
15279                intent,
15280                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15281                PackageManager.MATCH_DEFAULT_ONLY,
15282                userId);
15283
15284        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15285    }
15286
15287    private String getDefaultDialerPackageName(int userId) {
15288        synchronized (mPackages) {
15289            return mSettings.getDefaultDialerPackageNameLPw(userId);
15290        }
15291    }
15292
15293    @Override
15294    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15295        mContext.enforceCallingOrSelfPermission(
15296                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15297                "Only package verification agents can verify applications");
15298
15299        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15300        final PackageVerificationResponse response = new PackageVerificationResponse(
15301                verificationCode, Binder.getCallingUid());
15302        msg.arg1 = id;
15303        msg.obj = response;
15304        mHandler.sendMessage(msg);
15305    }
15306
15307    @Override
15308    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15309            long millisecondsToDelay) {
15310        mContext.enforceCallingOrSelfPermission(
15311                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15312                "Only package verification agents can extend verification timeouts");
15313
15314        final PackageVerificationState state = mPendingVerification.get(id);
15315        final PackageVerificationResponse response = new PackageVerificationResponse(
15316                verificationCodeAtTimeout, Binder.getCallingUid());
15317
15318        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15319            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15320        }
15321        if (millisecondsToDelay < 0) {
15322            millisecondsToDelay = 0;
15323        }
15324        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15325                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15326            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15327        }
15328
15329        if ((state != null) && !state.timeoutExtended()) {
15330            state.extendTimeout();
15331
15332            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15333            msg.arg1 = id;
15334            msg.obj = response;
15335            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15336        }
15337    }
15338
15339    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15340            int verificationCode, UserHandle user) {
15341        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15342        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15343        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15344        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15345        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15346
15347        mContext.sendBroadcastAsUser(intent, user,
15348                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15349    }
15350
15351    private ComponentName matchComponentForVerifier(String packageName,
15352            List<ResolveInfo> receivers) {
15353        ActivityInfo targetReceiver = null;
15354
15355        final int NR = receivers.size();
15356        for (int i = 0; i < NR; i++) {
15357            final ResolveInfo info = receivers.get(i);
15358            if (info.activityInfo == null) {
15359                continue;
15360            }
15361
15362            if (packageName.equals(info.activityInfo.packageName)) {
15363                targetReceiver = info.activityInfo;
15364                break;
15365            }
15366        }
15367
15368        if (targetReceiver == null) {
15369            return null;
15370        }
15371
15372        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15373    }
15374
15375    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15376            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15377        if (pkgInfo.verifiers.length == 0) {
15378            return null;
15379        }
15380
15381        final int N = pkgInfo.verifiers.length;
15382        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15383        for (int i = 0; i < N; i++) {
15384            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15385
15386            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15387                    receivers);
15388            if (comp == null) {
15389                continue;
15390            }
15391
15392            final int verifierUid = getUidForVerifier(verifierInfo);
15393            if (verifierUid == -1) {
15394                continue;
15395            }
15396
15397            if (DEBUG_VERIFY) {
15398                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15399                        + " with the correct signature");
15400            }
15401            sufficientVerifiers.add(comp);
15402            verificationState.addSufficientVerifier(verifierUid);
15403        }
15404
15405        return sufficientVerifiers;
15406    }
15407
15408    private int getUidForVerifier(VerifierInfo verifierInfo) {
15409        synchronized (mPackages) {
15410            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15411            if (pkg == null) {
15412                return -1;
15413            } else if (pkg.mSignatures.length != 1) {
15414                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15415                        + " has more than one signature; ignoring");
15416                return -1;
15417            }
15418
15419            /*
15420             * If the public key of the package's signature does not match
15421             * our expected public key, then this is a different package and
15422             * we should skip.
15423             */
15424
15425            final byte[] expectedPublicKey;
15426            try {
15427                final Signature verifierSig = pkg.mSignatures[0];
15428                final PublicKey publicKey = verifierSig.getPublicKey();
15429                expectedPublicKey = publicKey.getEncoded();
15430            } catch (CertificateException e) {
15431                return -1;
15432            }
15433
15434            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15435
15436            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15437                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15438                        + " does not have the expected public key; ignoring");
15439                return -1;
15440            }
15441
15442            return pkg.applicationInfo.uid;
15443        }
15444    }
15445
15446    @Override
15447    public void finishPackageInstall(int token, boolean didLaunch) {
15448        enforceSystemOrRoot("Only the system is allowed to finish installs");
15449
15450        if (DEBUG_INSTALL) {
15451            Slog.v(TAG, "BM finishing package install for " + token);
15452        }
15453        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15454
15455        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15456        mHandler.sendMessage(msg);
15457    }
15458
15459    /**
15460     * Get the verification agent timeout.  Used for both the APK verifier and the
15461     * intent filter verifier.
15462     *
15463     * @return verification timeout in milliseconds
15464     */
15465    private long getVerificationTimeout() {
15466        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15467                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15468                DEFAULT_VERIFICATION_TIMEOUT);
15469    }
15470
15471    /**
15472     * Get the default verification agent response code.
15473     *
15474     * @return default verification response code
15475     */
15476    private int getDefaultVerificationResponse(UserHandle user) {
15477        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15478            return PackageManager.VERIFICATION_REJECT;
15479        }
15480        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15481                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15482                DEFAULT_VERIFICATION_RESPONSE);
15483    }
15484
15485    /**
15486     * Check whether or not package verification has been enabled.
15487     *
15488     * @return true if verification should be performed
15489     */
15490    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15491        if (!DEFAULT_VERIFY_ENABLE) {
15492            return false;
15493        }
15494
15495        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15496
15497        // Check if installing from ADB
15498        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15499            // Do not run verification in a test harness environment
15500            if (ActivityManager.isRunningInTestHarness()) {
15501                return false;
15502            }
15503            if (ensureVerifyAppsEnabled) {
15504                return true;
15505            }
15506            // Check if the developer does not want package verification for ADB installs
15507            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15508                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15509                return false;
15510            }
15511        } else {
15512            // only when not installed from ADB, skip verification for instant apps when
15513            // the installer and verifier are the same.
15514            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15515                if (mInstantAppInstallerActivity != null
15516                        && mInstantAppInstallerActivity.packageName.equals(
15517                                mRequiredVerifierPackage)) {
15518                    try {
15519                        mContext.getSystemService(AppOpsManager.class)
15520                                .checkPackage(installerUid, mRequiredVerifierPackage);
15521                        if (DEBUG_VERIFY) {
15522                            Slog.i(TAG, "disable verification for instant app");
15523                        }
15524                        return false;
15525                    } catch (SecurityException ignore) { }
15526                }
15527            }
15528        }
15529
15530        if (ensureVerifyAppsEnabled) {
15531            return true;
15532        }
15533
15534        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15535                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15536    }
15537
15538    @Override
15539    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15540            throws RemoteException {
15541        mContext.enforceCallingOrSelfPermission(
15542                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15543                "Only intentfilter verification agents can verify applications");
15544
15545        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15546        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15547                Binder.getCallingUid(), verificationCode, failedDomains);
15548        msg.arg1 = id;
15549        msg.obj = response;
15550        mHandler.sendMessage(msg);
15551    }
15552
15553    @Override
15554    public int getIntentVerificationStatus(String packageName, int userId) {
15555        final int callingUid = Binder.getCallingUid();
15556        if (UserHandle.getUserId(callingUid) != userId) {
15557            mContext.enforceCallingOrSelfPermission(
15558                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15559                    "getIntentVerificationStatus" + userId);
15560        }
15561        if (getInstantAppPackageName(callingUid) != null) {
15562            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15563        }
15564        synchronized (mPackages) {
15565            final PackageSetting ps = mSettings.mPackages.get(packageName);
15566            if (ps == null
15567                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15568                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15569            }
15570            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15571        }
15572    }
15573
15574    @Override
15575    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15576        mContext.enforceCallingOrSelfPermission(
15577                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15578
15579        boolean result = false;
15580        synchronized (mPackages) {
15581            final PackageSetting ps = mSettings.mPackages.get(packageName);
15582            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15583                return false;
15584            }
15585            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15586        }
15587        if (result) {
15588            scheduleWritePackageRestrictionsLocked(userId);
15589        }
15590        return result;
15591    }
15592
15593    @Override
15594    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15595            String packageName) {
15596        final int callingUid = Binder.getCallingUid();
15597        if (getInstantAppPackageName(callingUid) != null) {
15598            return ParceledListSlice.emptyList();
15599        }
15600        synchronized (mPackages) {
15601            final PackageSetting ps = mSettings.mPackages.get(packageName);
15602            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15603                return ParceledListSlice.emptyList();
15604            }
15605            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15606        }
15607    }
15608
15609    @Override
15610    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15611        if (TextUtils.isEmpty(packageName)) {
15612            return ParceledListSlice.emptyList();
15613        }
15614        final int callingUid = Binder.getCallingUid();
15615        final int callingUserId = UserHandle.getUserId(callingUid);
15616        synchronized (mPackages) {
15617            PackageParser.Package pkg = mPackages.get(packageName);
15618            if (pkg == null || pkg.activities == null) {
15619                return ParceledListSlice.emptyList();
15620            }
15621            if (pkg.mExtras == null) {
15622                return ParceledListSlice.emptyList();
15623            }
15624            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15625            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15626                return ParceledListSlice.emptyList();
15627            }
15628            final int count = pkg.activities.size();
15629            ArrayList<IntentFilter> result = new ArrayList<>();
15630            for (int n=0; n<count; n++) {
15631                PackageParser.Activity activity = pkg.activities.get(n);
15632                if (activity.intents != null && activity.intents.size() > 0) {
15633                    result.addAll(activity.intents);
15634                }
15635            }
15636            return new ParceledListSlice<>(result);
15637        }
15638    }
15639
15640    @Override
15641    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15642        mContext.enforceCallingOrSelfPermission(
15643                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15644        if (UserHandle.getCallingUserId() != userId) {
15645            mContext.enforceCallingOrSelfPermission(
15646                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15647        }
15648
15649        synchronized (mPackages) {
15650            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15651            if (packageName != null) {
15652                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15653                        packageName, userId);
15654            }
15655            return result;
15656        }
15657    }
15658
15659    @Override
15660    public String getDefaultBrowserPackageName(int userId) {
15661        if (UserHandle.getCallingUserId() != userId) {
15662            mContext.enforceCallingOrSelfPermission(
15663                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15664        }
15665        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15666            return null;
15667        }
15668        synchronized (mPackages) {
15669            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15670        }
15671    }
15672
15673    /**
15674     * Get the "allow unknown sources" setting.
15675     *
15676     * @return the current "allow unknown sources" setting
15677     */
15678    private int getUnknownSourcesSettings() {
15679        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15680                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15681                -1);
15682    }
15683
15684    @Override
15685    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15686        final int callingUid = Binder.getCallingUid();
15687        if (getInstantAppPackageName(callingUid) != null) {
15688            return;
15689        }
15690        // writer
15691        synchronized (mPackages) {
15692            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15693            if (targetPackageSetting == null
15694                    || filterAppAccessLPr(
15695                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15696                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15697            }
15698
15699            PackageSetting installerPackageSetting;
15700            if (installerPackageName != null) {
15701                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15702                if (installerPackageSetting == null) {
15703                    throw new IllegalArgumentException("Unknown installer package: "
15704                            + installerPackageName);
15705                }
15706            } else {
15707                installerPackageSetting = null;
15708            }
15709
15710            Signature[] callerSignature;
15711            Object obj = mSettings.getUserIdLPr(callingUid);
15712            if (obj != null) {
15713                if (obj instanceof SharedUserSetting) {
15714                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15715                } else if (obj instanceof PackageSetting) {
15716                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15717                } else {
15718                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15719                }
15720            } else {
15721                throw new SecurityException("Unknown calling UID: " + callingUid);
15722            }
15723
15724            // Verify: can't set installerPackageName to a package that is
15725            // not signed with the same cert as the caller.
15726            if (installerPackageSetting != null) {
15727                if (compareSignatures(callerSignature,
15728                        installerPackageSetting.signatures.mSignatures)
15729                        != PackageManager.SIGNATURE_MATCH) {
15730                    throw new SecurityException(
15731                            "Caller does not have same cert as new installer package "
15732                            + installerPackageName);
15733                }
15734            }
15735
15736            // Verify: if target already has an installer package, it must
15737            // be signed with the same cert as the caller.
15738            if (targetPackageSetting.installerPackageName != null) {
15739                PackageSetting setting = mSettings.mPackages.get(
15740                        targetPackageSetting.installerPackageName);
15741                // If the currently set package isn't valid, then it's always
15742                // okay to change it.
15743                if (setting != null) {
15744                    if (compareSignatures(callerSignature,
15745                            setting.signatures.mSignatures)
15746                            != PackageManager.SIGNATURE_MATCH) {
15747                        throw new SecurityException(
15748                                "Caller does not have same cert as old installer package "
15749                                + targetPackageSetting.installerPackageName);
15750                    }
15751                }
15752            }
15753
15754            // Okay!
15755            targetPackageSetting.installerPackageName = installerPackageName;
15756            if (installerPackageName != null) {
15757                mSettings.mInstallerPackages.add(installerPackageName);
15758            }
15759            scheduleWriteSettingsLocked();
15760        }
15761    }
15762
15763    @Override
15764    public void setApplicationCategoryHint(String packageName, int categoryHint,
15765            String callerPackageName) {
15766        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15767            throw new SecurityException("Instant applications don't have access to this method");
15768        }
15769        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15770                callerPackageName);
15771        synchronized (mPackages) {
15772            PackageSetting ps = mSettings.mPackages.get(packageName);
15773            if (ps == null) {
15774                throw new IllegalArgumentException("Unknown target package " + packageName);
15775            }
15776            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15777                throw new IllegalArgumentException("Unknown target package " + packageName);
15778            }
15779            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15780                throw new IllegalArgumentException("Calling package " + callerPackageName
15781                        + " is not installer for " + packageName);
15782            }
15783
15784            if (ps.categoryHint != categoryHint) {
15785                ps.categoryHint = categoryHint;
15786                scheduleWriteSettingsLocked();
15787            }
15788        }
15789    }
15790
15791    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15792        // Queue up an async operation since the package installation may take a little while.
15793        mHandler.post(new Runnable() {
15794            public void run() {
15795                mHandler.removeCallbacks(this);
15796                 // Result object to be returned
15797                PackageInstalledInfo res = new PackageInstalledInfo();
15798                res.setReturnCode(currentStatus);
15799                res.uid = -1;
15800                res.pkg = null;
15801                res.removedInfo = null;
15802                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15803                    args.doPreInstall(res.returnCode);
15804                    synchronized (mInstallLock) {
15805                        installPackageTracedLI(args, res);
15806                    }
15807                    args.doPostInstall(res.returnCode, res.uid);
15808                }
15809
15810                // A restore should be performed at this point if (a) the install
15811                // succeeded, (b) the operation is not an update, and (c) the new
15812                // package has not opted out of backup participation.
15813                final boolean update = res.removedInfo != null
15814                        && res.removedInfo.removedPackage != null;
15815                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15816                boolean doRestore = !update
15817                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15818
15819                // Set up the post-install work request bookkeeping.  This will be used
15820                // and cleaned up by the post-install event handling regardless of whether
15821                // there's a restore pass performed.  Token values are >= 1.
15822                int token;
15823                if (mNextInstallToken < 0) mNextInstallToken = 1;
15824                token = mNextInstallToken++;
15825
15826                PostInstallData data = new PostInstallData(args, res);
15827                mRunningInstalls.put(token, data);
15828                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15829
15830                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15831                    // Pass responsibility to the Backup Manager.  It will perform a
15832                    // restore if appropriate, then pass responsibility back to the
15833                    // Package Manager to run the post-install observer callbacks
15834                    // and broadcasts.
15835                    IBackupManager bm = IBackupManager.Stub.asInterface(
15836                            ServiceManager.getService(Context.BACKUP_SERVICE));
15837                    if (bm != null) {
15838                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15839                                + " to BM for possible restore");
15840                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15841                        try {
15842                            // TODO: http://b/22388012
15843                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15844                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15845                            } else {
15846                                doRestore = false;
15847                            }
15848                        } catch (RemoteException e) {
15849                            // can't happen; the backup manager is local
15850                        } catch (Exception e) {
15851                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15852                            doRestore = false;
15853                        }
15854                    } else {
15855                        Slog.e(TAG, "Backup Manager not found!");
15856                        doRestore = false;
15857                    }
15858                }
15859
15860                if (!doRestore) {
15861                    // No restore possible, or the Backup Manager was mysteriously not
15862                    // available -- just fire the post-install work request directly.
15863                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15864
15865                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15866
15867                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15868                    mHandler.sendMessage(msg);
15869                }
15870            }
15871        });
15872    }
15873
15874    /**
15875     * Callback from PackageSettings whenever an app is first transitioned out of the
15876     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15877     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15878     * here whether the app is the target of an ongoing install, and only send the
15879     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15880     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15881     * handling.
15882     */
15883    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15884        // Serialize this with the rest of the install-process message chain.  In the
15885        // restore-at-install case, this Runnable will necessarily run before the
15886        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15887        // are coherent.  In the non-restore case, the app has already completed install
15888        // and been launched through some other means, so it is not in a problematic
15889        // state for observers to see the FIRST_LAUNCH signal.
15890        mHandler.post(new Runnable() {
15891            @Override
15892            public void run() {
15893                for (int i = 0; i < mRunningInstalls.size(); i++) {
15894                    final PostInstallData data = mRunningInstalls.valueAt(i);
15895                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15896                        continue;
15897                    }
15898                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15899                        // right package; but is it for the right user?
15900                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15901                            if (userId == data.res.newUsers[uIndex]) {
15902                                if (DEBUG_BACKUP) {
15903                                    Slog.i(TAG, "Package " + pkgName
15904                                            + " being restored so deferring FIRST_LAUNCH");
15905                                }
15906                                return;
15907                            }
15908                        }
15909                    }
15910                }
15911                // didn't find it, so not being restored
15912                if (DEBUG_BACKUP) {
15913                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15914                }
15915                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15916            }
15917        });
15918    }
15919
15920    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15921        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15922                installerPkg, null, userIds);
15923    }
15924
15925    private abstract class HandlerParams {
15926        private static final int MAX_RETRIES = 4;
15927
15928        /**
15929         * Number of times startCopy() has been attempted and had a non-fatal
15930         * error.
15931         */
15932        private int mRetries = 0;
15933
15934        /** User handle for the user requesting the information or installation. */
15935        private final UserHandle mUser;
15936        String traceMethod;
15937        int traceCookie;
15938
15939        HandlerParams(UserHandle user) {
15940            mUser = user;
15941        }
15942
15943        UserHandle getUser() {
15944            return mUser;
15945        }
15946
15947        HandlerParams setTraceMethod(String traceMethod) {
15948            this.traceMethod = traceMethod;
15949            return this;
15950        }
15951
15952        HandlerParams setTraceCookie(int traceCookie) {
15953            this.traceCookie = traceCookie;
15954            return this;
15955        }
15956
15957        final boolean startCopy() {
15958            boolean res;
15959            try {
15960                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15961
15962                if (++mRetries > MAX_RETRIES) {
15963                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15964                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15965                    handleServiceError();
15966                    return false;
15967                } else {
15968                    handleStartCopy();
15969                    res = true;
15970                }
15971            } catch (RemoteException e) {
15972                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15973                mHandler.sendEmptyMessage(MCS_RECONNECT);
15974                res = false;
15975            }
15976            handleReturnCode();
15977            return res;
15978        }
15979
15980        final void serviceError() {
15981            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15982            handleServiceError();
15983            handleReturnCode();
15984        }
15985
15986        abstract void handleStartCopy() throws RemoteException;
15987        abstract void handleServiceError();
15988        abstract void handleReturnCode();
15989    }
15990
15991    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15992        for (File path : paths) {
15993            try {
15994                mcs.clearDirectory(path.getAbsolutePath());
15995            } catch (RemoteException e) {
15996            }
15997        }
15998    }
15999
16000    static class OriginInfo {
16001        /**
16002         * Location where install is coming from, before it has been
16003         * copied/renamed into place. This could be a single monolithic APK
16004         * file, or a cluster directory. This location may be untrusted.
16005         */
16006        final File file;
16007        final String cid;
16008
16009        /**
16010         * Flag indicating that {@link #file} or {@link #cid} has already been
16011         * staged, meaning downstream users don't need to defensively copy the
16012         * contents.
16013         */
16014        final boolean staged;
16015
16016        /**
16017         * Flag indicating that {@link #file} or {@link #cid} is an already
16018         * installed app that is being moved.
16019         */
16020        final boolean existing;
16021
16022        final String resolvedPath;
16023        final File resolvedFile;
16024
16025        static OriginInfo fromNothing() {
16026            return new OriginInfo(null, null, false, false);
16027        }
16028
16029        static OriginInfo fromUntrustedFile(File file) {
16030            return new OriginInfo(file, null, false, false);
16031        }
16032
16033        static OriginInfo fromExistingFile(File file) {
16034            return new OriginInfo(file, null, false, true);
16035        }
16036
16037        static OriginInfo fromStagedFile(File file) {
16038            return new OriginInfo(file, null, true, false);
16039        }
16040
16041        static OriginInfo fromStagedContainer(String cid) {
16042            return new OriginInfo(null, cid, true, false);
16043        }
16044
16045        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16046            this.file = file;
16047            this.cid = cid;
16048            this.staged = staged;
16049            this.existing = existing;
16050
16051            if (cid != null) {
16052                resolvedPath = PackageHelper.getSdDir(cid);
16053                resolvedFile = new File(resolvedPath);
16054            } else if (file != null) {
16055                resolvedPath = file.getAbsolutePath();
16056                resolvedFile = file;
16057            } else {
16058                resolvedPath = null;
16059                resolvedFile = null;
16060            }
16061        }
16062    }
16063
16064    static class MoveInfo {
16065        final int moveId;
16066        final String fromUuid;
16067        final String toUuid;
16068        final String packageName;
16069        final String dataAppName;
16070        final int appId;
16071        final String seinfo;
16072        final int targetSdkVersion;
16073
16074        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16075                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16076            this.moveId = moveId;
16077            this.fromUuid = fromUuid;
16078            this.toUuid = toUuid;
16079            this.packageName = packageName;
16080            this.dataAppName = dataAppName;
16081            this.appId = appId;
16082            this.seinfo = seinfo;
16083            this.targetSdkVersion = targetSdkVersion;
16084        }
16085    }
16086
16087    static class VerificationInfo {
16088        /** A constant used to indicate that a uid value is not present. */
16089        public static final int NO_UID = -1;
16090
16091        /** URI referencing where the package was downloaded from. */
16092        final Uri originatingUri;
16093
16094        /** HTTP referrer URI associated with the originatingURI. */
16095        final Uri referrer;
16096
16097        /** UID of the application that the install request originated from. */
16098        final int originatingUid;
16099
16100        /** UID of application requesting the install */
16101        final int installerUid;
16102
16103        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16104            this.originatingUri = originatingUri;
16105            this.referrer = referrer;
16106            this.originatingUid = originatingUid;
16107            this.installerUid = installerUid;
16108        }
16109    }
16110
16111    class InstallParams extends HandlerParams {
16112        final OriginInfo origin;
16113        final MoveInfo move;
16114        final IPackageInstallObserver2 observer;
16115        int installFlags;
16116        final String installerPackageName;
16117        final String volumeUuid;
16118        private InstallArgs mArgs;
16119        private int mRet;
16120        final String packageAbiOverride;
16121        final String[] grantedRuntimePermissions;
16122        final VerificationInfo verificationInfo;
16123        final Certificate[][] certificates;
16124        final int installReason;
16125
16126        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16127                int installFlags, String installerPackageName, String volumeUuid,
16128                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16129                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16130            super(user);
16131            this.origin = origin;
16132            this.move = move;
16133            this.observer = observer;
16134            this.installFlags = installFlags;
16135            this.installerPackageName = installerPackageName;
16136            this.volumeUuid = volumeUuid;
16137            this.verificationInfo = verificationInfo;
16138            this.packageAbiOverride = packageAbiOverride;
16139            this.grantedRuntimePermissions = grantedPermissions;
16140            this.certificates = certificates;
16141            this.installReason = installReason;
16142        }
16143
16144        @Override
16145        public String toString() {
16146            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16147                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16148        }
16149
16150        private int installLocationPolicy(PackageInfoLite pkgLite) {
16151            String packageName = pkgLite.packageName;
16152            int installLocation = pkgLite.installLocation;
16153            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16154            // reader
16155            synchronized (mPackages) {
16156                // Currently installed package which the new package is attempting to replace or
16157                // null if no such package is installed.
16158                PackageParser.Package installedPkg = mPackages.get(packageName);
16159                // Package which currently owns the data which the new package will own if installed.
16160                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16161                // will be null whereas dataOwnerPkg will contain information about the package
16162                // which was uninstalled while keeping its data.
16163                PackageParser.Package dataOwnerPkg = installedPkg;
16164                if (dataOwnerPkg  == null) {
16165                    PackageSetting ps = mSettings.mPackages.get(packageName);
16166                    if (ps != null) {
16167                        dataOwnerPkg = ps.pkg;
16168                    }
16169                }
16170
16171                if (dataOwnerPkg != null) {
16172                    // If installed, the package will get access to data left on the device by its
16173                    // predecessor. As a security measure, this is permited only if this is not a
16174                    // version downgrade or if the predecessor package is marked as debuggable and
16175                    // a downgrade is explicitly requested.
16176                    //
16177                    // On debuggable platform builds, downgrades are permitted even for
16178                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16179                    // not offer security guarantees and thus it's OK to disable some security
16180                    // mechanisms to make debugging/testing easier on those builds. However, even on
16181                    // debuggable builds downgrades of packages are permitted only if requested via
16182                    // installFlags. This is because we aim to keep the behavior of debuggable
16183                    // platform builds as close as possible to the behavior of non-debuggable
16184                    // platform builds.
16185                    final boolean downgradeRequested =
16186                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16187                    final boolean packageDebuggable =
16188                                (dataOwnerPkg.applicationInfo.flags
16189                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16190                    final boolean downgradePermitted =
16191                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16192                    if (!downgradePermitted) {
16193                        try {
16194                            checkDowngrade(dataOwnerPkg, pkgLite);
16195                        } catch (PackageManagerException e) {
16196                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16197                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16198                        }
16199                    }
16200                }
16201
16202                if (installedPkg != null) {
16203                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16204                        // Check for updated system application.
16205                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16206                            if (onSd) {
16207                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16208                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16209                            }
16210                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16211                        } else {
16212                            if (onSd) {
16213                                // Install flag overrides everything.
16214                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16215                            }
16216                            // If current upgrade specifies particular preference
16217                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16218                                // Application explicitly specified internal.
16219                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16220                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16221                                // App explictly prefers external. Let policy decide
16222                            } else {
16223                                // Prefer previous location
16224                                if (isExternal(installedPkg)) {
16225                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16226                                }
16227                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16228                            }
16229                        }
16230                    } else {
16231                        // Invalid install. Return error code
16232                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16233                    }
16234                }
16235            }
16236            // All the special cases have been taken care of.
16237            // Return result based on recommended install location.
16238            if (onSd) {
16239                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16240            }
16241            return pkgLite.recommendedInstallLocation;
16242        }
16243
16244        /*
16245         * Invoke remote method to get package information and install
16246         * location values. Override install location based on default
16247         * policy if needed and then create install arguments based
16248         * on the install location.
16249         */
16250        public void handleStartCopy() throws RemoteException {
16251            int ret = PackageManager.INSTALL_SUCCEEDED;
16252
16253            // If we're already staged, we've firmly committed to an install location
16254            if (origin.staged) {
16255                if (origin.file != null) {
16256                    installFlags |= PackageManager.INSTALL_INTERNAL;
16257                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16258                } else if (origin.cid != null) {
16259                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16260                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16261                } else {
16262                    throw new IllegalStateException("Invalid stage location");
16263                }
16264            }
16265
16266            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16267            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16268            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16269            PackageInfoLite pkgLite = null;
16270
16271            if (onInt && onSd) {
16272                // Check if both bits are set.
16273                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16274                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16275            } else if (onSd && ephemeral) {
16276                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16277                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16278            } else {
16279                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16280                        packageAbiOverride);
16281
16282                if (DEBUG_EPHEMERAL && ephemeral) {
16283                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16284                }
16285
16286                /*
16287                 * If we have too little free space, try to free cache
16288                 * before giving up.
16289                 */
16290                if (!origin.staged && pkgLite.recommendedInstallLocation
16291                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16292                    // TODO: focus freeing disk space on the target device
16293                    final StorageManager storage = StorageManager.from(mContext);
16294                    final long lowThreshold = storage.getStorageLowBytes(
16295                            Environment.getDataDirectory());
16296
16297                    final long sizeBytes = mContainerService.calculateInstalledSize(
16298                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16299
16300                    try {
16301                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16302                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16303                                installFlags, packageAbiOverride);
16304                    } catch (InstallerException e) {
16305                        Slog.w(TAG, "Failed to free cache", e);
16306                    }
16307
16308                    /*
16309                     * The cache free must have deleted the file we
16310                     * downloaded to install.
16311                     *
16312                     * TODO: fix the "freeCache" call to not delete
16313                     *       the file we care about.
16314                     */
16315                    if (pkgLite.recommendedInstallLocation
16316                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16317                        pkgLite.recommendedInstallLocation
16318                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16319                    }
16320                }
16321            }
16322
16323            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16324                int loc = pkgLite.recommendedInstallLocation;
16325                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16326                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16327                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16328                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16329                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16330                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16331                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16332                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16333                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16334                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16335                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16336                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16337                } else {
16338                    // Override with defaults if needed.
16339                    loc = installLocationPolicy(pkgLite);
16340                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16341                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16342                    } else if (!onSd && !onInt) {
16343                        // Override install location with flags
16344                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16345                            // Set the flag to install on external media.
16346                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16347                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16348                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16349                            if (DEBUG_EPHEMERAL) {
16350                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16351                            }
16352                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16353                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16354                                    |PackageManager.INSTALL_INTERNAL);
16355                        } else {
16356                            // Make sure the flag for installing on external
16357                            // media is unset
16358                            installFlags |= PackageManager.INSTALL_INTERNAL;
16359                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16360                        }
16361                    }
16362                }
16363            }
16364
16365            final InstallArgs args = createInstallArgs(this);
16366            mArgs = args;
16367
16368            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16369                // TODO: http://b/22976637
16370                // Apps installed for "all" users use the device owner to verify the app
16371                UserHandle verifierUser = getUser();
16372                if (verifierUser == UserHandle.ALL) {
16373                    verifierUser = UserHandle.SYSTEM;
16374                }
16375
16376                /*
16377                 * Determine if we have any installed package verifiers. If we
16378                 * do, then we'll defer to them to verify the packages.
16379                 */
16380                final int requiredUid = mRequiredVerifierPackage == null ? -1
16381                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16382                                verifierUser.getIdentifier());
16383                final int installerUid =
16384                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16385                if (!origin.existing && requiredUid != -1
16386                        && isVerificationEnabled(
16387                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16388                    final Intent verification = new Intent(
16389                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16390                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16391                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16392                            PACKAGE_MIME_TYPE);
16393                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16394
16395                    // Query all live verifiers based on current user state
16396                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16397                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16398                            false /*allowDynamicSplits*/);
16399
16400                    if (DEBUG_VERIFY) {
16401                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16402                                + verification.toString() + " with " + pkgLite.verifiers.length
16403                                + " optional verifiers");
16404                    }
16405
16406                    final int verificationId = mPendingVerificationToken++;
16407
16408                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16409
16410                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16411                            installerPackageName);
16412
16413                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16414                            installFlags);
16415
16416                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16417                            pkgLite.packageName);
16418
16419                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16420                            pkgLite.versionCode);
16421
16422                    if (verificationInfo != null) {
16423                        if (verificationInfo.originatingUri != null) {
16424                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16425                                    verificationInfo.originatingUri);
16426                        }
16427                        if (verificationInfo.referrer != null) {
16428                            verification.putExtra(Intent.EXTRA_REFERRER,
16429                                    verificationInfo.referrer);
16430                        }
16431                        if (verificationInfo.originatingUid >= 0) {
16432                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16433                                    verificationInfo.originatingUid);
16434                        }
16435                        if (verificationInfo.installerUid >= 0) {
16436                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16437                                    verificationInfo.installerUid);
16438                        }
16439                    }
16440
16441                    final PackageVerificationState verificationState = new PackageVerificationState(
16442                            requiredUid, args);
16443
16444                    mPendingVerification.append(verificationId, verificationState);
16445
16446                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16447                            receivers, verificationState);
16448
16449                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16450                    final long idleDuration = getVerificationTimeout();
16451
16452                    /*
16453                     * If any sufficient verifiers were listed in the package
16454                     * manifest, attempt to ask them.
16455                     */
16456                    if (sufficientVerifiers != null) {
16457                        final int N = sufficientVerifiers.size();
16458                        if (N == 0) {
16459                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16460                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16461                        } else {
16462                            for (int i = 0; i < N; i++) {
16463                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16464                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16465                                        verifierComponent.getPackageName(), idleDuration,
16466                                        verifierUser.getIdentifier(), false, "package verifier");
16467
16468                                final Intent sufficientIntent = new Intent(verification);
16469                                sufficientIntent.setComponent(verifierComponent);
16470                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16471                            }
16472                        }
16473                    }
16474
16475                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16476                            mRequiredVerifierPackage, receivers);
16477                    if (ret == PackageManager.INSTALL_SUCCEEDED
16478                            && mRequiredVerifierPackage != null) {
16479                        Trace.asyncTraceBegin(
16480                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16481                        /*
16482                         * Send the intent to the required verification agent,
16483                         * but only start the verification timeout after the
16484                         * target BroadcastReceivers have run.
16485                         */
16486                        verification.setComponent(requiredVerifierComponent);
16487                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16488                                mRequiredVerifierPackage, idleDuration,
16489                                verifierUser.getIdentifier(), false, "package verifier");
16490                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16491                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16492                                new BroadcastReceiver() {
16493                                    @Override
16494                                    public void onReceive(Context context, Intent intent) {
16495                                        final Message msg = mHandler
16496                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16497                                        msg.arg1 = verificationId;
16498                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16499                                    }
16500                                }, null, 0, null, null);
16501
16502                        /*
16503                         * We don't want the copy to proceed until verification
16504                         * succeeds, so null out this field.
16505                         */
16506                        mArgs = null;
16507                    }
16508                } else {
16509                    /*
16510                     * No package verification is enabled, so immediately start
16511                     * the remote call to initiate copy using temporary file.
16512                     */
16513                    ret = args.copyApk(mContainerService, true);
16514                }
16515            }
16516
16517            mRet = ret;
16518        }
16519
16520        @Override
16521        void handleReturnCode() {
16522            // If mArgs is null, then MCS couldn't be reached. When it
16523            // reconnects, it will try again to install. At that point, this
16524            // will succeed.
16525            if (mArgs != null) {
16526                processPendingInstall(mArgs, mRet);
16527            }
16528        }
16529
16530        @Override
16531        void handleServiceError() {
16532            mArgs = createInstallArgs(this);
16533            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16534        }
16535
16536        public boolean isForwardLocked() {
16537            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16538        }
16539    }
16540
16541    /**
16542     * Used during creation of InstallArgs
16543     *
16544     * @param installFlags package installation flags
16545     * @return true if should be installed on external storage
16546     */
16547    private static boolean installOnExternalAsec(int installFlags) {
16548        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16549            return false;
16550        }
16551        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16552            return true;
16553        }
16554        return false;
16555    }
16556
16557    /**
16558     * Used during creation of InstallArgs
16559     *
16560     * @param installFlags package installation flags
16561     * @return true if should be installed as forward locked
16562     */
16563    private static boolean installForwardLocked(int installFlags) {
16564        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16565    }
16566
16567    private InstallArgs createInstallArgs(InstallParams params) {
16568        if (params.move != null) {
16569            return new MoveInstallArgs(params);
16570        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16571            return new AsecInstallArgs(params);
16572        } else {
16573            return new FileInstallArgs(params);
16574        }
16575    }
16576
16577    /**
16578     * Create args that describe an existing installed package. Typically used
16579     * when cleaning up old installs, or used as a move source.
16580     */
16581    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16582            String resourcePath, String[] instructionSets) {
16583        final boolean isInAsec;
16584        if (installOnExternalAsec(installFlags)) {
16585            /* Apps on SD card are always in ASEC containers. */
16586            isInAsec = true;
16587        } else if (installForwardLocked(installFlags)
16588                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16589            /*
16590             * Forward-locked apps are only in ASEC containers if they're the
16591             * new style
16592             */
16593            isInAsec = true;
16594        } else {
16595            isInAsec = false;
16596        }
16597
16598        if (isInAsec) {
16599            return new AsecInstallArgs(codePath, instructionSets,
16600                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16601        } else {
16602            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16603        }
16604    }
16605
16606    static abstract class InstallArgs {
16607        /** @see InstallParams#origin */
16608        final OriginInfo origin;
16609        /** @see InstallParams#move */
16610        final MoveInfo move;
16611
16612        final IPackageInstallObserver2 observer;
16613        // Always refers to PackageManager flags only
16614        final int installFlags;
16615        final String installerPackageName;
16616        final String volumeUuid;
16617        final UserHandle user;
16618        final String abiOverride;
16619        final String[] installGrantPermissions;
16620        /** If non-null, drop an async trace when the install completes */
16621        final String traceMethod;
16622        final int traceCookie;
16623        final Certificate[][] certificates;
16624        final int installReason;
16625
16626        // The list of instruction sets supported by this app. This is currently
16627        // only used during the rmdex() phase to clean up resources. We can get rid of this
16628        // if we move dex files under the common app path.
16629        /* nullable */ String[] instructionSets;
16630
16631        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16632                int installFlags, String installerPackageName, String volumeUuid,
16633                UserHandle user, String[] instructionSets,
16634                String abiOverride, String[] installGrantPermissions,
16635                String traceMethod, int traceCookie, Certificate[][] certificates,
16636                int installReason) {
16637            this.origin = origin;
16638            this.move = move;
16639            this.installFlags = installFlags;
16640            this.observer = observer;
16641            this.installerPackageName = installerPackageName;
16642            this.volumeUuid = volumeUuid;
16643            this.user = user;
16644            this.instructionSets = instructionSets;
16645            this.abiOverride = abiOverride;
16646            this.installGrantPermissions = installGrantPermissions;
16647            this.traceMethod = traceMethod;
16648            this.traceCookie = traceCookie;
16649            this.certificates = certificates;
16650            this.installReason = installReason;
16651        }
16652
16653        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16654        abstract int doPreInstall(int status);
16655
16656        /**
16657         * Rename package into final resting place. All paths on the given
16658         * scanned package should be updated to reflect the rename.
16659         */
16660        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16661        abstract int doPostInstall(int status, int uid);
16662
16663        /** @see PackageSettingBase#codePathString */
16664        abstract String getCodePath();
16665        /** @see PackageSettingBase#resourcePathString */
16666        abstract String getResourcePath();
16667
16668        // Need installer lock especially for dex file removal.
16669        abstract void cleanUpResourcesLI();
16670        abstract boolean doPostDeleteLI(boolean delete);
16671
16672        /**
16673         * Called before the source arguments are copied. This is used mostly
16674         * for MoveParams when it needs to read the source file to put it in the
16675         * destination.
16676         */
16677        int doPreCopy() {
16678            return PackageManager.INSTALL_SUCCEEDED;
16679        }
16680
16681        /**
16682         * Called after the source arguments are copied. This is used mostly for
16683         * MoveParams when it needs to read the source file to put it in the
16684         * destination.
16685         */
16686        int doPostCopy(int uid) {
16687            return PackageManager.INSTALL_SUCCEEDED;
16688        }
16689
16690        protected boolean isFwdLocked() {
16691            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16692        }
16693
16694        protected boolean isExternalAsec() {
16695            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16696        }
16697
16698        protected boolean isEphemeral() {
16699            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16700        }
16701
16702        UserHandle getUser() {
16703            return user;
16704        }
16705    }
16706
16707    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16708        if (!allCodePaths.isEmpty()) {
16709            if (instructionSets == null) {
16710                throw new IllegalStateException("instructionSet == null");
16711            }
16712            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16713            for (String codePath : allCodePaths) {
16714                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16715                    try {
16716                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16717                    } catch (InstallerException ignored) {
16718                    }
16719                }
16720            }
16721        }
16722    }
16723
16724    /**
16725     * Logic to handle installation of non-ASEC applications, including copying
16726     * and renaming logic.
16727     */
16728    class FileInstallArgs extends InstallArgs {
16729        private File codeFile;
16730        private File resourceFile;
16731
16732        // Example topology:
16733        // /data/app/com.example/base.apk
16734        // /data/app/com.example/split_foo.apk
16735        // /data/app/com.example/lib/arm/libfoo.so
16736        // /data/app/com.example/lib/arm64/libfoo.so
16737        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16738
16739        /** New install */
16740        FileInstallArgs(InstallParams params) {
16741            super(params.origin, params.move, params.observer, params.installFlags,
16742                    params.installerPackageName, params.volumeUuid,
16743                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16744                    params.grantedRuntimePermissions,
16745                    params.traceMethod, params.traceCookie, params.certificates,
16746                    params.installReason);
16747            if (isFwdLocked()) {
16748                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16749            }
16750        }
16751
16752        /** Existing install */
16753        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16754            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16755                    null, null, null, 0, null /*certificates*/,
16756                    PackageManager.INSTALL_REASON_UNKNOWN);
16757            this.codeFile = (codePath != null) ? new File(codePath) : null;
16758            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16759        }
16760
16761        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16762            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16763            try {
16764                return doCopyApk(imcs, temp);
16765            } finally {
16766                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16767            }
16768        }
16769
16770        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16771            if (origin.staged) {
16772                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16773                codeFile = origin.file;
16774                resourceFile = origin.file;
16775                return PackageManager.INSTALL_SUCCEEDED;
16776            }
16777
16778            try {
16779                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16780                final File tempDir =
16781                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16782                codeFile = tempDir;
16783                resourceFile = tempDir;
16784            } catch (IOException e) {
16785                Slog.w(TAG, "Failed to create copy file: " + e);
16786                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16787            }
16788
16789            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16790                @Override
16791                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16792                    if (!FileUtils.isValidExtFilename(name)) {
16793                        throw new IllegalArgumentException("Invalid filename: " + name);
16794                    }
16795                    try {
16796                        final File file = new File(codeFile, name);
16797                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16798                                O_RDWR | O_CREAT, 0644);
16799                        Os.chmod(file.getAbsolutePath(), 0644);
16800                        return new ParcelFileDescriptor(fd);
16801                    } catch (ErrnoException e) {
16802                        throw new RemoteException("Failed to open: " + e.getMessage());
16803                    }
16804                }
16805            };
16806
16807            int ret = PackageManager.INSTALL_SUCCEEDED;
16808            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16809            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16810                Slog.e(TAG, "Failed to copy package");
16811                return ret;
16812            }
16813
16814            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16815            NativeLibraryHelper.Handle handle = null;
16816            try {
16817                handle = NativeLibraryHelper.Handle.create(codeFile);
16818                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16819                        abiOverride);
16820            } catch (IOException e) {
16821                Slog.e(TAG, "Copying native libraries failed", e);
16822                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16823            } finally {
16824                IoUtils.closeQuietly(handle);
16825            }
16826
16827            return ret;
16828        }
16829
16830        int doPreInstall(int status) {
16831            if (status != PackageManager.INSTALL_SUCCEEDED) {
16832                cleanUp();
16833            }
16834            return status;
16835        }
16836
16837        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16838            if (status != PackageManager.INSTALL_SUCCEEDED) {
16839                cleanUp();
16840                return false;
16841            }
16842
16843            final File targetDir = codeFile.getParentFile();
16844            final File beforeCodeFile = codeFile;
16845            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16846
16847            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16848            try {
16849                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16850            } catch (ErrnoException e) {
16851                Slog.w(TAG, "Failed to rename", e);
16852                return false;
16853            }
16854
16855            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16856                Slog.w(TAG, "Failed to restorecon");
16857                return false;
16858            }
16859
16860            // Reflect the rename internally
16861            codeFile = afterCodeFile;
16862            resourceFile = afterCodeFile;
16863
16864            // Reflect the rename in scanned details
16865            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16866            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16867                    afterCodeFile, pkg.baseCodePath));
16868            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16869                    afterCodeFile, pkg.splitCodePaths));
16870
16871            // Reflect the rename in app info
16872            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16873            pkg.setApplicationInfoCodePath(pkg.codePath);
16874            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16875            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16876            pkg.setApplicationInfoResourcePath(pkg.codePath);
16877            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16878            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16879
16880            return true;
16881        }
16882
16883        int doPostInstall(int status, int uid) {
16884            if (status != PackageManager.INSTALL_SUCCEEDED) {
16885                cleanUp();
16886            }
16887            return status;
16888        }
16889
16890        @Override
16891        String getCodePath() {
16892            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16893        }
16894
16895        @Override
16896        String getResourcePath() {
16897            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16898        }
16899
16900        private boolean cleanUp() {
16901            if (codeFile == null || !codeFile.exists()) {
16902                return false;
16903            }
16904
16905            removeCodePathLI(codeFile);
16906
16907            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16908                resourceFile.delete();
16909            }
16910
16911            return true;
16912        }
16913
16914        void cleanUpResourcesLI() {
16915            // Try enumerating all code paths before deleting
16916            List<String> allCodePaths = Collections.EMPTY_LIST;
16917            if (codeFile != null && codeFile.exists()) {
16918                try {
16919                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16920                    allCodePaths = pkg.getAllCodePaths();
16921                } catch (PackageParserException e) {
16922                    // Ignored; we tried our best
16923                }
16924            }
16925
16926            cleanUp();
16927            removeDexFiles(allCodePaths, instructionSets);
16928        }
16929
16930        boolean doPostDeleteLI(boolean delete) {
16931            // XXX err, shouldn't we respect the delete flag?
16932            cleanUpResourcesLI();
16933            return true;
16934        }
16935    }
16936
16937    private boolean isAsecExternal(String cid) {
16938        final String asecPath = PackageHelper.getSdFilesystem(cid);
16939        return !asecPath.startsWith(mAsecInternalPath);
16940    }
16941
16942    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16943            PackageManagerException {
16944        if (copyRet < 0) {
16945            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16946                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16947                throw new PackageManagerException(copyRet, message);
16948            }
16949        }
16950    }
16951
16952    /**
16953     * Extract the StorageManagerService "container ID" from the full code path of an
16954     * .apk.
16955     */
16956    static String cidFromCodePath(String fullCodePath) {
16957        int eidx = fullCodePath.lastIndexOf("/");
16958        String subStr1 = fullCodePath.substring(0, eidx);
16959        int sidx = subStr1.lastIndexOf("/");
16960        return subStr1.substring(sidx+1, eidx);
16961    }
16962
16963    /**
16964     * Logic to handle installation of ASEC applications, including copying and
16965     * renaming logic.
16966     */
16967    class AsecInstallArgs extends InstallArgs {
16968        static final String RES_FILE_NAME = "pkg.apk";
16969        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16970
16971        String cid;
16972        String packagePath;
16973        String resourcePath;
16974
16975        /** New install */
16976        AsecInstallArgs(InstallParams params) {
16977            super(params.origin, params.move, params.observer, params.installFlags,
16978                    params.installerPackageName, params.volumeUuid,
16979                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16980                    params.grantedRuntimePermissions,
16981                    params.traceMethod, params.traceCookie, params.certificates,
16982                    params.installReason);
16983        }
16984
16985        /** Existing install */
16986        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16987                        boolean isExternal, boolean isForwardLocked) {
16988            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16989                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16990                    instructionSets, null, null, null, 0, null /*certificates*/,
16991                    PackageManager.INSTALL_REASON_UNKNOWN);
16992            // Hackily pretend we're still looking at a full code path
16993            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16994                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16995            }
16996
16997            // Extract cid from fullCodePath
16998            int eidx = fullCodePath.lastIndexOf("/");
16999            String subStr1 = fullCodePath.substring(0, eidx);
17000            int sidx = subStr1.lastIndexOf("/");
17001            cid = subStr1.substring(sidx+1, eidx);
17002            setMountPath(subStr1);
17003        }
17004
17005        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
17006            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
17007                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17008                    instructionSets, null, null, null, 0, null /*certificates*/,
17009                    PackageManager.INSTALL_REASON_UNKNOWN);
17010            this.cid = cid;
17011            setMountPath(PackageHelper.getSdDir(cid));
17012        }
17013
17014        void createCopyFile() {
17015            cid = mInstallerService.allocateExternalStageCidLegacy();
17016        }
17017
17018        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17019            if (origin.staged && origin.cid != null) {
17020                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17021                cid = origin.cid;
17022                setMountPath(PackageHelper.getSdDir(cid));
17023                return PackageManager.INSTALL_SUCCEEDED;
17024            }
17025
17026            if (temp) {
17027                createCopyFile();
17028            } else {
17029                /*
17030                 * Pre-emptively destroy the container since it's destroyed if
17031                 * copying fails due to it existing anyway.
17032                 */
17033                PackageHelper.destroySdDir(cid);
17034            }
17035
17036            final String newMountPath = imcs.copyPackageToContainer(
17037                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17038                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17039
17040            if (newMountPath != null) {
17041                setMountPath(newMountPath);
17042                return PackageManager.INSTALL_SUCCEEDED;
17043            } else {
17044                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17045            }
17046        }
17047
17048        @Override
17049        String getCodePath() {
17050            return packagePath;
17051        }
17052
17053        @Override
17054        String getResourcePath() {
17055            return resourcePath;
17056        }
17057
17058        int doPreInstall(int status) {
17059            if (status != PackageManager.INSTALL_SUCCEEDED) {
17060                // Destroy container
17061                PackageHelper.destroySdDir(cid);
17062            } else {
17063                boolean mounted = PackageHelper.isContainerMounted(cid);
17064                if (!mounted) {
17065                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17066                            Process.SYSTEM_UID);
17067                    if (newMountPath != null) {
17068                        setMountPath(newMountPath);
17069                    } else {
17070                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17071                    }
17072                }
17073            }
17074            return status;
17075        }
17076
17077        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17078            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17079            String newMountPath = null;
17080            if (PackageHelper.isContainerMounted(cid)) {
17081                // Unmount the container
17082                if (!PackageHelper.unMountSdDir(cid)) {
17083                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17084                    return false;
17085                }
17086            }
17087            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17088                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17089                        " which might be stale. Will try to clean up.");
17090                // Clean up the stale container and proceed to recreate.
17091                if (!PackageHelper.destroySdDir(newCacheId)) {
17092                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17093                    return false;
17094                }
17095                // Successfully cleaned up stale container. Try to rename again.
17096                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17097                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17098                            + " inspite of cleaning it up.");
17099                    return false;
17100                }
17101            }
17102            if (!PackageHelper.isContainerMounted(newCacheId)) {
17103                Slog.w(TAG, "Mounting container " + newCacheId);
17104                newMountPath = PackageHelper.mountSdDir(newCacheId,
17105                        getEncryptKey(), Process.SYSTEM_UID);
17106            } else {
17107                newMountPath = PackageHelper.getSdDir(newCacheId);
17108            }
17109            if (newMountPath == null) {
17110                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17111                return false;
17112            }
17113            Log.i(TAG, "Succesfully renamed " + cid +
17114                    " to " + newCacheId +
17115                    " at new path: " + newMountPath);
17116            cid = newCacheId;
17117
17118            final File beforeCodeFile = new File(packagePath);
17119            setMountPath(newMountPath);
17120            final File afterCodeFile = new File(packagePath);
17121
17122            // Reflect the rename in scanned details
17123            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17124            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17125                    afterCodeFile, pkg.baseCodePath));
17126            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17127                    afterCodeFile, pkg.splitCodePaths));
17128
17129            // Reflect the rename in app info
17130            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17131            pkg.setApplicationInfoCodePath(pkg.codePath);
17132            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17133            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17134            pkg.setApplicationInfoResourcePath(pkg.codePath);
17135            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17136            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17137
17138            return true;
17139        }
17140
17141        private void setMountPath(String mountPath) {
17142            final File mountFile = new File(mountPath);
17143
17144            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17145            if (monolithicFile.exists()) {
17146                packagePath = monolithicFile.getAbsolutePath();
17147                if (isFwdLocked()) {
17148                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17149                } else {
17150                    resourcePath = packagePath;
17151                }
17152            } else {
17153                packagePath = mountFile.getAbsolutePath();
17154                resourcePath = packagePath;
17155            }
17156        }
17157
17158        int doPostInstall(int status, int uid) {
17159            if (status != PackageManager.INSTALL_SUCCEEDED) {
17160                cleanUp();
17161            } else {
17162                final int groupOwner;
17163                final String protectedFile;
17164                if (isFwdLocked()) {
17165                    groupOwner = UserHandle.getSharedAppGid(uid);
17166                    protectedFile = RES_FILE_NAME;
17167                } else {
17168                    groupOwner = -1;
17169                    protectedFile = null;
17170                }
17171
17172                if (uid < Process.FIRST_APPLICATION_UID
17173                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17174                    Slog.e(TAG, "Failed to finalize " + cid);
17175                    PackageHelper.destroySdDir(cid);
17176                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17177                }
17178
17179                boolean mounted = PackageHelper.isContainerMounted(cid);
17180                if (!mounted) {
17181                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17182                }
17183            }
17184            return status;
17185        }
17186
17187        private void cleanUp() {
17188            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17189
17190            // Destroy secure container
17191            PackageHelper.destroySdDir(cid);
17192        }
17193
17194        private List<String> getAllCodePaths() {
17195            final File codeFile = new File(getCodePath());
17196            if (codeFile != null && codeFile.exists()) {
17197                try {
17198                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17199                    return pkg.getAllCodePaths();
17200                } catch (PackageParserException e) {
17201                    // Ignored; we tried our best
17202                }
17203            }
17204            return Collections.EMPTY_LIST;
17205        }
17206
17207        void cleanUpResourcesLI() {
17208            // Enumerate all code paths before deleting
17209            cleanUpResourcesLI(getAllCodePaths());
17210        }
17211
17212        private void cleanUpResourcesLI(List<String> allCodePaths) {
17213            cleanUp();
17214            removeDexFiles(allCodePaths, instructionSets);
17215        }
17216
17217        String getPackageName() {
17218            return getAsecPackageName(cid);
17219        }
17220
17221        boolean doPostDeleteLI(boolean delete) {
17222            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17223            final List<String> allCodePaths = getAllCodePaths();
17224            boolean mounted = PackageHelper.isContainerMounted(cid);
17225            if (mounted) {
17226                // Unmount first
17227                if (PackageHelper.unMountSdDir(cid)) {
17228                    mounted = false;
17229                }
17230            }
17231            if (!mounted && delete) {
17232                cleanUpResourcesLI(allCodePaths);
17233            }
17234            return !mounted;
17235        }
17236
17237        @Override
17238        int doPreCopy() {
17239            if (isFwdLocked()) {
17240                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17241                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17242                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17243                }
17244            }
17245
17246            return PackageManager.INSTALL_SUCCEEDED;
17247        }
17248
17249        @Override
17250        int doPostCopy(int uid) {
17251            if (isFwdLocked()) {
17252                if (uid < Process.FIRST_APPLICATION_UID
17253                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17254                                RES_FILE_NAME)) {
17255                    Slog.e(TAG, "Failed to finalize " + cid);
17256                    PackageHelper.destroySdDir(cid);
17257                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17258                }
17259            }
17260
17261            return PackageManager.INSTALL_SUCCEEDED;
17262        }
17263    }
17264
17265    /**
17266     * Logic to handle movement of existing installed applications.
17267     */
17268    class MoveInstallArgs extends InstallArgs {
17269        private File codeFile;
17270        private File resourceFile;
17271
17272        /** New install */
17273        MoveInstallArgs(InstallParams params) {
17274            super(params.origin, params.move, params.observer, params.installFlags,
17275                    params.installerPackageName, params.volumeUuid,
17276                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17277                    params.grantedRuntimePermissions,
17278                    params.traceMethod, params.traceCookie, params.certificates,
17279                    params.installReason);
17280        }
17281
17282        int copyApk(IMediaContainerService imcs, boolean temp) {
17283            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17284                    + move.fromUuid + " to " + move.toUuid);
17285            synchronized (mInstaller) {
17286                try {
17287                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17288                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17289                } catch (InstallerException e) {
17290                    Slog.w(TAG, "Failed to move app", e);
17291                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17292                }
17293            }
17294
17295            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17296            resourceFile = codeFile;
17297            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17298
17299            return PackageManager.INSTALL_SUCCEEDED;
17300        }
17301
17302        int doPreInstall(int status) {
17303            if (status != PackageManager.INSTALL_SUCCEEDED) {
17304                cleanUp(move.toUuid);
17305            }
17306            return status;
17307        }
17308
17309        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17310            if (status != PackageManager.INSTALL_SUCCEEDED) {
17311                cleanUp(move.toUuid);
17312                return false;
17313            }
17314
17315            // Reflect the move in app info
17316            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17317            pkg.setApplicationInfoCodePath(pkg.codePath);
17318            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17319            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17320            pkg.setApplicationInfoResourcePath(pkg.codePath);
17321            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17322            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17323
17324            return true;
17325        }
17326
17327        int doPostInstall(int status, int uid) {
17328            if (status == PackageManager.INSTALL_SUCCEEDED) {
17329                cleanUp(move.fromUuid);
17330            } else {
17331                cleanUp(move.toUuid);
17332            }
17333            return status;
17334        }
17335
17336        @Override
17337        String getCodePath() {
17338            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17339        }
17340
17341        @Override
17342        String getResourcePath() {
17343            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17344        }
17345
17346        private boolean cleanUp(String volumeUuid) {
17347            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17348                    move.dataAppName);
17349            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17350            final int[] userIds = sUserManager.getUserIds();
17351            synchronized (mInstallLock) {
17352                // Clean up both app data and code
17353                // All package moves are frozen until finished
17354                for (int userId : userIds) {
17355                    try {
17356                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17357                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17358                    } catch (InstallerException e) {
17359                        Slog.w(TAG, String.valueOf(e));
17360                    }
17361                }
17362                removeCodePathLI(codeFile);
17363            }
17364            return true;
17365        }
17366
17367        void cleanUpResourcesLI() {
17368            throw new UnsupportedOperationException();
17369        }
17370
17371        boolean doPostDeleteLI(boolean delete) {
17372            throw new UnsupportedOperationException();
17373        }
17374    }
17375
17376    static String getAsecPackageName(String packageCid) {
17377        int idx = packageCid.lastIndexOf("-");
17378        if (idx == -1) {
17379            return packageCid;
17380        }
17381        return packageCid.substring(0, idx);
17382    }
17383
17384    // Utility method used to create code paths based on package name and available index.
17385    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17386        String idxStr = "";
17387        int idx = 1;
17388        // Fall back to default value of idx=1 if prefix is not
17389        // part of oldCodePath
17390        if (oldCodePath != null) {
17391            String subStr = oldCodePath;
17392            // Drop the suffix right away
17393            if (suffix != null && subStr.endsWith(suffix)) {
17394                subStr = subStr.substring(0, subStr.length() - suffix.length());
17395            }
17396            // If oldCodePath already contains prefix find out the
17397            // ending index to either increment or decrement.
17398            int sidx = subStr.lastIndexOf(prefix);
17399            if (sidx != -1) {
17400                subStr = subStr.substring(sidx + prefix.length());
17401                if (subStr != null) {
17402                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17403                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17404                    }
17405                    try {
17406                        idx = Integer.parseInt(subStr);
17407                        if (idx <= 1) {
17408                            idx++;
17409                        } else {
17410                            idx--;
17411                        }
17412                    } catch(NumberFormatException e) {
17413                    }
17414                }
17415            }
17416        }
17417        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17418        return prefix + idxStr;
17419    }
17420
17421    private File getNextCodePath(File targetDir, String packageName) {
17422        File result;
17423        SecureRandom random = new SecureRandom();
17424        byte[] bytes = new byte[16];
17425        do {
17426            random.nextBytes(bytes);
17427            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17428            result = new File(targetDir, packageName + "-" + suffix);
17429        } while (result.exists());
17430        return result;
17431    }
17432
17433    // Utility method that returns the relative package path with respect
17434    // to the installation directory. Like say for /data/data/com.test-1.apk
17435    // string com.test-1 is returned.
17436    static String deriveCodePathName(String codePath) {
17437        if (codePath == null) {
17438            return null;
17439        }
17440        final File codeFile = new File(codePath);
17441        final String name = codeFile.getName();
17442        if (codeFile.isDirectory()) {
17443            return name;
17444        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17445            final int lastDot = name.lastIndexOf('.');
17446            return name.substring(0, lastDot);
17447        } else {
17448            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17449            return null;
17450        }
17451    }
17452
17453    static class PackageInstalledInfo {
17454        String name;
17455        int uid;
17456        // The set of users that originally had this package installed.
17457        int[] origUsers;
17458        // The set of users that now have this package installed.
17459        int[] newUsers;
17460        PackageParser.Package pkg;
17461        int returnCode;
17462        String returnMsg;
17463        String installerPackageName;
17464        PackageRemovedInfo removedInfo;
17465        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17466
17467        public void setError(int code, String msg) {
17468            setReturnCode(code);
17469            setReturnMessage(msg);
17470            Slog.w(TAG, msg);
17471        }
17472
17473        public void setError(String msg, PackageParserException e) {
17474            setReturnCode(e.error);
17475            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17476            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17477            for (int i = 0; i < childCount; i++) {
17478                addedChildPackages.valueAt(i).setError(msg, e);
17479            }
17480            Slog.w(TAG, msg, e);
17481        }
17482
17483        public void setError(String msg, PackageManagerException e) {
17484            returnCode = e.error;
17485            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17486            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17487            for (int i = 0; i < childCount; i++) {
17488                addedChildPackages.valueAt(i).setError(msg, e);
17489            }
17490            Slog.w(TAG, msg, e);
17491        }
17492
17493        public void setReturnCode(int returnCode) {
17494            this.returnCode = returnCode;
17495            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17496            for (int i = 0; i < childCount; i++) {
17497                addedChildPackages.valueAt(i).returnCode = returnCode;
17498            }
17499        }
17500
17501        private void setReturnMessage(String returnMsg) {
17502            this.returnMsg = returnMsg;
17503            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17504            for (int i = 0; i < childCount; i++) {
17505                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17506            }
17507        }
17508
17509        // In some error cases we want to convey more info back to the observer
17510        String origPackage;
17511        String origPermission;
17512    }
17513
17514    /*
17515     * Install a non-existing package.
17516     */
17517    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17518            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17519            PackageInstalledInfo res, int installReason) {
17520        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17521
17522        // Remember this for later, in case we need to rollback this install
17523        String pkgName = pkg.packageName;
17524
17525        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17526
17527        synchronized(mPackages) {
17528            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17529            if (renamedPackage != null) {
17530                // A package with the same name is already installed, though
17531                // it has been renamed to an older name.  The package we
17532                // are trying to install should be installed as an update to
17533                // the existing one, but that has not been requested, so bail.
17534                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17535                        + " without first uninstalling package running as "
17536                        + renamedPackage);
17537                return;
17538            }
17539            if (mPackages.containsKey(pkgName)) {
17540                // Don't allow installation over an existing package with the same name.
17541                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17542                        + " without first uninstalling.");
17543                return;
17544            }
17545        }
17546
17547        try {
17548            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17549                    System.currentTimeMillis(), user);
17550
17551            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17552
17553            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17554                prepareAppDataAfterInstallLIF(newPackage);
17555
17556            } else {
17557                // Remove package from internal structures, but keep around any
17558                // data that might have already existed
17559                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17560                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17561            }
17562        } catch (PackageManagerException e) {
17563            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17564        }
17565
17566        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17567    }
17568
17569    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17570        // Can't rotate keys during boot or if sharedUser.
17571        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17572                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17573            return false;
17574        }
17575        // app is using upgradeKeySets; make sure all are valid
17576        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17577        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17578        for (int i = 0; i < upgradeKeySets.length; i++) {
17579            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17580                Slog.wtf(TAG, "Package "
17581                         + (oldPs.name != null ? oldPs.name : "<null>")
17582                         + " contains upgrade-key-set reference to unknown key-set: "
17583                         + upgradeKeySets[i]
17584                         + " reverting to signatures check.");
17585                return false;
17586            }
17587        }
17588        return true;
17589    }
17590
17591    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17592        // Upgrade keysets are being used.  Determine if new package has a superset of the
17593        // required keys.
17594        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17595        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17596        for (int i = 0; i < upgradeKeySets.length; i++) {
17597            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17598            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17599                return true;
17600            }
17601        }
17602        return false;
17603    }
17604
17605    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17606        try (DigestInputStream digestStream =
17607                new DigestInputStream(new FileInputStream(file), digest)) {
17608            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17609        }
17610    }
17611
17612    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17613            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17614            int installReason) {
17615        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17616
17617        final PackageParser.Package oldPackage;
17618        final PackageSetting ps;
17619        final String pkgName = pkg.packageName;
17620        final int[] allUsers;
17621        final int[] installedUsers;
17622
17623        synchronized(mPackages) {
17624            oldPackage = mPackages.get(pkgName);
17625            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17626
17627            // don't allow upgrade to target a release SDK from a pre-release SDK
17628            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17629                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17630            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17631                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17632            if (oldTargetsPreRelease
17633                    && !newTargetsPreRelease
17634                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17635                Slog.w(TAG, "Can't install package targeting released sdk");
17636                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17637                return;
17638            }
17639
17640            ps = mSettings.mPackages.get(pkgName);
17641
17642            // verify signatures are valid
17643            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17644                if (!checkUpgradeKeySetLP(ps, pkg)) {
17645                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17646                            "New package not signed by keys specified by upgrade-keysets: "
17647                                    + pkgName);
17648                    return;
17649                }
17650            } else {
17651                // default to original signature matching
17652                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17653                        != PackageManager.SIGNATURE_MATCH) {
17654                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17655                            "New package has a different signature: " + pkgName);
17656                    return;
17657                }
17658            }
17659
17660            // don't allow a system upgrade unless the upgrade hash matches
17661            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17662                byte[] digestBytes = null;
17663                try {
17664                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17665                    updateDigest(digest, new File(pkg.baseCodePath));
17666                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17667                        for (String path : pkg.splitCodePaths) {
17668                            updateDigest(digest, new File(path));
17669                        }
17670                    }
17671                    digestBytes = digest.digest();
17672                } catch (NoSuchAlgorithmException | IOException e) {
17673                    res.setError(INSTALL_FAILED_INVALID_APK,
17674                            "Could not compute hash: " + pkgName);
17675                    return;
17676                }
17677                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17678                    res.setError(INSTALL_FAILED_INVALID_APK,
17679                            "New package fails restrict-update check: " + pkgName);
17680                    return;
17681                }
17682                // retain upgrade restriction
17683                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17684            }
17685
17686            // Check for shared user id changes
17687            String invalidPackageName =
17688                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17689            if (invalidPackageName != null) {
17690                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17691                        "Package " + invalidPackageName + " tried to change user "
17692                                + oldPackage.mSharedUserId);
17693                return;
17694            }
17695
17696            // In case of rollback, remember per-user/profile install state
17697            allUsers = sUserManager.getUserIds();
17698            installedUsers = ps.queryInstalledUsers(allUsers, true);
17699
17700            // don't allow an upgrade from full to ephemeral
17701            if (isInstantApp) {
17702                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17703                    for (int currentUser : allUsers) {
17704                        if (!ps.getInstantApp(currentUser)) {
17705                            // can't downgrade from full to instant
17706                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17707                                    + " for user: " + currentUser);
17708                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17709                            return;
17710                        }
17711                    }
17712                } else if (!ps.getInstantApp(user.getIdentifier())) {
17713                    // can't downgrade from full to instant
17714                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17715                            + " for user: " + user.getIdentifier());
17716                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17717                    return;
17718                }
17719            }
17720        }
17721
17722        // Update what is removed
17723        res.removedInfo = new PackageRemovedInfo(this);
17724        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17725        res.removedInfo.removedPackage = oldPackage.packageName;
17726        res.removedInfo.installerPackageName = ps.installerPackageName;
17727        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17728        res.removedInfo.isUpdate = true;
17729        res.removedInfo.origUsers = installedUsers;
17730        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17731        for (int i = 0; i < installedUsers.length; i++) {
17732            final int userId = installedUsers[i];
17733            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17734        }
17735
17736        final int childCount = (oldPackage.childPackages != null)
17737                ? oldPackage.childPackages.size() : 0;
17738        for (int i = 0; i < childCount; i++) {
17739            boolean childPackageUpdated = false;
17740            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17741            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17742            if (res.addedChildPackages != null) {
17743                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17744                if (childRes != null) {
17745                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17746                    childRes.removedInfo.removedPackage = childPkg.packageName;
17747                    if (childPs != null) {
17748                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17749                    }
17750                    childRes.removedInfo.isUpdate = true;
17751                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17752                    childPackageUpdated = true;
17753                }
17754            }
17755            if (!childPackageUpdated) {
17756                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17757                childRemovedRes.removedPackage = childPkg.packageName;
17758                if (childPs != null) {
17759                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17760                }
17761                childRemovedRes.isUpdate = false;
17762                childRemovedRes.dataRemoved = true;
17763                synchronized (mPackages) {
17764                    if (childPs != null) {
17765                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17766                    }
17767                }
17768                if (res.removedInfo.removedChildPackages == null) {
17769                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17770                }
17771                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17772            }
17773        }
17774
17775        boolean sysPkg = (isSystemApp(oldPackage));
17776        if (sysPkg) {
17777            // Set the system/privileged flags as needed
17778            final boolean privileged =
17779                    (oldPackage.applicationInfo.privateFlags
17780                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17781            final int systemPolicyFlags = policyFlags
17782                    | PackageParser.PARSE_IS_SYSTEM
17783                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17784
17785            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17786                    user, allUsers, installerPackageName, res, installReason);
17787        } else {
17788            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17789                    user, allUsers, installerPackageName, res, installReason);
17790        }
17791    }
17792
17793    @Override
17794    public List<String> getPreviousCodePaths(String packageName) {
17795        final int callingUid = Binder.getCallingUid();
17796        final List<String> result = new ArrayList<>();
17797        if (getInstantAppPackageName(callingUid) != null) {
17798            return result;
17799        }
17800        final PackageSetting ps = mSettings.mPackages.get(packageName);
17801        if (ps != null
17802                && ps.oldCodePaths != null
17803                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17804            result.addAll(ps.oldCodePaths);
17805        }
17806        return result;
17807    }
17808
17809    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17810            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17811            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17812            int installReason) {
17813        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17814                + deletedPackage);
17815
17816        String pkgName = deletedPackage.packageName;
17817        boolean deletedPkg = true;
17818        boolean addedPkg = false;
17819        boolean updatedSettings = false;
17820        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17821        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17822                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17823
17824        final long origUpdateTime = (pkg.mExtras != null)
17825                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17826
17827        // First delete the existing package while retaining the data directory
17828        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17829                res.removedInfo, true, pkg)) {
17830            // If the existing package wasn't successfully deleted
17831            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17832            deletedPkg = false;
17833        } else {
17834            // Successfully deleted the old package; proceed with replace.
17835
17836            // If deleted package lived in a container, give users a chance to
17837            // relinquish resources before killing.
17838            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17839                if (DEBUG_INSTALL) {
17840                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17841                }
17842                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17843                final ArrayList<String> pkgList = new ArrayList<String>(1);
17844                pkgList.add(deletedPackage.applicationInfo.packageName);
17845                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17846            }
17847
17848            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17849                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17850            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17851
17852            try {
17853                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17854                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17855                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17856                        installReason);
17857
17858                // Update the in-memory copy of the previous code paths.
17859                PackageSetting ps = mSettings.mPackages.get(pkgName);
17860                if (!killApp) {
17861                    if (ps.oldCodePaths == null) {
17862                        ps.oldCodePaths = new ArraySet<>();
17863                    }
17864                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17865                    if (deletedPackage.splitCodePaths != null) {
17866                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17867                    }
17868                } else {
17869                    ps.oldCodePaths = null;
17870                }
17871                if (ps.childPackageNames != null) {
17872                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17873                        final String childPkgName = ps.childPackageNames.get(i);
17874                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17875                        childPs.oldCodePaths = ps.oldCodePaths;
17876                    }
17877                }
17878                // set instant app status, but, only if it's explicitly specified
17879                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17880                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17881                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17882                prepareAppDataAfterInstallLIF(newPackage);
17883                addedPkg = true;
17884                mDexManager.notifyPackageUpdated(newPackage.packageName,
17885                        newPackage.baseCodePath, newPackage.splitCodePaths);
17886            } catch (PackageManagerException e) {
17887                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17888            }
17889        }
17890
17891        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17892            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17893
17894            // Revert all internal state mutations and added folders for the failed install
17895            if (addedPkg) {
17896                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17897                        res.removedInfo, true, null);
17898            }
17899
17900            // Restore the old package
17901            if (deletedPkg) {
17902                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17903                File restoreFile = new File(deletedPackage.codePath);
17904                // Parse old package
17905                boolean oldExternal = isExternal(deletedPackage);
17906                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17907                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17908                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17909                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17910                try {
17911                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17912                            null);
17913                } catch (PackageManagerException e) {
17914                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17915                            + e.getMessage());
17916                    return;
17917                }
17918
17919                synchronized (mPackages) {
17920                    // Ensure the installer package name up to date
17921                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17922
17923                    // Update permissions for restored package
17924                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17925
17926                    mSettings.writeLPr();
17927                }
17928
17929                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17930            }
17931        } else {
17932            synchronized (mPackages) {
17933                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17934                if (ps != null) {
17935                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17936                    if (res.removedInfo.removedChildPackages != null) {
17937                        final int childCount = res.removedInfo.removedChildPackages.size();
17938                        // Iterate in reverse as we may modify the collection
17939                        for (int i = childCount - 1; i >= 0; i--) {
17940                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17941                            if (res.addedChildPackages.containsKey(childPackageName)) {
17942                                res.removedInfo.removedChildPackages.removeAt(i);
17943                            } else {
17944                                PackageRemovedInfo childInfo = res.removedInfo
17945                                        .removedChildPackages.valueAt(i);
17946                                childInfo.removedForAllUsers = mPackages.get(
17947                                        childInfo.removedPackage) == null;
17948                            }
17949                        }
17950                    }
17951                }
17952            }
17953        }
17954    }
17955
17956    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17957            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17958            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17959            int installReason) {
17960        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17961                + ", old=" + deletedPackage);
17962
17963        final boolean disabledSystem;
17964
17965        // Remove existing system package
17966        removePackageLI(deletedPackage, true);
17967
17968        synchronized (mPackages) {
17969            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17970        }
17971        if (!disabledSystem) {
17972            // We didn't need to disable the .apk as a current system package,
17973            // which means we are replacing another update that is already
17974            // installed.  We need to make sure to delete the older one's .apk.
17975            res.removedInfo.args = createInstallArgsForExisting(0,
17976                    deletedPackage.applicationInfo.getCodePath(),
17977                    deletedPackage.applicationInfo.getResourcePath(),
17978                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17979        } else {
17980            res.removedInfo.args = null;
17981        }
17982
17983        // Successfully disabled the old package. Now proceed with re-installation
17984        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17985                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17986        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17987
17988        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17989        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17990                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17991
17992        PackageParser.Package newPackage = null;
17993        try {
17994            // Add the package to the internal data structures
17995            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17996
17997            // Set the update and install times
17998            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17999            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
18000                    System.currentTimeMillis());
18001
18002            // Update the package dynamic state if succeeded
18003            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18004                // Now that the install succeeded make sure we remove data
18005                // directories for any child package the update removed.
18006                final int deletedChildCount = (deletedPackage.childPackages != null)
18007                        ? deletedPackage.childPackages.size() : 0;
18008                final int newChildCount = (newPackage.childPackages != null)
18009                        ? newPackage.childPackages.size() : 0;
18010                for (int i = 0; i < deletedChildCount; i++) {
18011                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
18012                    boolean childPackageDeleted = true;
18013                    for (int j = 0; j < newChildCount; j++) {
18014                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18015                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18016                            childPackageDeleted = false;
18017                            break;
18018                        }
18019                    }
18020                    if (childPackageDeleted) {
18021                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18022                                deletedChildPkg.packageName);
18023                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18024                            PackageRemovedInfo removedChildRes = res.removedInfo
18025                                    .removedChildPackages.get(deletedChildPkg.packageName);
18026                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18027                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18028                        }
18029                    }
18030                }
18031
18032                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18033                        installReason);
18034                prepareAppDataAfterInstallLIF(newPackage);
18035
18036                mDexManager.notifyPackageUpdated(newPackage.packageName,
18037                            newPackage.baseCodePath, newPackage.splitCodePaths);
18038            }
18039        } catch (PackageManagerException e) {
18040            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18041            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18042        }
18043
18044        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18045            // Re installation failed. Restore old information
18046            // Remove new pkg information
18047            if (newPackage != null) {
18048                removeInstalledPackageLI(newPackage, true);
18049            }
18050            // Add back the old system package
18051            try {
18052                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18053            } catch (PackageManagerException e) {
18054                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18055            }
18056
18057            synchronized (mPackages) {
18058                if (disabledSystem) {
18059                    enableSystemPackageLPw(deletedPackage);
18060                }
18061
18062                // Ensure the installer package name up to date
18063                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18064
18065                // Update permissions for restored package
18066                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18067
18068                mSettings.writeLPr();
18069            }
18070
18071            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18072                    + " after failed upgrade");
18073        }
18074    }
18075
18076    /**
18077     * Checks whether the parent or any of the child packages have a change shared
18078     * user. For a package to be a valid update the shred users of the parent and
18079     * the children should match. We may later support changing child shared users.
18080     * @param oldPkg The updated package.
18081     * @param newPkg The update package.
18082     * @return The shared user that change between the versions.
18083     */
18084    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18085            PackageParser.Package newPkg) {
18086        // Check parent shared user
18087        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18088            return newPkg.packageName;
18089        }
18090        // Check child shared users
18091        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18092        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18093        for (int i = 0; i < newChildCount; i++) {
18094            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18095            // If this child was present, did it have the same shared user?
18096            for (int j = 0; j < oldChildCount; j++) {
18097                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18098                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18099                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18100                    return newChildPkg.packageName;
18101                }
18102            }
18103        }
18104        return null;
18105    }
18106
18107    private void removeNativeBinariesLI(PackageSetting ps) {
18108        // Remove the lib path for the parent package
18109        if (ps != null) {
18110            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18111            // Remove the lib path for the child packages
18112            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18113            for (int i = 0; i < childCount; i++) {
18114                PackageSetting childPs = null;
18115                synchronized (mPackages) {
18116                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18117                }
18118                if (childPs != null) {
18119                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18120                            .legacyNativeLibraryPathString);
18121                }
18122            }
18123        }
18124    }
18125
18126    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18127        // Enable the parent package
18128        mSettings.enableSystemPackageLPw(pkg.packageName);
18129        // Enable the child packages
18130        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18131        for (int i = 0; i < childCount; i++) {
18132            PackageParser.Package childPkg = pkg.childPackages.get(i);
18133            mSettings.enableSystemPackageLPw(childPkg.packageName);
18134        }
18135    }
18136
18137    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18138            PackageParser.Package newPkg) {
18139        // Disable the parent package (parent always replaced)
18140        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18141        // Disable the child packages
18142        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18143        for (int i = 0; i < childCount; i++) {
18144            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18145            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18146            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18147        }
18148        return disabled;
18149    }
18150
18151    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18152            String installerPackageName) {
18153        // Enable the parent package
18154        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18155        // Enable the child packages
18156        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18157        for (int i = 0; i < childCount; i++) {
18158            PackageParser.Package childPkg = pkg.childPackages.get(i);
18159            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18160        }
18161    }
18162
18163    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18164        // Collect all used permissions in the UID
18165        ArraySet<String> usedPermissions = new ArraySet<>();
18166        final int packageCount = su.packages.size();
18167        for (int i = 0; i < packageCount; i++) {
18168            PackageSetting ps = su.packages.valueAt(i);
18169            if (ps.pkg == null) {
18170                continue;
18171            }
18172            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18173            for (int j = 0; j < requestedPermCount; j++) {
18174                String permission = ps.pkg.requestedPermissions.get(j);
18175                BasePermission bp = mSettings.mPermissions.get(permission);
18176                if (bp != null) {
18177                    usedPermissions.add(permission);
18178                }
18179            }
18180        }
18181
18182        PermissionsState permissionsState = su.getPermissionsState();
18183        // Prune install permissions
18184        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18185        final int installPermCount = installPermStates.size();
18186        for (int i = installPermCount - 1; i >= 0;  i--) {
18187            PermissionState permissionState = installPermStates.get(i);
18188            if (!usedPermissions.contains(permissionState.getName())) {
18189                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18190                if (bp != null) {
18191                    permissionsState.revokeInstallPermission(bp);
18192                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18193                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18194                }
18195            }
18196        }
18197
18198        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18199
18200        // Prune runtime permissions
18201        for (int userId : allUserIds) {
18202            List<PermissionState> runtimePermStates = permissionsState
18203                    .getRuntimePermissionStates(userId);
18204            final int runtimePermCount = runtimePermStates.size();
18205            for (int i = runtimePermCount - 1; i >= 0; i--) {
18206                PermissionState permissionState = runtimePermStates.get(i);
18207                if (!usedPermissions.contains(permissionState.getName())) {
18208                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18209                    if (bp != null) {
18210                        permissionsState.revokeRuntimePermission(bp, userId);
18211                        permissionsState.updatePermissionFlags(bp, userId,
18212                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18213                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18214                                runtimePermissionChangedUserIds, userId);
18215                    }
18216                }
18217            }
18218        }
18219
18220        return runtimePermissionChangedUserIds;
18221    }
18222
18223    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18224            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18225        // Update the parent package setting
18226        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18227                res, user, installReason);
18228        // Update the child packages setting
18229        final int childCount = (newPackage.childPackages != null)
18230                ? newPackage.childPackages.size() : 0;
18231        for (int i = 0; i < childCount; i++) {
18232            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18233            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18234            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18235                    childRes.origUsers, childRes, user, installReason);
18236        }
18237    }
18238
18239    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18240            String installerPackageName, int[] allUsers, int[] installedForUsers,
18241            PackageInstalledInfo res, UserHandle user, int installReason) {
18242        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18243
18244        String pkgName = newPackage.packageName;
18245        synchronized (mPackages) {
18246            //write settings. the installStatus will be incomplete at this stage.
18247            //note that the new package setting would have already been
18248            //added to mPackages. It hasn't been persisted yet.
18249            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18250            // TODO: Remove this write? It's also written at the end of this method
18251            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18252            mSettings.writeLPr();
18253            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18254        }
18255
18256        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18257        synchronized (mPackages) {
18258            updatePermissionsLPw(newPackage.packageName, newPackage,
18259                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18260                            ? UPDATE_PERMISSIONS_ALL : 0));
18261            // For system-bundled packages, we assume that installing an upgraded version
18262            // of the package implies that the user actually wants to run that new code,
18263            // so we enable the package.
18264            PackageSetting ps = mSettings.mPackages.get(pkgName);
18265            final int userId = user.getIdentifier();
18266            if (ps != null) {
18267                if (isSystemApp(newPackage)) {
18268                    if (DEBUG_INSTALL) {
18269                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18270                    }
18271                    // Enable system package for requested users
18272                    if (res.origUsers != null) {
18273                        for (int origUserId : res.origUsers) {
18274                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18275                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18276                                        origUserId, installerPackageName);
18277                            }
18278                        }
18279                    }
18280                    // Also convey the prior install/uninstall state
18281                    if (allUsers != null && installedForUsers != null) {
18282                        for (int currentUserId : allUsers) {
18283                            final boolean installed = ArrayUtils.contains(
18284                                    installedForUsers, currentUserId);
18285                            if (DEBUG_INSTALL) {
18286                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18287                            }
18288                            ps.setInstalled(installed, currentUserId);
18289                        }
18290                        // these install state changes will be persisted in the
18291                        // upcoming call to mSettings.writeLPr().
18292                    }
18293                }
18294                // It's implied that when a user requests installation, they want the app to be
18295                // installed and enabled.
18296                if (userId != UserHandle.USER_ALL) {
18297                    ps.setInstalled(true, userId);
18298                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18299                }
18300
18301                // When replacing an existing package, preserve the original install reason for all
18302                // users that had the package installed before.
18303                final Set<Integer> previousUserIds = new ArraySet<>();
18304                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18305                    final int installReasonCount = res.removedInfo.installReasons.size();
18306                    for (int i = 0; i < installReasonCount; i++) {
18307                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18308                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18309                        ps.setInstallReason(previousInstallReason, previousUserId);
18310                        previousUserIds.add(previousUserId);
18311                    }
18312                }
18313
18314                // Set install reason for users that are having the package newly installed.
18315                if (userId == UserHandle.USER_ALL) {
18316                    for (int currentUserId : sUserManager.getUserIds()) {
18317                        if (!previousUserIds.contains(currentUserId)) {
18318                            ps.setInstallReason(installReason, currentUserId);
18319                        }
18320                    }
18321                } else if (!previousUserIds.contains(userId)) {
18322                    ps.setInstallReason(installReason, userId);
18323                }
18324                mSettings.writeKernelMappingLPr(ps);
18325            }
18326            res.name = pkgName;
18327            res.uid = newPackage.applicationInfo.uid;
18328            res.pkg = newPackage;
18329            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18330            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18331            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18332            //to update install status
18333            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18334            mSettings.writeLPr();
18335            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18336        }
18337
18338        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18339    }
18340
18341    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18342        try {
18343            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18344            installPackageLI(args, res);
18345        } finally {
18346            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18347        }
18348    }
18349
18350    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18351        final int installFlags = args.installFlags;
18352        final String installerPackageName = args.installerPackageName;
18353        final String volumeUuid = args.volumeUuid;
18354        final File tmpPackageFile = new File(args.getCodePath());
18355        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18356        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18357                || (args.volumeUuid != null));
18358        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18359        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18360        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18361        final boolean virtualPreload =
18362                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18363        boolean replace = false;
18364        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18365        if (args.move != null) {
18366            // moving a complete application; perform an initial scan on the new install location
18367            scanFlags |= SCAN_INITIAL;
18368        }
18369        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18370            scanFlags |= SCAN_DONT_KILL_APP;
18371        }
18372        if (instantApp) {
18373            scanFlags |= SCAN_AS_INSTANT_APP;
18374        }
18375        if (fullApp) {
18376            scanFlags |= SCAN_AS_FULL_APP;
18377        }
18378        if (virtualPreload) {
18379            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18380        }
18381
18382        // Result object to be returned
18383        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18384        res.installerPackageName = installerPackageName;
18385
18386        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18387
18388        // Sanity check
18389        if (instantApp && (forwardLocked || onExternal)) {
18390            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18391                    + " external=" + onExternal);
18392            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18393            return;
18394        }
18395
18396        // Retrieve PackageSettings and parse package
18397        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18398                | PackageParser.PARSE_ENFORCE_CODE
18399                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18400                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18401                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18402                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18403        PackageParser pp = new PackageParser();
18404        pp.setSeparateProcesses(mSeparateProcesses);
18405        pp.setDisplayMetrics(mMetrics);
18406        pp.setCallback(mPackageParserCallback);
18407
18408        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18409        final PackageParser.Package pkg;
18410        try {
18411            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18412        } catch (PackageParserException e) {
18413            res.setError("Failed parse during installPackageLI", e);
18414            return;
18415        } finally {
18416            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18417        }
18418
18419        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18420        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18421            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18422            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18423                    "Instant app package must target O");
18424            return;
18425        }
18426        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18427            Slog.w(TAG, "Instant app package " + pkg.packageName
18428                    + " does not target targetSandboxVersion 2");
18429            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18430                    "Instant app package must use targetSanboxVersion 2");
18431            return;
18432        }
18433
18434        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18435            // Static shared libraries have synthetic package names
18436            renameStaticSharedLibraryPackage(pkg);
18437
18438            // No static shared libs on external storage
18439            if (onExternal) {
18440                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18441                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18442                        "Packages declaring static-shared libs cannot be updated");
18443                return;
18444            }
18445        }
18446
18447        // If we are installing a clustered package add results for the children
18448        if (pkg.childPackages != null) {
18449            synchronized (mPackages) {
18450                final int childCount = pkg.childPackages.size();
18451                for (int i = 0; i < childCount; i++) {
18452                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18453                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18454                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18455                    childRes.pkg = childPkg;
18456                    childRes.name = childPkg.packageName;
18457                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18458                    if (childPs != null) {
18459                        childRes.origUsers = childPs.queryInstalledUsers(
18460                                sUserManager.getUserIds(), true);
18461                    }
18462                    if ((mPackages.containsKey(childPkg.packageName))) {
18463                        childRes.removedInfo = new PackageRemovedInfo(this);
18464                        childRes.removedInfo.removedPackage = childPkg.packageName;
18465                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18466                    }
18467                    if (res.addedChildPackages == null) {
18468                        res.addedChildPackages = new ArrayMap<>();
18469                    }
18470                    res.addedChildPackages.put(childPkg.packageName, childRes);
18471                }
18472            }
18473        }
18474
18475        // If package doesn't declare API override, mark that we have an install
18476        // time CPU ABI override.
18477        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18478            pkg.cpuAbiOverride = args.abiOverride;
18479        }
18480
18481        String pkgName = res.name = pkg.packageName;
18482        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18483            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18484                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18485                return;
18486            }
18487        }
18488
18489        try {
18490            // either use what we've been given or parse directly from the APK
18491            if (args.certificates != null) {
18492                try {
18493                    PackageParser.populateCertificates(pkg, args.certificates);
18494                } catch (PackageParserException e) {
18495                    // there was something wrong with the certificates we were given;
18496                    // try to pull them from the APK
18497                    PackageParser.collectCertificates(pkg, parseFlags);
18498                }
18499            } else {
18500                PackageParser.collectCertificates(pkg, parseFlags);
18501            }
18502        } catch (PackageParserException e) {
18503            res.setError("Failed collect during installPackageLI", e);
18504            return;
18505        }
18506
18507        // Get rid of all references to package scan path via parser.
18508        pp = null;
18509        String oldCodePath = null;
18510        boolean systemApp = false;
18511        synchronized (mPackages) {
18512            // Check if installing already existing package
18513            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18514                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18515                if (pkg.mOriginalPackages != null
18516                        && pkg.mOriginalPackages.contains(oldName)
18517                        && mPackages.containsKey(oldName)) {
18518                    // This package is derived from an original package,
18519                    // and this device has been updating from that original
18520                    // name.  We must continue using the original name, so
18521                    // rename the new package here.
18522                    pkg.setPackageName(oldName);
18523                    pkgName = pkg.packageName;
18524                    replace = true;
18525                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18526                            + oldName + " pkgName=" + pkgName);
18527                } else if (mPackages.containsKey(pkgName)) {
18528                    // This package, under its official name, already exists
18529                    // on the device; we should replace it.
18530                    replace = true;
18531                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18532                }
18533
18534                // Child packages are installed through the parent package
18535                if (pkg.parentPackage != null) {
18536                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18537                            "Package " + pkg.packageName + " is child of package "
18538                                    + pkg.parentPackage.parentPackage + ". Child packages "
18539                                    + "can be updated only through the parent package.");
18540                    return;
18541                }
18542
18543                if (replace) {
18544                    // Prevent apps opting out from runtime permissions
18545                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18546                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18547                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18548                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18549                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18550                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18551                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18552                                        + " doesn't support runtime permissions but the old"
18553                                        + " target SDK " + oldTargetSdk + " does.");
18554                        return;
18555                    }
18556                    // Prevent apps from downgrading their targetSandbox.
18557                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18558                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18559                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18560                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18561                                "Package " + pkg.packageName + " new target sandbox "
18562                                + newTargetSandbox + " is incompatible with the previous value of"
18563                                + oldTargetSandbox + ".");
18564                        return;
18565                    }
18566
18567                    // Prevent installing of child packages
18568                    if (oldPackage.parentPackage != null) {
18569                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18570                                "Package " + pkg.packageName + " is child of package "
18571                                        + oldPackage.parentPackage + ". Child packages "
18572                                        + "can be updated only through the parent package.");
18573                        return;
18574                    }
18575                }
18576            }
18577
18578            PackageSetting ps = mSettings.mPackages.get(pkgName);
18579            if (ps != null) {
18580                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18581
18582                // Static shared libs have same package with different versions where
18583                // we internally use a synthetic package name to allow multiple versions
18584                // of the same package, therefore we need to compare signatures against
18585                // the package setting for the latest library version.
18586                PackageSetting signatureCheckPs = ps;
18587                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18588                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18589                    if (libraryEntry != null) {
18590                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18591                    }
18592                }
18593
18594                // Quick sanity check that we're signed correctly if updating;
18595                // we'll check this again later when scanning, but we want to
18596                // bail early here before tripping over redefined permissions.
18597                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18598                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18599                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18600                                + pkg.packageName + " upgrade keys do not match the "
18601                                + "previously installed version");
18602                        return;
18603                    }
18604                } else {
18605                    try {
18606                        verifySignaturesLP(signatureCheckPs, pkg);
18607                    } catch (PackageManagerException e) {
18608                        res.setError(e.error, e.getMessage());
18609                        return;
18610                    }
18611                }
18612
18613                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18614                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18615                    systemApp = (ps.pkg.applicationInfo.flags &
18616                            ApplicationInfo.FLAG_SYSTEM) != 0;
18617                }
18618                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18619            }
18620
18621            int N = pkg.permissions.size();
18622            for (int i = N-1; i >= 0; i--) {
18623                PackageParser.Permission perm = pkg.permissions.get(i);
18624                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18625
18626                // Don't allow anyone but the system to define ephemeral permissions.
18627                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18628                        && !systemApp) {
18629                    Slog.w(TAG, "Non-System package " + pkg.packageName
18630                            + " attempting to delcare ephemeral permission "
18631                            + perm.info.name + "; Removing ephemeral.");
18632                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18633                }
18634                // Check whether the newly-scanned package wants to define an already-defined perm
18635                if (bp != null) {
18636                    // If the defining package is signed with our cert, it's okay.  This
18637                    // also includes the "updating the same package" case, of course.
18638                    // "updating same package" could also involve key-rotation.
18639                    final boolean sigsOk;
18640                    if (bp.sourcePackage.equals(pkg.packageName)
18641                            && (bp.packageSetting instanceof PackageSetting)
18642                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18643                                    scanFlags))) {
18644                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18645                    } else {
18646                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18647                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18648                    }
18649                    if (!sigsOk) {
18650                        // If the owning package is the system itself, we log but allow
18651                        // install to proceed; we fail the install on all other permission
18652                        // redefinitions.
18653                        if (!bp.sourcePackage.equals("android")) {
18654                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18655                                    + pkg.packageName + " attempting to redeclare permission "
18656                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18657                            res.origPermission = perm.info.name;
18658                            res.origPackage = bp.sourcePackage;
18659                            return;
18660                        } else {
18661                            Slog.w(TAG, "Package " + pkg.packageName
18662                                    + " attempting to redeclare system permission "
18663                                    + perm.info.name + "; ignoring new declaration");
18664                            pkg.permissions.remove(i);
18665                        }
18666                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18667                        // Prevent apps to change protection level to dangerous from any other
18668                        // type as this would allow a privilege escalation where an app adds a
18669                        // normal/signature permission in other app's group and later redefines
18670                        // it as dangerous leading to the group auto-grant.
18671                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18672                                == PermissionInfo.PROTECTION_DANGEROUS) {
18673                            if (bp != null && !bp.isRuntime()) {
18674                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18675                                        + "non-runtime permission " + perm.info.name
18676                                        + " to runtime; keeping old protection level");
18677                                perm.info.protectionLevel = bp.protectionLevel;
18678                            }
18679                        }
18680                    }
18681                }
18682            }
18683        }
18684
18685        if (systemApp) {
18686            if (onExternal) {
18687                // Abort update; system app can't be replaced with app on sdcard
18688                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18689                        "Cannot install updates to system apps on sdcard");
18690                return;
18691            } else if (instantApp) {
18692                // Abort update; system app can't be replaced with an instant app
18693                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18694                        "Cannot update a system app with an instant app");
18695                return;
18696            }
18697        }
18698
18699        if (args.move != null) {
18700            // We did an in-place move, so dex is ready to roll
18701            scanFlags |= SCAN_NO_DEX;
18702            scanFlags |= SCAN_MOVE;
18703
18704            synchronized (mPackages) {
18705                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18706                if (ps == null) {
18707                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18708                            "Missing settings for moved package " + pkgName);
18709                }
18710
18711                // We moved the entire application as-is, so bring over the
18712                // previously derived ABI information.
18713                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18714                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18715            }
18716
18717        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18718            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18719            scanFlags |= SCAN_NO_DEX;
18720
18721            try {
18722                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18723                    args.abiOverride : pkg.cpuAbiOverride);
18724                final boolean extractNativeLibs = !pkg.isLibrary();
18725                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18726                        extractNativeLibs, mAppLib32InstallDir);
18727            } catch (PackageManagerException pme) {
18728                Slog.e(TAG, "Error deriving application ABI", pme);
18729                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18730                return;
18731            }
18732
18733            // Shared libraries for the package need to be updated.
18734            synchronized (mPackages) {
18735                try {
18736                    updateSharedLibrariesLPr(pkg, null);
18737                } catch (PackageManagerException e) {
18738                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18739                }
18740            }
18741        }
18742
18743        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18744            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18745            return;
18746        }
18747
18748        // Verify if we need to dexopt the app.
18749        //
18750        // NOTE: it is *important* to call dexopt after doRename which will sync the
18751        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18752        //
18753        // We only need to dexopt if the package meets ALL of the following conditions:
18754        //   1) it is not forward locked.
18755        //   2) it is not on on an external ASEC container.
18756        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18757        //
18758        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18759        // complete, so we skip this step during installation. Instead, we'll take extra time
18760        // the first time the instant app starts. It's preferred to do it this way to provide
18761        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18762        // middle of running an instant app. The default behaviour can be overridden
18763        // via gservices.
18764        final boolean performDexopt = !forwardLocked
18765            && !pkg.applicationInfo.isExternalAsec()
18766            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18767                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18768
18769        if (performDexopt) {
18770            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18771            // Do not run PackageDexOptimizer through the local performDexOpt
18772            // method because `pkg` may not be in `mPackages` yet.
18773            //
18774            // Also, don't fail application installs if the dexopt step fails.
18775            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18776                REASON_INSTALL,
18777                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18778            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18779                null /* instructionSets */,
18780                getOrCreateCompilerPackageStats(pkg),
18781                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18782                dexoptOptions);
18783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18784        }
18785
18786        // Notify BackgroundDexOptService that the package has been changed.
18787        // If this is an update of a package which used to fail to compile,
18788        // BackgroundDexOptService will remove it from its blacklist.
18789        // TODO: Layering violation
18790        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18791
18792        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18793
18794        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18795                "installPackageLI")) {
18796            if (replace) {
18797                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18798                    // Static libs have a synthetic package name containing the version
18799                    // and cannot be updated as an update would get a new package name,
18800                    // unless this is the exact same version code which is useful for
18801                    // development.
18802                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18803                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18804                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18805                                + "static-shared libs cannot be updated");
18806                        return;
18807                    }
18808                }
18809                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18810                        installerPackageName, res, args.installReason);
18811            } else {
18812                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18813                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18814            }
18815        }
18816
18817        synchronized (mPackages) {
18818            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18819            if (ps != null) {
18820                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18821                ps.setUpdateAvailable(false /*updateAvailable*/);
18822            }
18823
18824            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18825            for (int i = 0; i < childCount; i++) {
18826                PackageParser.Package childPkg = pkg.childPackages.get(i);
18827                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18828                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18829                if (childPs != null) {
18830                    childRes.newUsers = childPs.queryInstalledUsers(
18831                            sUserManager.getUserIds(), true);
18832                }
18833            }
18834
18835            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18836                updateSequenceNumberLP(ps, res.newUsers);
18837                updateInstantAppInstallerLocked(pkgName);
18838            }
18839        }
18840    }
18841
18842    private void startIntentFilterVerifications(int userId, boolean replacing,
18843            PackageParser.Package pkg) {
18844        if (mIntentFilterVerifierComponent == null) {
18845            Slog.w(TAG, "No IntentFilter verification will not be done as "
18846                    + "there is no IntentFilterVerifier available!");
18847            return;
18848        }
18849
18850        final int verifierUid = getPackageUid(
18851                mIntentFilterVerifierComponent.getPackageName(),
18852                MATCH_DEBUG_TRIAGED_MISSING,
18853                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18854
18855        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18856        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18857        mHandler.sendMessage(msg);
18858
18859        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18860        for (int i = 0; i < childCount; i++) {
18861            PackageParser.Package childPkg = pkg.childPackages.get(i);
18862            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18863            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18864            mHandler.sendMessage(msg);
18865        }
18866    }
18867
18868    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18869            PackageParser.Package pkg) {
18870        int size = pkg.activities.size();
18871        if (size == 0) {
18872            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18873                    "No activity, so no need to verify any IntentFilter!");
18874            return;
18875        }
18876
18877        final boolean hasDomainURLs = hasDomainURLs(pkg);
18878        if (!hasDomainURLs) {
18879            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18880                    "No domain URLs, so no need to verify any IntentFilter!");
18881            return;
18882        }
18883
18884        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18885                + " if any IntentFilter from the " + size
18886                + " Activities needs verification ...");
18887
18888        int count = 0;
18889        final String packageName = pkg.packageName;
18890
18891        synchronized (mPackages) {
18892            // If this is a new install and we see that we've already run verification for this
18893            // package, we have nothing to do: it means the state was restored from backup.
18894            if (!replacing) {
18895                IntentFilterVerificationInfo ivi =
18896                        mSettings.getIntentFilterVerificationLPr(packageName);
18897                if (ivi != null) {
18898                    if (DEBUG_DOMAIN_VERIFICATION) {
18899                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18900                                + ivi.getStatusString());
18901                    }
18902                    return;
18903                }
18904            }
18905
18906            // If any filters need to be verified, then all need to be.
18907            boolean needToVerify = false;
18908            for (PackageParser.Activity a : pkg.activities) {
18909                for (ActivityIntentInfo filter : a.intents) {
18910                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18911                        if (DEBUG_DOMAIN_VERIFICATION) {
18912                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18913                        }
18914                        needToVerify = true;
18915                        break;
18916                    }
18917                }
18918            }
18919
18920            if (needToVerify) {
18921                final int verificationId = mIntentFilterVerificationToken++;
18922                for (PackageParser.Activity a : pkg.activities) {
18923                    for (ActivityIntentInfo filter : a.intents) {
18924                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18925                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18926                                    "Verification needed for IntentFilter:" + filter.toString());
18927                            mIntentFilterVerifier.addOneIntentFilterVerification(
18928                                    verifierUid, userId, verificationId, filter, packageName);
18929                            count++;
18930                        }
18931                    }
18932                }
18933            }
18934        }
18935
18936        if (count > 0) {
18937            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18938                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18939                    +  " for userId:" + userId);
18940            mIntentFilterVerifier.startVerifications(userId);
18941        } else {
18942            if (DEBUG_DOMAIN_VERIFICATION) {
18943                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18944            }
18945        }
18946    }
18947
18948    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18949        final ComponentName cn  = filter.activity.getComponentName();
18950        final String packageName = cn.getPackageName();
18951
18952        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18953                packageName);
18954        if (ivi == null) {
18955            return true;
18956        }
18957        int status = ivi.getStatus();
18958        switch (status) {
18959            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18960            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18961                return true;
18962
18963            default:
18964                // Nothing to do
18965                return false;
18966        }
18967    }
18968
18969    private static boolean isMultiArch(ApplicationInfo info) {
18970        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18971    }
18972
18973    private static boolean isExternal(PackageParser.Package pkg) {
18974        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18975    }
18976
18977    private static boolean isExternal(PackageSetting ps) {
18978        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18979    }
18980
18981    private static boolean isSystemApp(PackageParser.Package pkg) {
18982        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18983    }
18984
18985    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18986        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18987    }
18988
18989    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18990        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18991    }
18992
18993    private static boolean isSystemApp(PackageSetting ps) {
18994        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18995    }
18996
18997    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18998        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18999    }
19000
19001    private int packageFlagsToInstallFlags(PackageSetting ps) {
19002        int installFlags = 0;
19003        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
19004            // This existing package was an external ASEC install when we have
19005            // the external flag without a UUID
19006            installFlags |= PackageManager.INSTALL_EXTERNAL;
19007        }
19008        if (ps.isForwardLocked()) {
19009            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
19010        }
19011        return installFlags;
19012    }
19013
19014    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19015        if (isExternal(pkg)) {
19016            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19017                return StorageManager.UUID_PRIMARY_PHYSICAL;
19018            } else {
19019                return pkg.volumeUuid;
19020            }
19021        } else {
19022            return StorageManager.UUID_PRIVATE_INTERNAL;
19023        }
19024    }
19025
19026    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19027        if (isExternal(pkg)) {
19028            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19029                return mSettings.getExternalVersion();
19030            } else {
19031                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19032            }
19033        } else {
19034            return mSettings.getInternalVersion();
19035        }
19036    }
19037
19038    private void deleteTempPackageFiles() {
19039        final FilenameFilter filter = new FilenameFilter() {
19040            public boolean accept(File dir, String name) {
19041                return name.startsWith("vmdl") && name.endsWith(".tmp");
19042            }
19043        };
19044        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19045            file.delete();
19046        }
19047    }
19048
19049    @Override
19050    public void deletePackageAsUser(String packageName, int versionCode,
19051            IPackageDeleteObserver observer, int userId, int flags) {
19052        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19053                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19054    }
19055
19056    @Override
19057    public void deletePackageVersioned(VersionedPackage versionedPackage,
19058            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19059        final int callingUid = Binder.getCallingUid();
19060        mContext.enforceCallingOrSelfPermission(
19061                android.Manifest.permission.DELETE_PACKAGES, null);
19062        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19063        Preconditions.checkNotNull(versionedPackage);
19064        Preconditions.checkNotNull(observer);
19065        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19066                PackageManager.VERSION_CODE_HIGHEST,
19067                Integer.MAX_VALUE, "versionCode must be >= -1");
19068
19069        final String packageName = versionedPackage.getPackageName();
19070        final int versionCode = versionedPackage.getVersionCode();
19071        final String internalPackageName;
19072        synchronized (mPackages) {
19073            // Normalize package name to handle renamed packages and static libs
19074            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19075                    versionedPackage.getVersionCode());
19076        }
19077
19078        final int uid = Binder.getCallingUid();
19079        if (!isOrphaned(internalPackageName)
19080                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19081            try {
19082                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19083                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19084                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19085                observer.onUserActionRequired(intent);
19086            } catch (RemoteException re) {
19087            }
19088            return;
19089        }
19090        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19091        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19092        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19093            mContext.enforceCallingOrSelfPermission(
19094                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19095                    "deletePackage for user " + userId);
19096        }
19097
19098        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19099            try {
19100                observer.onPackageDeleted(packageName,
19101                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19102            } catch (RemoteException re) {
19103            }
19104            return;
19105        }
19106
19107        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19108            try {
19109                observer.onPackageDeleted(packageName,
19110                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19111            } catch (RemoteException re) {
19112            }
19113            return;
19114        }
19115
19116        if (DEBUG_REMOVE) {
19117            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19118                    + " deleteAllUsers: " + deleteAllUsers + " version="
19119                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19120                    ? "VERSION_CODE_HIGHEST" : versionCode));
19121        }
19122        // Queue up an async operation since the package deletion may take a little while.
19123        mHandler.post(new Runnable() {
19124            public void run() {
19125                mHandler.removeCallbacks(this);
19126                int returnCode;
19127                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19128                boolean doDeletePackage = true;
19129                if (ps != null) {
19130                    final boolean targetIsInstantApp =
19131                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19132                    doDeletePackage = !targetIsInstantApp
19133                            || canViewInstantApps;
19134                }
19135                if (doDeletePackage) {
19136                    if (!deleteAllUsers) {
19137                        returnCode = deletePackageX(internalPackageName, versionCode,
19138                                userId, deleteFlags);
19139                    } else {
19140                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19141                                internalPackageName, users);
19142                        // If nobody is blocking uninstall, proceed with delete for all users
19143                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19144                            returnCode = deletePackageX(internalPackageName, versionCode,
19145                                    userId, deleteFlags);
19146                        } else {
19147                            // Otherwise uninstall individually for users with blockUninstalls=false
19148                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19149                            for (int userId : users) {
19150                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19151                                    returnCode = deletePackageX(internalPackageName, versionCode,
19152                                            userId, userFlags);
19153                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19154                                        Slog.w(TAG, "Package delete failed for user " + userId
19155                                                + ", returnCode " + returnCode);
19156                                    }
19157                                }
19158                            }
19159                            // The app has only been marked uninstalled for certain users.
19160                            // We still need to report that delete was blocked
19161                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19162                        }
19163                    }
19164                } else {
19165                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19166                }
19167                try {
19168                    observer.onPackageDeleted(packageName, returnCode, null);
19169                } catch (RemoteException e) {
19170                    Log.i(TAG, "Observer no longer exists.");
19171                } //end catch
19172            } //end run
19173        });
19174    }
19175
19176    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19177        if (pkg.staticSharedLibName != null) {
19178            return pkg.manifestPackageName;
19179        }
19180        return pkg.packageName;
19181    }
19182
19183    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19184        // Handle renamed packages
19185        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19186        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19187
19188        // Is this a static library?
19189        SparseArray<SharedLibraryEntry> versionedLib =
19190                mStaticLibsByDeclaringPackage.get(packageName);
19191        if (versionedLib == null || versionedLib.size() <= 0) {
19192            return packageName;
19193        }
19194
19195        // Figure out which lib versions the caller can see
19196        SparseIntArray versionsCallerCanSee = null;
19197        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19198        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19199                && callingAppId != Process.ROOT_UID) {
19200            versionsCallerCanSee = new SparseIntArray();
19201            String libName = versionedLib.valueAt(0).info.getName();
19202            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19203            if (uidPackages != null) {
19204                for (String uidPackage : uidPackages) {
19205                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19206                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19207                    if (libIdx >= 0) {
19208                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19209                        versionsCallerCanSee.append(libVersion, libVersion);
19210                    }
19211                }
19212            }
19213        }
19214
19215        // Caller can see nothing - done
19216        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19217            return packageName;
19218        }
19219
19220        // Find the version the caller can see and the app version code
19221        SharedLibraryEntry highestVersion = null;
19222        final int versionCount = versionedLib.size();
19223        for (int i = 0; i < versionCount; i++) {
19224            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19225            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19226                    libEntry.info.getVersion()) < 0) {
19227                continue;
19228            }
19229            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19230            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19231                if (libVersionCode == versionCode) {
19232                    return libEntry.apk;
19233                }
19234            } else if (highestVersion == null) {
19235                highestVersion = libEntry;
19236            } else if (libVersionCode  > highestVersion.info
19237                    .getDeclaringPackage().getVersionCode()) {
19238                highestVersion = libEntry;
19239            }
19240        }
19241
19242        if (highestVersion != null) {
19243            return highestVersion.apk;
19244        }
19245
19246        return packageName;
19247    }
19248
19249    boolean isCallerVerifier(int callingUid) {
19250        final int callingUserId = UserHandle.getUserId(callingUid);
19251        return mRequiredVerifierPackage != null &&
19252                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19253    }
19254
19255    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19256        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19257              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19258            return true;
19259        }
19260        final int callingUserId = UserHandle.getUserId(callingUid);
19261        // If the caller installed the pkgName, then allow it to silently uninstall.
19262        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19263            return true;
19264        }
19265
19266        // Allow package verifier to silently uninstall.
19267        if (mRequiredVerifierPackage != null &&
19268                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19269            return true;
19270        }
19271
19272        // Allow package uninstaller to silently uninstall.
19273        if (mRequiredUninstallerPackage != null &&
19274                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19275            return true;
19276        }
19277
19278        // Allow storage manager to silently uninstall.
19279        if (mStorageManagerPackage != null &&
19280                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19281            return true;
19282        }
19283
19284        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19285        // uninstall for device owner provisioning.
19286        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19287                == PERMISSION_GRANTED) {
19288            return true;
19289        }
19290
19291        return false;
19292    }
19293
19294    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19295        int[] result = EMPTY_INT_ARRAY;
19296        for (int userId : userIds) {
19297            if (getBlockUninstallForUser(packageName, userId)) {
19298                result = ArrayUtils.appendInt(result, userId);
19299            }
19300        }
19301        return result;
19302    }
19303
19304    @Override
19305    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19306        final int callingUid = Binder.getCallingUid();
19307        if (getInstantAppPackageName(callingUid) != null
19308                && !isCallerSameApp(packageName, callingUid)) {
19309            return false;
19310        }
19311        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19312    }
19313
19314    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19315        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19316                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19317        try {
19318            if (dpm != null) {
19319                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19320                        /* callingUserOnly =*/ false);
19321                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19322                        : deviceOwnerComponentName.getPackageName();
19323                // Does the package contains the device owner?
19324                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19325                // this check is probably not needed, since DO should be registered as a device
19326                // admin on some user too. (Original bug for this: b/17657954)
19327                if (packageName.equals(deviceOwnerPackageName)) {
19328                    return true;
19329                }
19330                // Does it contain a device admin for any user?
19331                int[] users;
19332                if (userId == UserHandle.USER_ALL) {
19333                    users = sUserManager.getUserIds();
19334                } else {
19335                    users = new int[]{userId};
19336                }
19337                for (int i = 0; i < users.length; ++i) {
19338                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19339                        return true;
19340                    }
19341                }
19342            }
19343        } catch (RemoteException e) {
19344        }
19345        return false;
19346    }
19347
19348    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19349        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19350    }
19351
19352    /**
19353     *  This method is an internal method that could be get invoked either
19354     *  to delete an installed package or to clean up a failed installation.
19355     *  After deleting an installed package, a broadcast is sent to notify any
19356     *  listeners that the package has been removed. For cleaning up a failed
19357     *  installation, the broadcast is not necessary since the package's
19358     *  installation wouldn't have sent the initial broadcast either
19359     *  The key steps in deleting a package are
19360     *  deleting the package information in internal structures like mPackages,
19361     *  deleting the packages base directories through installd
19362     *  updating mSettings to reflect current status
19363     *  persisting settings for later use
19364     *  sending a broadcast if necessary
19365     */
19366    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19367        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19368        final boolean res;
19369
19370        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19371                ? UserHandle.USER_ALL : userId;
19372
19373        if (isPackageDeviceAdmin(packageName, removeUser)) {
19374            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19375            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19376        }
19377
19378        PackageSetting uninstalledPs = null;
19379        PackageParser.Package pkg = null;
19380
19381        // for the uninstall-updates case and restricted profiles, remember the per-
19382        // user handle installed state
19383        int[] allUsers;
19384        synchronized (mPackages) {
19385            uninstalledPs = mSettings.mPackages.get(packageName);
19386            if (uninstalledPs == null) {
19387                Slog.w(TAG, "Not removing non-existent package " + packageName);
19388                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19389            }
19390
19391            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19392                    && uninstalledPs.versionCode != versionCode) {
19393                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19394                        + uninstalledPs.versionCode + " != " + versionCode);
19395                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19396            }
19397
19398            // Static shared libs can be declared by any package, so let us not
19399            // allow removing a package if it provides a lib others depend on.
19400            pkg = mPackages.get(packageName);
19401
19402            allUsers = sUserManager.getUserIds();
19403
19404            if (pkg != null && pkg.staticSharedLibName != null) {
19405                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19406                        pkg.staticSharedLibVersion);
19407                if (libEntry != null) {
19408                    for (int currUserId : allUsers) {
19409                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19410                            continue;
19411                        }
19412                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19413                                libEntry.info, 0, currUserId);
19414                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19415                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19416                                    + " hosting lib " + libEntry.info.getName() + " version "
19417                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19418                                    + " for user " + currUserId);
19419                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19420                        }
19421                    }
19422                }
19423            }
19424
19425            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19426        }
19427
19428        final int freezeUser;
19429        if (isUpdatedSystemApp(uninstalledPs)
19430                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19431            // We're downgrading a system app, which will apply to all users, so
19432            // freeze them all during the downgrade
19433            freezeUser = UserHandle.USER_ALL;
19434        } else {
19435            freezeUser = removeUser;
19436        }
19437
19438        synchronized (mInstallLock) {
19439            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19440            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19441                    deleteFlags, "deletePackageX")) {
19442                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19443                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19444            }
19445            synchronized (mPackages) {
19446                if (res) {
19447                    if (pkg != null) {
19448                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19449                    }
19450                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19451                    updateInstantAppInstallerLocked(packageName);
19452                }
19453            }
19454        }
19455
19456        if (res) {
19457            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19458            info.sendPackageRemovedBroadcasts(killApp);
19459            info.sendSystemPackageUpdatedBroadcasts();
19460            info.sendSystemPackageAppearedBroadcasts();
19461        }
19462        // Force a gc here.
19463        Runtime.getRuntime().gc();
19464        // Delete the resources here after sending the broadcast to let
19465        // other processes clean up before deleting resources.
19466        if (info.args != null) {
19467            synchronized (mInstallLock) {
19468                info.args.doPostDeleteLI(true);
19469            }
19470        }
19471
19472        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19473    }
19474
19475    static class PackageRemovedInfo {
19476        final PackageSender packageSender;
19477        String removedPackage;
19478        String installerPackageName;
19479        int uid = -1;
19480        int removedAppId = -1;
19481        int[] origUsers;
19482        int[] removedUsers = null;
19483        int[] broadcastUsers = null;
19484        SparseArray<Integer> installReasons;
19485        boolean isRemovedPackageSystemUpdate = false;
19486        boolean isUpdate;
19487        boolean dataRemoved;
19488        boolean removedForAllUsers;
19489        boolean isStaticSharedLib;
19490        // Clean up resources deleted packages.
19491        InstallArgs args = null;
19492        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19493        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19494
19495        PackageRemovedInfo(PackageSender packageSender) {
19496            this.packageSender = packageSender;
19497        }
19498
19499        void sendPackageRemovedBroadcasts(boolean killApp) {
19500            sendPackageRemovedBroadcastInternal(killApp);
19501            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19502            for (int i = 0; i < childCount; i++) {
19503                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19504                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19505            }
19506        }
19507
19508        void sendSystemPackageUpdatedBroadcasts() {
19509            if (isRemovedPackageSystemUpdate) {
19510                sendSystemPackageUpdatedBroadcastsInternal();
19511                final int childCount = (removedChildPackages != null)
19512                        ? removedChildPackages.size() : 0;
19513                for (int i = 0; i < childCount; i++) {
19514                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19515                    if (childInfo.isRemovedPackageSystemUpdate) {
19516                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19517                    }
19518                }
19519            }
19520        }
19521
19522        void sendSystemPackageAppearedBroadcasts() {
19523            final int packageCount = (appearedChildPackages != null)
19524                    ? appearedChildPackages.size() : 0;
19525            for (int i = 0; i < packageCount; i++) {
19526                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19527                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19528                    true /*sendBootCompleted*/, false /*startReceiver*/,
19529                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19530            }
19531        }
19532
19533        private void sendSystemPackageUpdatedBroadcastsInternal() {
19534            Bundle extras = new Bundle(2);
19535            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19536            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19537            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19538                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19539            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19540                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19541            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19542                null, null, 0, removedPackage, null, null);
19543            if (installerPackageName != null) {
19544                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19545                        removedPackage, extras, 0 /*flags*/,
19546                        installerPackageName, null, null);
19547                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19548                        removedPackage, extras, 0 /*flags*/,
19549                        installerPackageName, null, null);
19550            }
19551        }
19552
19553        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19554            // Don't send static shared library removal broadcasts as these
19555            // libs are visible only the the apps that depend on them an one
19556            // cannot remove the library if it has a dependency.
19557            if (isStaticSharedLib) {
19558                return;
19559            }
19560            Bundle extras = new Bundle(2);
19561            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19562            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19563            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19564            if (isUpdate || isRemovedPackageSystemUpdate) {
19565                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19566            }
19567            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19568            if (removedPackage != null) {
19569                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19570                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19571                if (installerPackageName != null) {
19572                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19573                            removedPackage, extras, 0 /*flags*/,
19574                            installerPackageName, null, broadcastUsers);
19575                }
19576                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19577                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19578                        removedPackage, extras,
19579                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19580                        null, null, broadcastUsers);
19581                }
19582            }
19583            if (removedAppId >= 0) {
19584                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19585                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19586                    null, null, broadcastUsers);
19587            }
19588        }
19589
19590        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19591            removedUsers = userIds;
19592            if (removedUsers == null) {
19593                broadcastUsers = null;
19594                return;
19595            }
19596
19597            broadcastUsers = EMPTY_INT_ARRAY;
19598            for (int i = userIds.length - 1; i >= 0; --i) {
19599                final int userId = userIds[i];
19600                if (deletedPackageSetting.getInstantApp(userId)) {
19601                    continue;
19602                }
19603                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19604            }
19605        }
19606    }
19607
19608    /*
19609     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19610     * flag is not set, the data directory is removed as well.
19611     * make sure this flag is set for partially installed apps. If not its meaningless to
19612     * delete a partially installed application.
19613     */
19614    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19615            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19616        String packageName = ps.name;
19617        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19618        // Retrieve object to delete permissions for shared user later on
19619        final PackageParser.Package deletedPkg;
19620        final PackageSetting deletedPs;
19621        // reader
19622        synchronized (mPackages) {
19623            deletedPkg = mPackages.get(packageName);
19624            deletedPs = mSettings.mPackages.get(packageName);
19625            if (outInfo != null) {
19626                outInfo.removedPackage = packageName;
19627                outInfo.installerPackageName = ps.installerPackageName;
19628                outInfo.isStaticSharedLib = deletedPkg != null
19629                        && deletedPkg.staticSharedLibName != null;
19630                outInfo.populateUsers(deletedPs == null ? null
19631                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19632            }
19633        }
19634
19635        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19636
19637        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19638            final PackageParser.Package resolvedPkg;
19639            if (deletedPkg != null) {
19640                resolvedPkg = deletedPkg;
19641            } else {
19642                // We don't have a parsed package when it lives on an ejected
19643                // adopted storage device, so fake something together
19644                resolvedPkg = new PackageParser.Package(ps.name);
19645                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19646            }
19647            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19648                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19649            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19650            if (outInfo != null) {
19651                outInfo.dataRemoved = true;
19652            }
19653            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19654        }
19655
19656        int removedAppId = -1;
19657
19658        // writer
19659        synchronized (mPackages) {
19660            boolean installedStateChanged = false;
19661            if (deletedPs != null) {
19662                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19663                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19664                    clearDefaultBrowserIfNeeded(packageName);
19665                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19666                    removedAppId = mSettings.removePackageLPw(packageName);
19667                    if (outInfo != null) {
19668                        outInfo.removedAppId = removedAppId;
19669                    }
19670                    updatePermissionsLPw(deletedPs.name, null, 0);
19671                    if (deletedPs.sharedUser != null) {
19672                        // Remove permissions associated with package. Since runtime
19673                        // permissions are per user we have to kill the removed package
19674                        // or packages running under the shared user of the removed
19675                        // package if revoking the permissions requested only by the removed
19676                        // package is successful and this causes a change in gids.
19677                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19678                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19679                                    userId);
19680                            if (userIdToKill == UserHandle.USER_ALL
19681                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19682                                // If gids changed for this user, kill all affected packages.
19683                                mHandler.post(new Runnable() {
19684                                    @Override
19685                                    public void run() {
19686                                        // This has to happen with no lock held.
19687                                        killApplication(deletedPs.name, deletedPs.appId,
19688                                                KILL_APP_REASON_GIDS_CHANGED);
19689                                    }
19690                                });
19691                                break;
19692                            }
19693                        }
19694                    }
19695                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19696                }
19697                // make sure to preserve per-user disabled state if this removal was just
19698                // a downgrade of a system app to the factory package
19699                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19700                    if (DEBUG_REMOVE) {
19701                        Slog.d(TAG, "Propagating install state across downgrade");
19702                    }
19703                    for (int userId : allUserHandles) {
19704                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19705                        if (DEBUG_REMOVE) {
19706                            Slog.d(TAG, "    user " + userId + " => " + installed);
19707                        }
19708                        if (installed != ps.getInstalled(userId)) {
19709                            installedStateChanged = true;
19710                        }
19711                        ps.setInstalled(installed, userId);
19712                    }
19713                }
19714            }
19715            // can downgrade to reader
19716            if (writeSettings) {
19717                // Save settings now
19718                mSettings.writeLPr();
19719            }
19720            if (installedStateChanged) {
19721                mSettings.writeKernelMappingLPr(ps);
19722            }
19723        }
19724        if (removedAppId != -1) {
19725            // A user ID was deleted here. Go through all users and remove it
19726            // from KeyStore.
19727            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19728        }
19729    }
19730
19731    static boolean locationIsPrivileged(File path) {
19732        try {
19733            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19734                    .getCanonicalPath();
19735            return path.getCanonicalPath().startsWith(privilegedAppDir);
19736        } catch (IOException e) {
19737            Slog.e(TAG, "Unable to access code path " + path);
19738        }
19739        return false;
19740    }
19741
19742    /*
19743     * Tries to delete system package.
19744     */
19745    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19746            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19747            boolean writeSettings) {
19748        if (deletedPs.parentPackageName != null) {
19749            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19750            return false;
19751        }
19752
19753        final boolean applyUserRestrictions
19754                = (allUserHandles != null) && (outInfo.origUsers != null);
19755        final PackageSetting disabledPs;
19756        // Confirm if the system package has been updated
19757        // An updated system app can be deleted. This will also have to restore
19758        // the system pkg from system partition
19759        // reader
19760        synchronized (mPackages) {
19761            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19762        }
19763
19764        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19765                + " disabledPs=" + disabledPs);
19766
19767        if (disabledPs == null) {
19768            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19769            return false;
19770        } else if (DEBUG_REMOVE) {
19771            Slog.d(TAG, "Deleting system pkg from data partition");
19772        }
19773
19774        if (DEBUG_REMOVE) {
19775            if (applyUserRestrictions) {
19776                Slog.d(TAG, "Remembering install states:");
19777                for (int userId : allUserHandles) {
19778                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19779                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19780                }
19781            }
19782        }
19783
19784        // Delete the updated package
19785        outInfo.isRemovedPackageSystemUpdate = true;
19786        if (outInfo.removedChildPackages != null) {
19787            final int childCount = (deletedPs.childPackageNames != null)
19788                    ? deletedPs.childPackageNames.size() : 0;
19789            for (int i = 0; i < childCount; i++) {
19790                String childPackageName = deletedPs.childPackageNames.get(i);
19791                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19792                        .contains(childPackageName)) {
19793                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19794                            childPackageName);
19795                    if (childInfo != null) {
19796                        childInfo.isRemovedPackageSystemUpdate = true;
19797                    }
19798                }
19799            }
19800        }
19801
19802        if (disabledPs.versionCode < deletedPs.versionCode) {
19803            // Delete data for downgrades
19804            flags &= ~PackageManager.DELETE_KEEP_DATA;
19805        } else {
19806            // Preserve data by setting flag
19807            flags |= PackageManager.DELETE_KEEP_DATA;
19808        }
19809
19810        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19811                outInfo, writeSettings, disabledPs.pkg);
19812        if (!ret) {
19813            return false;
19814        }
19815
19816        // writer
19817        synchronized (mPackages) {
19818            // NOTE: The system package always needs to be enabled; even if it's for
19819            // a compressed stub. If we don't, installing the system package fails
19820            // during scan [scanning checks the disabled packages]. We will reverse
19821            // this later, after we've "installed" the stub.
19822            // Reinstate the old system package
19823            enableSystemPackageLPw(disabledPs.pkg);
19824            // Remove any native libraries from the upgraded package.
19825            removeNativeBinariesLI(deletedPs);
19826        }
19827
19828        // Install the system package
19829        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19830        try {
19831            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19832                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19833        } catch (PackageManagerException e) {
19834            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19835                    + e.getMessage());
19836            return false;
19837        } finally {
19838            if (disabledPs.pkg.isStub) {
19839                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19840            }
19841        }
19842        return true;
19843    }
19844
19845    /**
19846     * Installs a package that's already on the system partition.
19847     */
19848    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19849            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19850            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19851                    throws PackageManagerException {
19852        int parseFlags = mDefParseFlags
19853                | PackageParser.PARSE_MUST_BE_APK
19854                | PackageParser.PARSE_IS_SYSTEM
19855                | PackageParser.PARSE_IS_SYSTEM_DIR;
19856        if (isPrivileged || locationIsPrivileged(codePath)) {
19857            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19858        }
19859
19860        final PackageParser.Package newPkg =
19861                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19862
19863        try {
19864            // update shared libraries for the newly re-installed system package
19865            updateSharedLibrariesLPr(newPkg, null);
19866        } catch (PackageManagerException e) {
19867            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19868        }
19869
19870        prepareAppDataAfterInstallLIF(newPkg);
19871
19872        // writer
19873        synchronized (mPackages) {
19874            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19875
19876            // Propagate the permissions state as we do not want to drop on the floor
19877            // runtime permissions. The update permissions method below will take
19878            // care of removing obsolete permissions and grant install permissions.
19879            if (origPermissionState != null) {
19880                ps.getPermissionsState().copyFrom(origPermissionState);
19881            }
19882            updatePermissionsLPw(newPkg.packageName, newPkg,
19883                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19884
19885            final boolean applyUserRestrictions
19886                    = (allUserHandles != null) && (origUserHandles != null);
19887            if (applyUserRestrictions) {
19888                boolean installedStateChanged = false;
19889                if (DEBUG_REMOVE) {
19890                    Slog.d(TAG, "Propagating install state across reinstall");
19891                }
19892                for (int userId : allUserHandles) {
19893                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19894                    if (DEBUG_REMOVE) {
19895                        Slog.d(TAG, "    user " + userId + " => " + installed);
19896                    }
19897                    if (installed != ps.getInstalled(userId)) {
19898                        installedStateChanged = true;
19899                    }
19900                    ps.setInstalled(installed, userId);
19901
19902                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19903                }
19904                // Regardless of writeSettings we need to ensure that this restriction
19905                // state propagation is persisted
19906                mSettings.writeAllUsersPackageRestrictionsLPr();
19907                if (installedStateChanged) {
19908                    mSettings.writeKernelMappingLPr(ps);
19909                }
19910            }
19911            // can downgrade to reader here
19912            if (writeSettings) {
19913                mSettings.writeLPr();
19914            }
19915        }
19916        return newPkg;
19917    }
19918
19919    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19920            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19921            PackageRemovedInfo outInfo, boolean writeSettings,
19922            PackageParser.Package replacingPackage) {
19923        synchronized (mPackages) {
19924            if (outInfo != null) {
19925                outInfo.uid = ps.appId;
19926            }
19927
19928            if (outInfo != null && outInfo.removedChildPackages != null) {
19929                final int childCount = (ps.childPackageNames != null)
19930                        ? ps.childPackageNames.size() : 0;
19931                for (int i = 0; i < childCount; i++) {
19932                    String childPackageName = ps.childPackageNames.get(i);
19933                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19934                    if (childPs == null) {
19935                        return false;
19936                    }
19937                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19938                            childPackageName);
19939                    if (childInfo != null) {
19940                        childInfo.uid = childPs.appId;
19941                    }
19942                }
19943            }
19944        }
19945
19946        // Delete package data from internal structures and also remove data if flag is set
19947        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19948
19949        // Delete the child packages data
19950        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19951        for (int i = 0; i < childCount; i++) {
19952            PackageSetting childPs;
19953            synchronized (mPackages) {
19954                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19955            }
19956            if (childPs != null) {
19957                PackageRemovedInfo childOutInfo = (outInfo != null
19958                        && outInfo.removedChildPackages != null)
19959                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19960                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19961                        && (replacingPackage != null
19962                        && !replacingPackage.hasChildPackage(childPs.name))
19963                        ? flags & ~DELETE_KEEP_DATA : flags;
19964                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19965                        deleteFlags, writeSettings);
19966            }
19967        }
19968
19969        // Delete application code and resources only for parent packages
19970        if (ps.parentPackageName == null) {
19971            if (deleteCodeAndResources && (outInfo != null)) {
19972                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19973                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19974                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19975            }
19976        }
19977
19978        return true;
19979    }
19980
19981    @Override
19982    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19983            int userId) {
19984        mContext.enforceCallingOrSelfPermission(
19985                android.Manifest.permission.DELETE_PACKAGES, null);
19986        synchronized (mPackages) {
19987            // Cannot block uninstall of static shared libs as they are
19988            // considered a part of the using app (emulating static linking).
19989            // Also static libs are installed always on internal storage.
19990            PackageParser.Package pkg = mPackages.get(packageName);
19991            if (pkg != null && pkg.staticSharedLibName != null) {
19992                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19993                        + " providing static shared library: " + pkg.staticSharedLibName);
19994                return false;
19995            }
19996            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19997            mSettings.writePackageRestrictionsLPr(userId);
19998        }
19999        return true;
20000    }
20001
20002    @Override
20003    public boolean getBlockUninstallForUser(String packageName, int userId) {
20004        synchronized (mPackages) {
20005            final PackageSetting ps = mSettings.mPackages.get(packageName);
20006            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
20007                return false;
20008            }
20009            return mSettings.getBlockUninstallLPr(userId, packageName);
20010        }
20011    }
20012
20013    @Override
20014    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20015        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20016        synchronized (mPackages) {
20017            PackageSetting ps = mSettings.mPackages.get(packageName);
20018            if (ps == null) {
20019                Log.w(TAG, "Package doesn't exist: " + packageName);
20020                return false;
20021            }
20022            if (systemUserApp) {
20023                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20024            } else {
20025                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20026            }
20027            mSettings.writeLPr();
20028        }
20029        return true;
20030    }
20031
20032    /*
20033     * This method handles package deletion in general
20034     */
20035    private boolean deletePackageLIF(String packageName, UserHandle user,
20036            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20037            PackageRemovedInfo outInfo, boolean writeSettings,
20038            PackageParser.Package replacingPackage) {
20039        if (packageName == null) {
20040            Slog.w(TAG, "Attempt to delete null packageName.");
20041            return false;
20042        }
20043
20044        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20045
20046        PackageSetting ps;
20047        synchronized (mPackages) {
20048            ps = mSettings.mPackages.get(packageName);
20049            if (ps == null) {
20050                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20051                return false;
20052            }
20053
20054            if (ps.parentPackageName != null && (!isSystemApp(ps)
20055                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20056                if (DEBUG_REMOVE) {
20057                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20058                            + ((user == null) ? UserHandle.USER_ALL : user));
20059                }
20060                final int removedUserId = (user != null) ? user.getIdentifier()
20061                        : UserHandle.USER_ALL;
20062                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20063                    return false;
20064                }
20065                markPackageUninstalledForUserLPw(ps, user);
20066                scheduleWritePackageRestrictionsLocked(user);
20067                return true;
20068            }
20069        }
20070
20071        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20072                && user.getIdentifier() != UserHandle.USER_ALL)) {
20073            // The caller is asking that the package only be deleted for a single
20074            // user.  To do this, we just mark its uninstalled state and delete
20075            // its data. If this is a system app, we only allow this to happen if
20076            // they have set the special DELETE_SYSTEM_APP which requests different
20077            // semantics than normal for uninstalling system apps.
20078            markPackageUninstalledForUserLPw(ps, user);
20079
20080            if (!isSystemApp(ps)) {
20081                // Do not uninstall the APK if an app should be cached
20082                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20083                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20084                    // Other user still have this package installed, so all
20085                    // we need to do is clear this user's data and save that
20086                    // it is uninstalled.
20087                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20088                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20089                        return false;
20090                    }
20091                    scheduleWritePackageRestrictionsLocked(user);
20092                    return true;
20093                } else {
20094                    // We need to set it back to 'installed' so the uninstall
20095                    // broadcasts will be sent correctly.
20096                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20097                    ps.setInstalled(true, user.getIdentifier());
20098                    mSettings.writeKernelMappingLPr(ps);
20099                }
20100            } else {
20101                // This is a system app, so we assume that the
20102                // other users still have this package installed, so all
20103                // we need to do is clear this user's data and save that
20104                // it is uninstalled.
20105                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20106                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20107                    return false;
20108                }
20109                scheduleWritePackageRestrictionsLocked(user);
20110                return true;
20111            }
20112        }
20113
20114        // If we are deleting a composite package for all users, keep track
20115        // of result for each child.
20116        if (ps.childPackageNames != null && outInfo != null) {
20117            synchronized (mPackages) {
20118                final int childCount = ps.childPackageNames.size();
20119                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20120                for (int i = 0; i < childCount; i++) {
20121                    String childPackageName = ps.childPackageNames.get(i);
20122                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20123                    childInfo.removedPackage = childPackageName;
20124                    childInfo.installerPackageName = ps.installerPackageName;
20125                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20126                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20127                    if (childPs != null) {
20128                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20129                    }
20130                }
20131            }
20132        }
20133
20134        boolean ret = false;
20135        if (isSystemApp(ps)) {
20136            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20137            // When an updated system application is deleted we delete the existing resources
20138            // as well and fall back to existing code in system partition
20139            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20140        } else {
20141            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20142            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20143                    outInfo, writeSettings, replacingPackage);
20144        }
20145
20146        // Take a note whether we deleted the package for all users
20147        if (outInfo != null) {
20148            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20149            if (outInfo.removedChildPackages != null) {
20150                synchronized (mPackages) {
20151                    final int childCount = outInfo.removedChildPackages.size();
20152                    for (int i = 0; i < childCount; i++) {
20153                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20154                        if (childInfo != null) {
20155                            childInfo.removedForAllUsers = mPackages.get(
20156                                    childInfo.removedPackage) == null;
20157                        }
20158                    }
20159                }
20160            }
20161            // If we uninstalled an update to a system app there may be some
20162            // child packages that appeared as they are declared in the system
20163            // app but were not declared in the update.
20164            if (isSystemApp(ps)) {
20165                synchronized (mPackages) {
20166                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20167                    final int childCount = (updatedPs.childPackageNames != null)
20168                            ? updatedPs.childPackageNames.size() : 0;
20169                    for (int i = 0; i < childCount; i++) {
20170                        String childPackageName = updatedPs.childPackageNames.get(i);
20171                        if (outInfo.removedChildPackages == null
20172                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20173                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20174                            if (childPs == null) {
20175                                continue;
20176                            }
20177                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20178                            installRes.name = childPackageName;
20179                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20180                            installRes.pkg = mPackages.get(childPackageName);
20181                            installRes.uid = childPs.pkg.applicationInfo.uid;
20182                            if (outInfo.appearedChildPackages == null) {
20183                                outInfo.appearedChildPackages = new ArrayMap<>();
20184                            }
20185                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20186                        }
20187                    }
20188                }
20189            }
20190        }
20191
20192        return ret;
20193    }
20194
20195    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20196        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20197                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20198        for (int nextUserId : userIds) {
20199            if (DEBUG_REMOVE) {
20200                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20201            }
20202            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20203                    false /*installed*/,
20204                    true /*stopped*/,
20205                    true /*notLaunched*/,
20206                    false /*hidden*/,
20207                    false /*suspended*/,
20208                    false /*instantApp*/,
20209                    false /*virtualPreload*/,
20210                    null /*lastDisableAppCaller*/,
20211                    null /*enabledComponents*/,
20212                    null /*disabledComponents*/,
20213                    ps.readUserState(nextUserId).domainVerificationStatus,
20214                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20215        }
20216        mSettings.writeKernelMappingLPr(ps);
20217    }
20218
20219    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20220            PackageRemovedInfo outInfo) {
20221        final PackageParser.Package pkg;
20222        synchronized (mPackages) {
20223            pkg = mPackages.get(ps.name);
20224        }
20225
20226        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20227                : new int[] {userId};
20228        for (int nextUserId : userIds) {
20229            if (DEBUG_REMOVE) {
20230                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20231                        + nextUserId);
20232            }
20233
20234            destroyAppDataLIF(pkg, userId,
20235                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20236            destroyAppProfilesLIF(pkg, userId);
20237            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20238            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20239            schedulePackageCleaning(ps.name, nextUserId, false);
20240            synchronized (mPackages) {
20241                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20242                    scheduleWritePackageRestrictionsLocked(nextUserId);
20243                }
20244                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20245            }
20246        }
20247
20248        if (outInfo != null) {
20249            outInfo.removedPackage = ps.name;
20250            outInfo.installerPackageName = ps.installerPackageName;
20251            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20252            outInfo.removedAppId = ps.appId;
20253            outInfo.removedUsers = userIds;
20254            outInfo.broadcastUsers = userIds;
20255        }
20256
20257        return true;
20258    }
20259
20260    private final class ClearStorageConnection implements ServiceConnection {
20261        IMediaContainerService mContainerService;
20262
20263        @Override
20264        public void onServiceConnected(ComponentName name, IBinder service) {
20265            synchronized (this) {
20266                mContainerService = IMediaContainerService.Stub
20267                        .asInterface(Binder.allowBlocking(service));
20268                notifyAll();
20269            }
20270        }
20271
20272        @Override
20273        public void onServiceDisconnected(ComponentName name) {
20274        }
20275    }
20276
20277    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20278        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20279
20280        final boolean mounted;
20281        if (Environment.isExternalStorageEmulated()) {
20282            mounted = true;
20283        } else {
20284            final String status = Environment.getExternalStorageState();
20285
20286            mounted = status.equals(Environment.MEDIA_MOUNTED)
20287                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20288        }
20289
20290        if (!mounted) {
20291            return;
20292        }
20293
20294        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20295        int[] users;
20296        if (userId == UserHandle.USER_ALL) {
20297            users = sUserManager.getUserIds();
20298        } else {
20299            users = new int[] { userId };
20300        }
20301        final ClearStorageConnection conn = new ClearStorageConnection();
20302        if (mContext.bindServiceAsUser(
20303                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20304            try {
20305                for (int curUser : users) {
20306                    long timeout = SystemClock.uptimeMillis() + 5000;
20307                    synchronized (conn) {
20308                        long now;
20309                        while (conn.mContainerService == null &&
20310                                (now = SystemClock.uptimeMillis()) < timeout) {
20311                            try {
20312                                conn.wait(timeout - now);
20313                            } catch (InterruptedException e) {
20314                            }
20315                        }
20316                    }
20317                    if (conn.mContainerService == null) {
20318                        return;
20319                    }
20320
20321                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20322                    clearDirectory(conn.mContainerService,
20323                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20324                    if (allData) {
20325                        clearDirectory(conn.mContainerService,
20326                                userEnv.buildExternalStorageAppDataDirs(packageName));
20327                        clearDirectory(conn.mContainerService,
20328                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20329                    }
20330                }
20331            } finally {
20332                mContext.unbindService(conn);
20333            }
20334        }
20335    }
20336
20337    @Override
20338    public void clearApplicationProfileData(String packageName) {
20339        enforceSystemOrRoot("Only the system can clear all profile data");
20340
20341        final PackageParser.Package pkg;
20342        synchronized (mPackages) {
20343            pkg = mPackages.get(packageName);
20344        }
20345
20346        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20347            synchronized (mInstallLock) {
20348                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20349            }
20350        }
20351    }
20352
20353    @Override
20354    public void clearApplicationUserData(final String packageName,
20355            final IPackageDataObserver observer, final int userId) {
20356        mContext.enforceCallingOrSelfPermission(
20357                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20358
20359        final int callingUid = Binder.getCallingUid();
20360        enforceCrossUserPermission(callingUid, userId,
20361                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20362
20363        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20364        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20365        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20366            throw new SecurityException("Cannot clear data for a protected package: "
20367                    + packageName);
20368        }
20369        // Queue up an async operation since the package deletion may take a little while.
20370        mHandler.post(new Runnable() {
20371            public void run() {
20372                mHandler.removeCallbacks(this);
20373                final boolean succeeded;
20374                if (!filterApp) {
20375                    try (PackageFreezer freezer = freezePackage(packageName,
20376                            "clearApplicationUserData")) {
20377                        synchronized (mInstallLock) {
20378                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20379                        }
20380                        clearExternalStorageDataSync(packageName, userId, true);
20381                        synchronized (mPackages) {
20382                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20383                                    packageName, userId);
20384                        }
20385                    }
20386                    if (succeeded) {
20387                        // invoke DeviceStorageMonitor's update method to clear any notifications
20388                        DeviceStorageMonitorInternal dsm = LocalServices
20389                                .getService(DeviceStorageMonitorInternal.class);
20390                        if (dsm != null) {
20391                            dsm.checkMemory();
20392                        }
20393                    }
20394                } else {
20395                    succeeded = false;
20396                }
20397                if (observer != null) {
20398                    try {
20399                        observer.onRemoveCompleted(packageName, succeeded);
20400                    } catch (RemoteException e) {
20401                        Log.i(TAG, "Observer no longer exists.");
20402                    }
20403                } //end if observer
20404            } //end run
20405        });
20406    }
20407
20408    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20409        if (packageName == null) {
20410            Slog.w(TAG, "Attempt to delete null packageName.");
20411            return false;
20412        }
20413
20414        // Try finding details about the requested package
20415        PackageParser.Package pkg;
20416        synchronized (mPackages) {
20417            pkg = mPackages.get(packageName);
20418            if (pkg == null) {
20419                final PackageSetting ps = mSettings.mPackages.get(packageName);
20420                if (ps != null) {
20421                    pkg = ps.pkg;
20422                }
20423            }
20424
20425            if (pkg == null) {
20426                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20427                return false;
20428            }
20429
20430            PackageSetting ps = (PackageSetting) pkg.mExtras;
20431            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20432        }
20433
20434        clearAppDataLIF(pkg, userId,
20435                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20436
20437        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20438        removeKeystoreDataIfNeeded(userId, appId);
20439
20440        UserManagerInternal umInternal = getUserManagerInternal();
20441        final int flags;
20442        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20443            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20444        } else if (umInternal.isUserRunning(userId)) {
20445            flags = StorageManager.FLAG_STORAGE_DE;
20446        } else {
20447            flags = 0;
20448        }
20449        prepareAppDataContentsLIF(pkg, userId, flags);
20450
20451        return true;
20452    }
20453
20454    /**
20455     * Reverts user permission state changes (permissions and flags) in
20456     * all packages for a given user.
20457     *
20458     * @param userId The device user for which to do a reset.
20459     */
20460    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20461        final int packageCount = mPackages.size();
20462        for (int i = 0; i < packageCount; i++) {
20463            PackageParser.Package pkg = mPackages.valueAt(i);
20464            PackageSetting ps = (PackageSetting) pkg.mExtras;
20465            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20466        }
20467    }
20468
20469    private void resetNetworkPolicies(int userId) {
20470        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20471    }
20472
20473    /**
20474     * Reverts user permission state changes (permissions and flags).
20475     *
20476     * @param ps The package for which to reset.
20477     * @param userId The device user for which to do a reset.
20478     */
20479    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20480            final PackageSetting ps, final int userId) {
20481        if (ps.pkg == null) {
20482            return;
20483        }
20484
20485        // These are flags that can change base on user actions.
20486        final int userSettableMask = FLAG_PERMISSION_USER_SET
20487                | FLAG_PERMISSION_USER_FIXED
20488                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20489                | FLAG_PERMISSION_REVIEW_REQUIRED;
20490
20491        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20492                | FLAG_PERMISSION_POLICY_FIXED;
20493
20494        boolean writeInstallPermissions = false;
20495        boolean writeRuntimePermissions = false;
20496
20497        final int permissionCount = ps.pkg.requestedPermissions.size();
20498        for (int i = 0; i < permissionCount; i++) {
20499            String permission = ps.pkg.requestedPermissions.get(i);
20500
20501            BasePermission bp = mSettings.mPermissions.get(permission);
20502            if (bp == null) {
20503                continue;
20504            }
20505
20506            // If shared user we just reset the state to which only this app contributed.
20507            if (ps.sharedUser != null) {
20508                boolean used = false;
20509                final int packageCount = ps.sharedUser.packages.size();
20510                for (int j = 0; j < packageCount; j++) {
20511                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20512                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20513                            && pkg.pkg.requestedPermissions.contains(permission)) {
20514                        used = true;
20515                        break;
20516                    }
20517                }
20518                if (used) {
20519                    continue;
20520                }
20521            }
20522
20523            PermissionsState permissionsState = ps.getPermissionsState();
20524
20525            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20526
20527            // Always clear the user settable flags.
20528            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20529                    bp.name) != null;
20530            // If permission review is enabled and this is a legacy app, mark the
20531            // permission as requiring a review as this is the initial state.
20532            int flags = 0;
20533            if (mPermissionReviewRequired
20534                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20535                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20536            }
20537            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20538                if (hasInstallState) {
20539                    writeInstallPermissions = true;
20540                } else {
20541                    writeRuntimePermissions = true;
20542                }
20543            }
20544
20545            // Below is only runtime permission handling.
20546            if (!bp.isRuntime()) {
20547                continue;
20548            }
20549
20550            // Never clobber system or policy.
20551            if ((oldFlags & policyOrSystemFlags) != 0) {
20552                continue;
20553            }
20554
20555            // If this permission was granted by default, make sure it is.
20556            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20557                if (permissionsState.grantRuntimePermission(bp, userId)
20558                        != PERMISSION_OPERATION_FAILURE) {
20559                    writeRuntimePermissions = true;
20560                }
20561            // If permission review is enabled the permissions for a legacy apps
20562            // are represented as constantly granted runtime ones, so don't revoke.
20563            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20564                // Otherwise, reset the permission.
20565                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20566                switch (revokeResult) {
20567                    case PERMISSION_OPERATION_SUCCESS:
20568                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20569                        writeRuntimePermissions = true;
20570                        final int appId = ps.appId;
20571                        mHandler.post(new Runnable() {
20572                            @Override
20573                            public void run() {
20574                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20575                            }
20576                        });
20577                    } break;
20578                }
20579            }
20580        }
20581
20582        // Synchronously write as we are taking permissions away.
20583        if (writeRuntimePermissions) {
20584            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20585        }
20586
20587        // Synchronously write as we are taking permissions away.
20588        if (writeInstallPermissions) {
20589            mSettings.writeLPr();
20590        }
20591    }
20592
20593    /**
20594     * Remove entries from the keystore daemon. Will only remove it if the
20595     * {@code appId} is valid.
20596     */
20597    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20598        if (appId < 0) {
20599            return;
20600        }
20601
20602        final KeyStore keyStore = KeyStore.getInstance();
20603        if (keyStore != null) {
20604            if (userId == UserHandle.USER_ALL) {
20605                for (final int individual : sUserManager.getUserIds()) {
20606                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20607                }
20608            } else {
20609                keyStore.clearUid(UserHandle.getUid(userId, appId));
20610            }
20611        } else {
20612            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20613        }
20614    }
20615
20616    @Override
20617    public void deleteApplicationCacheFiles(final String packageName,
20618            final IPackageDataObserver observer) {
20619        final int userId = UserHandle.getCallingUserId();
20620        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20621    }
20622
20623    @Override
20624    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20625            final IPackageDataObserver observer) {
20626        final int callingUid = Binder.getCallingUid();
20627        mContext.enforceCallingOrSelfPermission(
20628                android.Manifest.permission.DELETE_CACHE_FILES, null);
20629        enforceCrossUserPermission(callingUid, userId,
20630                /* requireFullPermission= */ true, /* checkShell= */ false,
20631                "delete application cache files");
20632        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20633                android.Manifest.permission.ACCESS_INSTANT_APPS);
20634
20635        final PackageParser.Package pkg;
20636        synchronized (mPackages) {
20637            pkg = mPackages.get(packageName);
20638        }
20639
20640        // Queue up an async operation since the package deletion may take a little while.
20641        mHandler.post(new Runnable() {
20642            public void run() {
20643                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20644                boolean doClearData = true;
20645                if (ps != null) {
20646                    final boolean targetIsInstantApp =
20647                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20648                    doClearData = !targetIsInstantApp
20649                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20650                }
20651                if (doClearData) {
20652                    synchronized (mInstallLock) {
20653                        final int flags = StorageManager.FLAG_STORAGE_DE
20654                                | StorageManager.FLAG_STORAGE_CE;
20655                        // We're only clearing cache files, so we don't care if the
20656                        // app is unfrozen and still able to run
20657                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20658                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20659                    }
20660                    clearExternalStorageDataSync(packageName, userId, false);
20661                }
20662                if (observer != null) {
20663                    try {
20664                        observer.onRemoveCompleted(packageName, true);
20665                    } catch (RemoteException e) {
20666                        Log.i(TAG, "Observer no longer exists.");
20667                    }
20668                }
20669            }
20670        });
20671    }
20672
20673    @Override
20674    public void getPackageSizeInfo(final String packageName, int userHandle,
20675            final IPackageStatsObserver observer) {
20676        throw new UnsupportedOperationException(
20677                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20678    }
20679
20680    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20681        final PackageSetting ps;
20682        synchronized (mPackages) {
20683            ps = mSettings.mPackages.get(packageName);
20684            if (ps == null) {
20685                Slog.w(TAG, "Failed to find settings for " + packageName);
20686                return false;
20687            }
20688        }
20689
20690        final String[] packageNames = { packageName };
20691        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20692        final String[] codePaths = { ps.codePathString };
20693
20694        try {
20695            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20696                    ps.appId, ceDataInodes, codePaths, stats);
20697
20698            // For now, ignore code size of packages on system partition
20699            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20700                stats.codeSize = 0;
20701            }
20702
20703            // External clients expect these to be tracked separately
20704            stats.dataSize -= stats.cacheSize;
20705
20706        } catch (InstallerException e) {
20707            Slog.w(TAG, String.valueOf(e));
20708            return false;
20709        }
20710
20711        return true;
20712    }
20713
20714    private int getUidTargetSdkVersionLockedLPr(int uid) {
20715        Object obj = mSettings.getUserIdLPr(uid);
20716        if (obj instanceof SharedUserSetting) {
20717            final SharedUserSetting sus = (SharedUserSetting) obj;
20718            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20719            final Iterator<PackageSetting> it = sus.packages.iterator();
20720            while (it.hasNext()) {
20721                final PackageSetting ps = it.next();
20722                if (ps.pkg != null) {
20723                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20724                    if (v < vers) vers = v;
20725                }
20726            }
20727            return vers;
20728        } else if (obj instanceof PackageSetting) {
20729            final PackageSetting ps = (PackageSetting) obj;
20730            if (ps.pkg != null) {
20731                return ps.pkg.applicationInfo.targetSdkVersion;
20732            }
20733        }
20734        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20735    }
20736
20737    @Override
20738    public void addPreferredActivity(IntentFilter filter, int match,
20739            ComponentName[] set, ComponentName activity, int userId) {
20740        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20741                "Adding preferred");
20742    }
20743
20744    private void addPreferredActivityInternal(IntentFilter filter, int match,
20745            ComponentName[] set, ComponentName activity, boolean always, int userId,
20746            String opname) {
20747        // writer
20748        int callingUid = Binder.getCallingUid();
20749        enforceCrossUserPermission(callingUid, userId,
20750                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20751        if (filter.countActions() == 0) {
20752            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20753            return;
20754        }
20755        synchronized (mPackages) {
20756            if (mContext.checkCallingOrSelfPermission(
20757                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20758                    != PackageManager.PERMISSION_GRANTED) {
20759                if (getUidTargetSdkVersionLockedLPr(callingUid)
20760                        < Build.VERSION_CODES.FROYO) {
20761                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20762                            + callingUid);
20763                    return;
20764                }
20765                mContext.enforceCallingOrSelfPermission(
20766                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20767            }
20768
20769            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20770            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20771                    + userId + ":");
20772            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20773            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20774            scheduleWritePackageRestrictionsLocked(userId);
20775            postPreferredActivityChangedBroadcast(userId);
20776        }
20777    }
20778
20779    private void postPreferredActivityChangedBroadcast(int userId) {
20780        mHandler.post(() -> {
20781            final IActivityManager am = ActivityManager.getService();
20782            if (am == null) {
20783                return;
20784            }
20785
20786            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20787            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20788            try {
20789                am.broadcastIntent(null, intent, null, null,
20790                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20791                        null, false, false, userId);
20792            } catch (RemoteException e) {
20793            }
20794        });
20795    }
20796
20797    @Override
20798    public void replacePreferredActivity(IntentFilter filter, int match,
20799            ComponentName[] set, ComponentName activity, int userId) {
20800        if (filter.countActions() != 1) {
20801            throw new IllegalArgumentException(
20802                    "replacePreferredActivity expects filter to have only 1 action.");
20803        }
20804        if (filter.countDataAuthorities() != 0
20805                || filter.countDataPaths() != 0
20806                || filter.countDataSchemes() > 1
20807                || filter.countDataTypes() != 0) {
20808            throw new IllegalArgumentException(
20809                    "replacePreferredActivity expects filter to have no data authorities, " +
20810                    "paths, or types; and at most one scheme.");
20811        }
20812
20813        final int callingUid = Binder.getCallingUid();
20814        enforceCrossUserPermission(callingUid, userId,
20815                true /* requireFullPermission */, false /* checkShell */,
20816                "replace preferred activity");
20817        synchronized (mPackages) {
20818            if (mContext.checkCallingOrSelfPermission(
20819                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20820                    != PackageManager.PERMISSION_GRANTED) {
20821                if (getUidTargetSdkVersionLockedLPr(callingUid)
20822                        < Build.VERSION_CODES.FROYO) {
20823                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20824                            + Binder.getCallingUid());
20825                    return;
20826                }
20827                mContext.enforceCallingOrSelfPermission(
20828                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20829            }
20830
20831            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20832            if (pir != null) {
20833                // Get all of the existing entries that exactly match this filter.
20834                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20835                if (existing != null && existing.size() == 1) {
20836                    PreferredActivity cur = existing.get(0);
20837                    if (DEBUG_PREFERRED) {
20838                        Slog.i(TAG, "Checking replace of preferred:");
20839                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20840                        if (!cur.mPref.mAlways) {
20841                            Slog.i(TAG, "  -- CUR; not mAlways!");
20842                        } else {
20843                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20844                            Slog.i(TAG, "  -- CUR: mSet="
20845                                    + Arrays.toString(cur.mPref.mSetComponents));
20846                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20847                            Slog.i(TAG, "  -- NEW: mMatch="
20848                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20849                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20850                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20851                        }
20852                    }
20853                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20854                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20855                            && cur.mPref.sameSet(set)) {
20856                        // Setting the preferred activity to what it happens to be already
20857                        if (DEBUG_PREFERRED) {
20858                            Slog.i(TAG, "Replacing with same preferred activity "
20859                                    + cur.mPref.mShortComponent + " for user "
20860                                    + userId + ":");
20861                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20862                        }
20863                        return;
20864                    }
20865                }
20866
20867                if (existing != null) {
20868                    if (DEBUG_PREFERRED) {
20869                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20870                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20871                    }
20872                    for (int i = 0; i < existing.size(); i++) {
20873                        PreferredActivity pa = existing.get(i);
20874                        if (DEBUG_PREFERRED) {
20875                            Slog.i(TAG, "Removing existing preferred activity "
20876                                    + pa.mPref.mComponent + ":");
20877                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20878                        }
20879                        pir.removeFilter(pa);
20880                    }
20881                }
20882            }
20883            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20884                    "Replacing preferred");
20885        }
20886    }
20887
20888    @Override
20889    public void clearPackagePreferredActivities(String packageName) {
20890        final int callingUid = Binder.getCallingUid();
20891        if (getInstantAppPackageName(callingUid) != null) {
20892            return;
20893        }
20894        // writer
20895        synchronized (mPackages) {
20896            PackageParser.Package pkg = mPackages.get(packageName);
20897            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20898                if (mContext.checkCallingOrSelfPermission(
20899                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20900                        != PackageManager.PERMISSION_GRANTED) {
20901                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20902                            < Build.VERSION_CODES.FROYO) {
20903                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20904                                + callingUid);
20905                        return;
20906                    }
20907                    mContext.enforceCallingOrSelfPermission(
20908                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20909                }
20910            }
20911            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20912            if (ps != null
20913                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20914                return;
20915            }
20916            int user = UserHandle.getCallingUserId();
20917            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20918                scheduleWritePackageRestrictionsLocked(user);
20919            }
20920        }
20921    }
20922
20923    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20924    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20925        ArrayList<PreferredActivity> removed = null;
20926        boolean changed = false;
20927        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20928            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20929            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20930            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20931                continue;
20932            }
20933            Iterator<PreferredActivity> it = pir.filterIterator();
20934            while (it.hasNext()) {
20935                PreferredActivity pa = it.next();
20936                // Mark entry for removal only if it matches the package name
20937                // and the entry is of type "always".
20938                if (packageName == null ||
20939                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20940                                && pa.mPref.mAlways)) {
20941                    if (removed == null) {
20942                        removed = new ArrayList<PreferredActivity>();
20943                    }
20944                    removed.add(pa);
20945                }
20946            }
20947            if (removed != null) {
20948                for (int j=0; j<removed.size(); j++) {
20949                    PreferredActivity pa = removed.get(j);
20950                    pir.removeFilter(pa);
20951                }
20952                changed = true;
20953            }
20954        }
20955        if (changed) {
20956            postPreferredActivityChangedBroadcast(userId);
20957        }
20958        return changed;
20959    }
20960
20961    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20962    private void clearIntentFilterVerificationsLPw(int userId) {
20963        final int packageCount = mPackages.size();
20964        for (int i = 0; i < packageCount; i++) {
20965            PackageParser.Package pkg = mPackages.valueAt(i);
20966            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20967        }
20968    }
20969
20970    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20971    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20972        if (userId == UserHandle.USER_ALL) {
20973            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20974                    sUserManager.getUserIds())) {
20975                for (int oneUserId : sUserManager.getUserIds()) {
20976                    scheduleWritePackageRestrictionsLocked(oneUserId);
20977                }
20978            }
20979        } else {
20980            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20981                scheduleWritePackageRestrictionsLocked(userId);
20982            }
20983        }
20984    }
20985
20986    /** Clears state for all users, and touches intent filter verification policy */
20987    void clearDefaultBrowserIfNeeded(String packageName) {
20988        for (int oneUserId : sUserManager.getUserIds()) {
20989            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20990        }
20991    }
20992
20993    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20994        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20995        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20996            if (packageName.equals(defaultBrowserPackageName)) {
20997                setDefaultBrowserPackageName(null, userId);
20998            }
20999        }
21000    }
21001
21002    @Override
21003    public void resetApplicationPreferences(int userId) {
21004        mContext.enforceCallingOrSelfPermission(
21005                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
21006        final long identity = Binder.clearCallingIdentity();
21007        // writer
21008        try {
21009            synchronized (mPackages) {
21010                clearPackagePreferredActivitiesLPw(null, userId);
21011                mSettings.applyDefaultPreferredAppsLPw(this, userId);
21012                // TODO: We have to reset the default SMS and Phone. This requires
21013                // significant refactoring to keep all default apps in the package
21014                // manager (cleaner but more work) or have the services provide
21015                // callbacks to the package manager to request a default app reset.
21016                applyFactoryDefaultBrowserLPw(userId);
21017                clearIntentFilterVerificationsLPw(userId);
21018                primeDomainVerificationsLPw(userId);
21019                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21020                scheduleWritePackageRestrictionsLocked(userId);
21021            }
21022            resetNetworkPolicies(userId);
21023        } finally {
21024            Binder.restoreCallingIdentity(identity);
21025        }
21026    }
21027
21028    @Override
21029    public int getPreferredActivities(List<IntentFilter> outFilters,
21030            List<ComponentName> outActivities, String packageName) {
21031        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21032            return 0;
21033        }
21034        int num = 0;
21035        final int userId = UserHandle.getCallingUserId();
21036        // reader
21037        synchronized (mPackages) {
21038            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21039            if (pir != null) {
21040                final Iterator<PreferredActivity> it = pir.filterIterator();
21041                while (it.hasNext()) {
21042                    final PreferredActivity pa = it.next();
21043                    if (packageName == null
21044                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21045                                    && pa.mPref.mAlways)) {
21046                        if (outFilters != null) {
21047                            outFilters.add(new IntentFilter(pa));
21048                        }
21049                        if (outActivities != null) {
21050                            outActivities.add(pa.mPref.mComponent);
21051                        }
21052                    }
21053                }
21054            }
21055        }
21056
21057        return num;
21058    }
21059
21060    @Override
21061    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21062            int userId) {
21063        int callingUid = Binder.getCallingUid();
21064        if (callingUid != Process.SYSTEM_UID) {
21065            throw new SecurityException(
21066                    "addPersistentPreferredActivity can only be run by the system");
21067        }
21068        if (filter.countActions() == 0) {
21069            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21070            return;
21071        }
21072        synchronized (mPackages) {
21073            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21074                    ":");
21075            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21076            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21077                    new PersistentPreferredActivity(filter, activity));
21078            scheduleWritePackageRestrictionsLocked(userId);
21079            postPreferredActivityChangedBroadcast(userId);
21080        }
21081    }
21082
21083    @Override
21084    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21085        int callingUid = Binder.getCallingUid();
21086        if (callingUid != Process.SYSTEM_UID) {
21087            throw new SecurityException(
21088                    "clearPackagePersistentPreferredActivities can only be run by the system");
21089        }
21090        ArrayList<PersistentPreferredActivity> removed = null;
21091        boolean changed = false;
21092        synchronized (mPackages) {
21093            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21094                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21095                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21096                        .valueAt(i);
21097                if (userId != thisUserId) {
21098                    continue;
21099                }
21100                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21101                while (it.hasNext()) {
21102                    PersistentPreferredActivity ppa = it.next();
21103                    // Mark entry for removal only if it matches the package name.
21104                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21105                        if (removed == null) {
21106                            removed = new ArrayList<PersistentPreferredActivity>();
21107                        }
21108                        removed.add(ppa);
21109                    }
21110                }
21111                if (removed != null) {
21112                    for (int j=0; j<removed.size(); j++) {
21113                        PersistentPreferredActivity ppa = removed.get(j);
21114                        ppir.removeFilter(ppa);
21115                    }
21116                    changed = true;
21117                }
21118            }
21119
21120            if (changed) {
21121                scheduleWritePackageRestrictionsLocked(userId);
21122                postPreferredActivityChangedBroadcast(userId);
21123            }
21124        }
21125    }
21126
21127    /**
21128     * Common machinery for picking apart a restored XML blob and passing
21129     * it to a caller-supplied functor to be applied to the running system.
21130     */
21131    private void restoreFromXml(XmlPullParser parser, int userId,
21132            String expectedStartTag, BlobXmlRestorer functor)
21133            throws IOException, XmlPullParserException {
21134        int type;
21135        while ((type = parser.next()) != XmlPullParser.START_TAG
21136                && type != XmlPullParser.END_DOCUMENT) {
21137        }
21138        if (type != XmlPullParser.START_TAG) {
21139            // oops didn't find a start tag?!
21140            if (DEBUG_BACKUP) {
21141                Slog.e(TAG, "Didn't find start tag during restore");
21142            }
21143            return;
21144        }
21145Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21146        // this is supposed to be TAG_PREFERRED_BACKUP
21147        if (!expectedStartTag.equals(parser.getName())) {
21148            if (DEBUG_BACKUP) {
21149                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21150            }
21151            return;
21152        }
21153
21154        // skip interfering stuff, then we're aligned with the backing implementation
21155        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21156Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21157        functor.apply(parser, userId);
21158    }
21159
21160    private interface BlobXmlRestorer {
21161        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21162    }
21163
21164    /**
21165     * Non-Binder method, support for the backup/restore mechanism: write the
21166     * full set of preferred activities in its canonical XML format.  Returns the
21167     * XML output as a byte array, or null if there is none.
21168     */
21169    @Override
21170    public byte[] getPreferredActivityBackup(int userId) {
21171        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21172            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21173        }
21174
21175        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21176        try {
21177            final XmlSerializer serializer = new FastXmlSerializer();
21178            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21179            serializer.startDocument(null, true);
21180            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21181
21182            synchronized (mPackages) {
21183                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21184            }
21185
21186            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21187            serializer.endDocument();
21188            serializer.flush();
21189        } catch (Exception e) {
21190            if (DEBUG_BACKUP) {
21191                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21192            }
21193            return null;
21194        }
21195
21196        return dataStream.toByteArray();
21197    }
21198
21199    @Override
21200    public void restorePreferredActivities(byte[] backup, int userId) {
21201        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21202            throw new SecurityException("Only the system may call restorePreferredActivities()");
21203        }
21204
21205        try {
21206            final XmlPullParser parser = Xml.newPullParser();
21207            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21208            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21209                    new BlobXmlRestorer() {
21210                        @Override
21211                        public void apply(XmlPullParser parser, int userId)
21212                                throws XmlPullParserException, IOException {
21213                            synchronized (mPackages) {
21214                                mSettings.readPreferredActivitiesLPw(parser, userId);
21215                            }
21216                        }
21217                    } );
21218        } catch (Exception e) {
21219            if (DEBUG_BACKUP) {
21220                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21221            }
21222        }
21223    }
21224
21225    /**
21226     * Non-Binder method, support for the backup/restore mechanism: write the
21227     * default browser (etc) settings in its canonical XML format.  Returns the default
21228     * browser XML representation as a byte array, or null if there is none.
21229     */
21230    @Override
21231    public byte[] getDefaultAppsBackup(int userId) {
21232        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21233            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21234        }
21235
21236        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21237        try {
21238            final XmlSerializer serializer = new FastXmlSerializer();
21239            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21240            serializer.startDocument(null, true);
21241            serializer.startTag(null, TAG_DEFAULT_APPS);
21242
21243            synchronized (mPackages) {
21244                mSettings.writeDefaultAppsLPr(serializer, userId);
21245            }
21246
21247            serializer.endTag(null, TAG_DEFAULT_APPS);
21248            serializer.endDocument();
21249            serializer.flush();
21250        } catch (Exception e) {
21251            if (DEBUG_BACKUP) {
21252                Slog.e(TAG, "Unable to write default apps for backup", e);
21253            }
21254            return null;
21255        }
21256
21257        return dataStream.toByteArray();
21258    }
21259
21260    @Override
21261    public void restoreDefaultApps(byte[] backup, int userId) {
21262        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21263            throw new SecurityException("Only the system may call restoreDefaultApps()");
21264        }
21265
21266        try {
21267            final XmlPullParser parser = Xml.newPullParser();
21268            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21269            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21270                    new BlobXmlRestorer() {
21271                        @Override
21272                        public void apply(XmlPullParser parser, int userId)
21273                                throws XmlPullParserException, IOException {
21274                            synchronized (mPackages) {
21275                                mSettings.readDefaultAppsLPw(parser, userId);
21276                            }
21277                        }
21278                    } );
21279        } catch (Exception e) {
21280            if (DEBUG_BACKUP) {
21281                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21282            }
21283        }
21284    }
21285
21286    @Override
21287    public byte[] getIntentFilterVerificationBackup(int userId) {
21288        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21289            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21290        }
21291
21292        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21293        try {
21294            final XmlSerializer serializer = new FastXmlSerializer();
21295            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21296            serializer.startDocument(null, true);
21297            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21298
21299            synchronized (mPackages) {
21300                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21301            }
21302
21303            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21304            serializer.endDocument();
21305            serializer.flush();
21306        } catch (Exception e) {
21307            if (DEBUG_BACKUP) {
21308                Slog.e(TAG, "Unable to write default apps for backup", e);
21309            }
21310            return null;
21311        }
21312
21313        return dataStream.toByteArray();
21314    }
21315
21316    @Override
21317    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21318        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21319            throw new SecurityException("Only the system may call restorePreferredActivities()");
21320        }
21321
21322        try {
21323            final XmlPullParser parser = Xml.newPullParser();
21324            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21325            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21326                    new BlobXmlRestorer() {
21327                        @Override
21328                        public void apply(XmlPullParser parser, int userId)
21329                                throws XmlPullParserException, IOException {
21330                            synchronized (mPackages) {
21331                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21332                                mSettings.writeLPr();
21333                            }
21334                        }
21335                    } );
21336        } catch (Exception e) {
21337            if (DEBUG_BACKUP) {
21338                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21339            }
21340        }
21341    }
21342
21343    @Override
21344    public byte[] getPermissionGrantBackup(int userId) {
21345        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21346            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21347        }
21348
21349        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21350        try {
21351            final XmlSerializer serializer = new FastXmlSerializer();
21352            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21353            serializer.startDocument(null, true);
21354            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21355
21356            synchronized (mPackages) {
21357                serializeRuntimePermissionGrantsLPr(serializer, userId);
21358            }
21359
21360            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21361            serializer.endDocument();
21362            serializer.flush();
21363        } catch (Exception e) {
21364            if (DEBUG_BACKUP) {
21365                Slog.e(TAG, "Unable to write default apps for backup", e);
21366            }
21367            return null;
21368        }
21369
21370        return dataStream.toByteArray();
21371    }
21372
21373    @Override
21374    public void restorePermissionGrants(byte[] backup, int userId) {
21375        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21376            throw new SecurityException("Only the system may call restorePermissionGrants()");
21377        }
21378
21379        try {
21380            final XmlPullParser parser = Xml.newPullParser();
21381            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21382            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21383                    new BlobXmlRestorer() {
21384                        @Override
21385                        public void apply(XmlPullParser parser, int userId)
21386                                throws XmlPullParserException, IOException {
21387                            synchronized (mPackages) {
21388                                processRestoredPermissionGrantsLPr(parser, userId);
21389                            }
21390                        }
21391                    } );
21392        } catch (Exception e) {
21393            if (DEBUG_BACKUP) {
21394                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21395            }
21396        }
21397    }
21398
21399    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21400            throws IOException {
21401        serializer.startTag(null, TAG_ALL_GRANTS);
21402
21403        final int N = mSettings.mPackages.size();
21404        for (int i = 0; i < N; i++) {
21405            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21406            boolean pkgGrantsKnown = false;
21407
21408            PermissionsState packagePerms = ps.getPermissionsState();
21409
21410            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21411                final int grantFlags = state.getFlags();
21412                // only look at grants that are not system/policy fixed
21413                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21414                    final boolean isGranted = state.isGranted();
21415                    // And only back up the user-twiddled state bits
21416                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21417                        final String packageName = mSettings.mPackages.keyAt(i);
21418                        if (!pkgGrantsKnown) {
21419                            serializer.startTag(null, TAG_GRANT);
21420                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21421                            pkgGrantsKnown = true;
21422                        }
21423
21424                        final boolean userSet =
21425                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21426                        final boolean userFixed =
21427                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21428                        final boolean revoke =
21429                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21430
21431                        serializer.startTag(null, TAG_PERMISSION);
21432                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21433                        if (isGranted) {
21434                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21435                        }
21436                        if (userSet) {
21437                            serializer.attribute(null, ATTR_USER_SET, "true");
21438                        }
21439                        if (userFixed) {
21440                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21441                        }
21442                        if (revoke) {
21443                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21444                        }
21445                        serializer.endTag(null, TAG_PERMISSION);
21446                    }
21447                }
21448            }
21449
21450            if (pkgGrantsKnown) {
21451                serializer.endTag(null, TAG_GRANT);
21452            }
21453        }
21454
21455        serializer.endTag(null, TAG_ALL_GRANTS);
21456    }
21457
21458    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21459            throws XmlPullParserException, IOException {
21460        String pkgName = null;
21461        int outerDepth = parser.getDepth();
21462        int type;
21463        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21464                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21465            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21466                continue;
21467            }
21468
21469            final String tagName = parser.getName();
21470            if (tagName.equals(TAG_GRANT)) {
21471                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21472                if (DEBUG_BACKUP) {
21473                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21474                }
21475            } else if (tagName.equals(TAG_PERMISSION)) {
21476
21477                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21478                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21479
21480                int newFlagSet = 0;
21481                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21482                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21483                }
21484                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21485                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21486                }
21487                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21488                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21489                }
21490                if (DEBUG_BACKUP) {
21491                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21492                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21493                }
21494                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21495                if (ps != null) {
21496                    // Already installed so we apply the grant immediately
21497                    if (DEBUG_BACKUP) {
21498                        Slog.v(TAG, "        + already installed; applying");
21499                    }
21500                    PermissionsState perms = ps.getPermissionsState();
21501                    BasePermission bp = mSettings.mPermissions.get(permName);
21502                    if (bp != null) {
21503                        if (isGranted) {
21504                            perms.grantRuntimePermission(bp, userId);
21505                        }
21506                        if (newFlagSet != 0) {
21507                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21508                        }
21509                    }
21510                } else {
21511                    // Need to wait for post-restore install to apply the grant
21512                    if (DEBUG_BACKUP) {
21513                        Slog.v(TAG, "        - not yet installed; saving for later");
21514                    }
21515                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21516                            isGranted, newFlagSet, userId);
21517                }
21518            } else {
21519                PackageManagerService.reportSettingsProblem(Log.WARN,
21520                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21521                XmlUtils.skipCurrentTag(parser);
21522            }
21523        }
21524
21525        scheduleWriteSettingsLocked();
21526        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21527    }
21528
21529    @Override
21530    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21531            int sourceUserId, int targetUserId, int flags) {
21532        mContext.enforceCallingOrSelfPermission(
21533                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21534        int callingUid = Binder.getCallingUid();
21535        enforceOwnerRights(ownerPackage, callingUid);
21536        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21537        if (intentFilter.countActions() == 0) {
21538            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21539            return;
21540        }
21541        synchronized (mPackages) {
21542            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21543                    ownerPackage, targetUserId, flags);
21544            CrossProfileIntentResolver resolver =
21545                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21546            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21547            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21548            if (existing != null) {
21549                int size = existing.size();
21550                for (int i = 0; i < size; i++) {
21551                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21552                        return;
21553                    }
21554                }
21555            }
21556            resolver.addFilter(newFilter);
21557            scheduleWritePackageRestrictionsLocked(sourceUserId);
21558        }
21559    }
21560
21561    @Override
21562    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21563        mContext.enforceCallingOrSelfPermission(
21564                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21565        final int callingUid = Binder.getCallingUid();
21566        enforceOwnerRights(ownerPackage, callingUid);
21567        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21568        synchronized (mPackages) {
21569            CrossProfileIntentResolver resolver =
21570                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21571            ArraySet<CrossProfileIntentFilter> set =
21572                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21573            for (CrossProfileIntentFilter filter : set) {
21574                if (filter.getOwnerPackage().equals(ownerPackage)) {
21575                    resolver.removeFilter(filter);
21576                }
21577            }
21578            scheduleWritePackageRestrictionsLocked(sourceUserId);
21579        }
21580    }
21581
21582    // Enforcing that callingUid is owning pkg on userId
21583    private void enforceOwnerRights(String pkg, int callingUid) {
21584        // The system owns everything.
21585        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21586            return;
21587        }
21588        final int callingUserId = UserHandle.getUserId(callingUid);
21589        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21590        if (pi == null) {
21591            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21592                    + callingUserId);
21593        }
21594        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21595            throw new SecurityException("Calling uid " + callingUid
21596                    + " does not own package " + pkg);
21597        }
21598    }
21599
21600    @Override
21601    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21602        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21603            return null;
21604        }
21605        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21606    }
21607
21608    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21609        UserManagerService ums = UserManagerService.getInstance();
21610        if (ums != null) {
21611            final UserInfo parent = ums.getProfileParent(userId);
21612            final int launcherUid = (parent != null) ? parent.id : userId;
21613            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21614            if (launcherComponent != null) {
21615                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21616                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21617                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21618                        .setPackage(launcherComponent.getPackageName());
21619                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21620            }
21621        }
21622    }
21623
21624    /**
21625     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21626     * then reports the most likely home activity or null if there are more than one.
21627     */
21628    private ComponentName getDefaultHomeActivity(int userId) {
21629        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21630        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21631        if (cn != null) {
21632            return cn;
21633        }
21634
21635        // Find the launcher with the highest priority and return that component if there are no
21636        // other home activity with the same priority.
21637        int lastPriority = Integer.MIN_VALUE;
21638        ComponentName lastComponent = null;
21639        final int size = allHomeCandidates.size();
21640        for (int i = 0; i < size; i++) {
21641            final ResolveInfo ri = allHomeCandidates.get(i);
21642            if (ri.priority > lastPriority) {
21643                lastComponent = ri.activityInfo.getComponentName();
21644                lastPriority = ri.priority;
21645            } else if (ri.priority == lastPriority) {
21646                // Two components found with same priority.
21647                lastComponent = null;
21648            }
21649        }
21650        return lastComponent;
21651    }
21652
21653    private Intent getHomeIntent() {
21654        Intent intent = new Intent(Intent.ACTION_MAIN);
21655        intent.addCategory(Intent.CATEGORY_HOME);
21656        intent.addCategory(Intent.CATEGORY_DEFAULT);
21657        return intent;
21658    }
21659
21660    private IntentFilter getHomeFilter() {
21661        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21662        filter.addCategory(Intent.CATEGORY_HOME);
21663        filter.addCategory(Intent.CATEGORY_DEFAULT);
21664        return filter;
21665    }
21666
21667    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21668            int userId) {
21669        Intent intent  = getHomeIntent();
21670        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21671                PackageManager.GET_META_DATA, userId);
21672        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21673                true, false, false, userId);
21674
21675        allHomeCandidates.clear();
21676        if (list != null) {
21677            for (ResolveInfo ri : list) {
21678                allHomeCandidates.add(ri);
21679            }
21680        }
21681        return (preferred == null || preferred.activityInfo == null)
21682                ? null
21683                : new ComponentName(preferred.activityInfo.packageName,
21684                        preferred.activityInfo.name);
21685    }
21686
21687    @Override
21688    public void setHomeActivity(ComponentName comp, int userId) {
21689        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21690            return;
21691        }
21692        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21693        getHomeActivitiesAsUser(homeActivities, userId);
21694
21695        boolean found = false;
21696
21697        final int size = homeActivities.size();
21698        final ComponentName[] set = new ComponentName[size];
21699        for (int i = 0; i < size; i++) {
21700            final ResolveInfo candidate = homeActivities.get(i);
21701            final ActivityInfo info = candidate.activityInfo;
21702            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21703            set[i] = activityName;
21704            if (!found && activityName.equals(comp)) {
21705                found = true;
21706            }
21707        }
21708        if (!found) {
21709            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21710                    + userId);
21711        }
21712        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21713                set, comp, userId);
21714    }
21715
21716    private @Nullable String getSetupWizardPackageName() {
21717        final Intent intent = new Intent(Intent.ACTION_MAIN);
21718        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21719
21720        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21721                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21722                        | MATCH_DISABLED_COMPONENTS,
21723                UserHandle.myUserId());
21724        if (matches.size() == 1) {
21725            return matches.get(0).getComponentInfo().packageName;
21726        } else {
21727            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21728                    + ": matches=" + matches);
21729            return null;
21730        }
21731    }
21732
21733    private @Nullable String getStorageManagerPackageName() {
21734        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21735
21736        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21737                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21738                        | MATCH_DISABLED_COMPONENTS,
21739                UserHandle.myUserId());
21740        if (matches.size() == 1) {
21741            return matches.get(0).getComponentInfo().packageName;
21742        } else {
21743            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21744                    + matches.size() + ": matches=" + matches);
21745            return null;
21746        }
21747    }
21748
21749    @Override
21750    public void setApplicationEnabledSetting(String appPackageName,
21751            int newState, int flags, int userId, String callingPackage) {
21752        if (!sUserManager.exists(userId)) return;
21753        if (callingPackage == null) {
21754            callingPackage = Integer.toString(Binder.getCallingUid());
21755        }
21756        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21757    }
21758
21759    @Override
21760    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21761        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21762        synchronized (mPackages) {
21763            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21764            if (pkgSetting != null) {
21765                pkgSetting.setUpdateAvailable(updateAvailable);
21766            }
21767        }
21768    }
21769
21770    @Override
21771    public void setComponentEnabledSetting(ComponentName componentName,
21772            int newState, int flags, int userId) {
21773        if (!sUserManager.exists(userId)) return;
21774        setEnabledSetting(componentName.getPackageName(),
21775                componentName.getClassName(), newState, flags, userId, null);
21776    }
21777
21778    private void setEnabledSetting(final String packageName, String className, int newState,
21779            final int flags, int userId, String callingPackage) {
21780        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21781              || newState == COMPONENT_ENABLED_STATE_ENABLED
21782              || newState == COMPONENT_ENABLED_STATE_DISABLED
21783              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21784              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21785            throw new IllegalArgumentException("Invalid new component state: "
21786                    + newState);
21787        }
21788        PackageSetting pkgSetting;
21789        final int callingUid = Binder.getCallingUid();
21790        final int permission;
21791        if (callingUid == Process.SYSTEM_UID) {
21792            permission = PackageManager.PERMISSION_GRANTED;
21793        } else {
21794            permission = mContext.checkCallingOrSelfPermission(
21795                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21796        }
21797        enforceCrossUserPermission(callingUid, userId,
21798                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21799        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21800        boolean sendNow = false;
21801        boolean isApp = (className == null);
21802        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21803        String componentName = isApp ? packageName : className;
21804        int packageUid = -1;
21805        ArrayList<String> components;
21806
21807        // reader
21808        synchronized (mPackages) {
21809            pkgSetting = mSettings.mPackages.get(packageName);
21810            if (pkgSetting == null) {
21811                if (!isCallerInstantApp) {
21812                    if (className == null) {
21813                        throw new IllegalArgumentException("Unknown package: " + packageName);
21814                    }
21815                    throw new IllegalArgumentException(
21816                            "Unknown component: " + packageName + "/" + className);
21817                } else {
21818                    // throw SecurityException to prevent leaking package information
21819                    throw new SecurityException(
21820                            "Attempt to change component state; "
21821                            + "pid=" + Binder.getCallingPid()
21822                            + ", uid=" + callingUid
21823                            + (className == null
21824                                    ? ", package=" + packageName
21825                                    : ", component=" + packageName + "/" + className));
21826                }
21827            }
21828        }
21829
21830        // Limit who can change which apps
21831        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21832            // Don't allow apps that don't have permission to modify other apps
21833            if (!allowedByPermission
21834                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21835                throw new SecurityException(
21836                        "Attempt to change component state; "
21837                        + "pid=" + Binder.getCallingPid()
21838                        + ", uid=" + callingUid
21839                        + (className == null
21840                                ? ", package=" + packageName
21841                                : ", component=" + packageName + "/" + className));
21842            }
21843            // Don't allow changing protected packages.
21844            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21845                throw new SecurityException("Cannot disable a protected package: " + packageName);
21846            }
21847        }
21848
21849        synchronized (mPackages) {
21850            if (callingUid == Process.SHELL_UID
21851                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21852                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21853                // unless it is a test package.
21854                int oldState = pkgSetting.getEnabled(userId);
21855                if (className == null
21856                        &&
21857                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21858                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21859                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21860                        &&
21861                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21862                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21863                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21864                    // ok
21865                } else {
21866                    throw new SecurityException(
21867                            "Shell cannot change component state for " + packageName + "/"
21868                                    + className + " to " + newState);
21869                }
21870            }
21871        }
21872        if (className == null) {
21873            // We're dealing with an application/package level state change
21874            synchronized (mPackages) {
21875                if (pkgSetting.getEnabled(userId) == newState) {
21876                    // Nothing to do
21877                    return;
21878                }
21879            }
21880            // If we're enabling a system stub, there's a little more work to do.
21881            // Prior to enabling the package, we need to decompress the APK(s) to the
21882            // data partition and then replace the version on the system partition.
21883            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21884            final boolean isSystemStub = deletedPkg.isStub
21885                    && deletedPkg.isSystemApp();
21886            if (isSystemStub
21887                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21888                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21889                final File codePath = decompressPackage(deletedPkg);
21890                if (codePath == null) {
21891                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21892                    return;
21893                }
21894                // TODO remove direct parsing of the package object during internal cleanup
21895                // of scan package
21896                // We need to call parse directly here for no other reason than we need
21897                // the new package in order to disable the old one [we use the information
21898                // for some internal optimization to optionally create a new package setting
21899                // object on replace]. However, we can't get the package from the scan
21900                // because the scan modifies live structures and we need to remove the
21901                // old [system] package from the system before a scan can be attempted.
21902                // Once scan is indempotent we can remove this parse and use the package
21903                // object we scanned, prior to adding it to package settings.
21904                final PackageParser pp = new PackageParser();
21905                pp.setSeparateProcesses(mSeparateProcesses);
21906                pp.setDisplayMetrics(mMetrics);
21907                pp.setCallback(mPackageParserCallback);
21908                final PackageParser.Package tmpPkg;
21909                try {
21910                    final int parseFlags = mDefParseFlags
21911                            | PackageParser.PARSE_MUST_BE_APK
21912                            | PackageParser.PARSE_IS_SYSTEM
21913                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21914                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21915                } catch (PackageParserException e) {
21916                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21917                    return;
21918                }
21919                synchronized (mInstallLock) {
21920                    // Disable the stub and remove any package entries
21921                    removePackageLI(deletedPkg, true);
21922                    synchronized (mPackages) {
21923                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21924                    }
21925                    final PackageParser.Package newPkg;
21926                    try (PackageFreezer freezer =
21927                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21928                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21929                                | PackageParser.PARSE_ENFORCE_CODE;
21930                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21931                                0 /*currentTime*/, null /*user*/);
21932                        prepareAppDataAfterInstallLIF(newPkg);
21933                        synchronized (mPackages) {
21934                            try {
21935                                updateSharedLibrariesLPr(newPkg, null);
21936                            } catch (PackageManagerException e) {
21937                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21938                            }
21939                            updatePermissionsLPw(newPkg.packageName, newPkg,
21940                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21941                            mSettings.writeLPr();
21942                        }
21943                    } catch (PackageManagerException e) {
21944                        // Whoops! Something went wrong; try to roll back to the stub
21945                        Slog.w(TAG, "Failed to install compressed system package:"
21946                                + pkgSetting.name, e);
21947                        // Remove the failed install
21948                        removeCodePathLI(codePath);
21949
21950                        // Install the system package
21951                        try (PackageFreezer freezer =
21952                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21953                            synchronized (mPackages) {
21954                                // NOTE: The system package always needs to be enabled; even
21955                                // if it's for a compressed stub. If we don't, installing the
21956                                // system package fails during scan [scanning checks the disabled
21957                                // packages]. We will reverse this later, after we've "installed"
21958                                // the stub.
21959                                // This leaves us in a fragile state; the stub should never be
21960                                // enabled, so, cross your fingers and hope nothing goes wrong
21961                                // until we can disable the package later.
21962                                enableSystemPackageLPw(deletedPkg);
21963                            }
21964                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
21965                                    false /*isPrivileged*/, null /*allUserHandles*/,
21966                                    null /*origUserHandles*/, null /*origPermissionsState*/,
21967                                    true /*writeSettings*/);
21968                        } catch (PackageManagerException pme) {
21969                            Slog.w(TAG, "Failed to restore system package:"
21970                                    + deletedPkg.packageName, pme);
21971                        } finally {
21972                            synchronized (mPackages) {
21973                                mSettings.disableSystemPackageLPw(
21974                                        deletedPkg.packageName, true /*replaced*/);
21975                                mSettings.writeLPr();
21976                            }
21977                        }
21978                        return;
21979                    }
21980                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
21981                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21982                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
21983                    mDexManager.notifyPackageUpdated(newPkg.packageName,
21984                            newPkg.baseCodePath, newPkg.splitCodePaths);
21985                }
21986            }
21987            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21988                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21989                // Don't care about who enables an app.
21990                callingPackage = null;
21991            }
21992            synchronized (mPackages) {
21993                pkgSetting.setEnabled(newState, userId, callingPackage);
21994            }
21995        } else {
21996            synchronized (mPackages) {
21997                // We're dealing with a component level state change
21998                // First, verify that this is a valid class name.
21999                PackageParser.Package pkg = pkgSetting.pkg;
22000                if (pkg == null || !pkg.hasComponentClassName(className)) {
22001                    if (pkg != null &&
22002                            pkg.applicationInfo.targetSdkVersion >=
22003                                    Build.VERSION_CODES.JELLY_BEAN) {
22004                        throw new IllegalArgumentException("Component class " + className
22005                                + " does not exist in " + packageName);
22006                    } else {
22007                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
22008                                + className + " does not exist in " + packageName);
22009                    }
22010                }
22011                switch (newState) {
22012                    case COMPONENT_ENABLED_STATE_ENABLED:
22013                        if (!pkgSetting.enableComponentLPw(className, userId)) {
22014                            return;
22015                        }
22016                        break;
22017                    case COMPONENT_ENABLED_STATE_DISABLED:
22018                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22019                            return;
22020                        }
22021                        break;
22022                    case COMPONENT_ENABLED_STATE_DEFAULT:
22023                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22024                            return;
22025                        }
22026                        break;
22027                    default:
22028                        Slog.e(TAG, "Invalid new component state: " + newState);
22029                        return;
22030                }
22031            }
22032        }
22033        synchronized (mPackages) {
22034            scheduleWritePackageRestrictionsLocked(userId);
22035            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22036            final long callingId = Binder.clearCallingIdentity();
22037            try {
22038                updateInstantAppInstallerLocked(packageName);
22039            } finally {
22040                Binder.restoreCallingIdentity(callingId);
22041            }
22042            components = mPendingBroadcasts.get(userId, packageName);
22043            final boolean newPackage = components == null;
22044            if (newPackage) {
22045                components = new ArrayList<String>();
22046            }
22047            if (!components.contains(componentName)) {
22048                components.add(componentName);
22049            }
22050            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22051                sendNow = true;
22052                // Purge entry from pending broadcast list if another one exists already
22053                // since we are sending one right away.
22054                mPendingBroadcasts.remove(userId, packageName);
22055            } else {
22056                if (newPackage) {
22057                    mPendingBroadcasts.put(userId, packageName, components);
22058                }
22059                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22060                    // Schedule a message
22061                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22062                }
22063            }
22064        }
22065
22066        long callingId = Binder.clearCallingIdentity();
22067        try {
22068            if (sendNow) {
22069                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22070                sendPackageChangedBroadcast(packageName,
22071                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22072            }
22073        } finally {
22074            Binder.restoreCallingIdentity(callingId);
22075        }
22076    }
22077
22078    @Override
22079    public void flushPackageRestrictionsAsUser(int userId) {
22080        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22081            return;
22082        }
22083        if (!sUserManager.exists(userId)) {
22084            return;
22085        }
22086        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22087                false /* checkShell */, "flushPackageRestrictions");
22088        synchronized (mPackages) {
22089            mSettings.writePackageRestrictionsLPr(userId);
22090            mDirtyUsers.remove(userId);
22091            if (mDirtyUsers.isEmpty()) {
22092                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22093            }
22094        }
22095    }
22096
22097    private void sendPackageChangedBroadcast(String packageName,
22098            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22099        if (DEBUG_INSTALL)
22100            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22101                    + componentNames);
22102        Bundle extras = new Bundle(4);
22103        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22104        String nameList[] = new String[componentNames.size()];
22105        componentNames.toArray(nameList);
22106        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22107        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22108        extras.putInt(Intent.EXTRA_UID, packageUid);
22109        // If this is not reporting a change of the overall package, then only send it
22110        // to registered receivers.  We don't want to launch a swath of apps for every
22111        // little component state change.
22112        final int flags = !componentNames.contains(packageName)
22113                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22114        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22115                new int[] {UserHandle.getUserId(packageUid)});
22116    }
22117
22118    @Override
22119    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22120        if (!sUserManager.exists(userId)) return;
22121        final int callingUid = Binder.getCallingUid();
22122        if (getInstantAppPackageName(callingUid) != null) {
22123            return;
22124        }
22125        final int permission = mContext.checkCallingOrSelfPermission(
22126                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22127        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22128        enforceCrossUserPermission(callingUid, userId,
22129                true /* requireFullPermission */, true /* checkShell */, "stop package");
22130        // writer
22131        synchronized (mPackages) {
22132            final PackageSetting ps = mSettings.mPackages.get(packageName);
22133            if (!filterAppAccessLPr(ps, callingUid, userId)
22134                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22135                            allowedByPermission, callingUid, userId)) {
22136                scheduleWritePackageRestrictionsLocked(userId);
22137            }
22138        }
22139    }
22140
22141    @Override
22142    public String getInstallerPackageName(String packageName) {
22143        final int callingUid = Binder.getCallingUid();
22144        if (getInstantAppPackageName(callingUid) != null) {
22145            return null;
22146        }
22147        // reader
22148        synchronized (mPackages) {
22149            final PackageSetting ps = mSettings.mPackages.get(packageName);
22150            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22151                return null;
22152            }
22153            return mSettings.getInstallerPackageNameLPr(packageName);
22154        }
22155    }
22156
22157    public boolean isOrphaned(String packageName) {
22158        // reader
22159        synchronized (mPackages) {
22160            return mSettings.isOrphaned(packageName);
22161        }
22162    }
22163
22164    @Override
22165    public int getApplicationEnabledSetting(String packageName, int userId) {
22166        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22167        int callingUid = Binder.getCallingUid();
22168        enforceCrossUserPermission(callingUid, userId,
22169                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22170        // reader
22171        synchronized (mPackages) {
22172            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22173                return COMPONENT_ENABLED_STATE_DISABLED;
22174            }
22175            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22176        }
22177    }
22178
22179    @Override
22180    public int getComponentEnabledSetting(ComponentName component, int userId) {
22181        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22182        int callingUid = Binder.getCallingUid();
22183        enforceCrossUserPermission(callingUid, userId,
22184                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22185        synchronized (mPackages) {
22186            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22187                    component, TYPE_UNKNOWN, userId)) {
22188                return COMPONENT_ENABLED_STATE_DISABLED;
22189            }
22190            return mSettings.getComponentEnabledSettingLPr(component, userId);
22191        }
22192    }
22193
22194    @Override
22195    public void enterSafeMode() {
22196        enforceSystemOrRoot("Only the system can request entering safe mode");
22197
22198        if (!mSystemReady) {
22199            mSafeMode = true;
22200        }
22201    }
22202
22203    @Override
22204    public void systemReady() {
22205        enforceSystemOrRoot("Only the system can claim the system is ready");
22206
22207        mSystemReady = true;
22208        final ContentResolver resolver = mContext.getContentResolver();
22209        ContentObserver co = new ContentObserver(mHandler) {
22210            @Override
22211            public void onChange(boolean selfChange) {
22212                mEphemeralAppsDisabled =
22213                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22214                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22215            }
22216        };
22217        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22218                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22219                false, co, UserHandle.USER_SYSTEM);
22220        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22221                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22222        co.onChange(true);
22223
22224        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22225        // disabled after already being started.
22226        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22227                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22228
22229        // Read the compatibilty setting when the system is ready.
22230        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22231                mContext.getContentResolver(),
22232                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22233        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22234        if (DEBUG_SETTINGS) {
22235            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22236        }
22237
22238        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22239
22240        synchronized (mPackages) {
22241            // Verify that all of the preferred activity components actually
22242            // exist.  It is possible for applications to be updated and at
22243            // that point remove a previously declared activity component that
22244            // had been set as a preferred activity.  We try to clean this up
22245            // the next time we encounter that preferred activity, but it is
22246            // possible for the user flow to never be able to return to that
22247            // situation so here we do a sanity check to make sure we haven't
22248            // left any junk around.
22249            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22250            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22251                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22252                removed.clear();
22253                for (PreferredActivity pa : pir.filterSet()) {
22254                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22255                        removed.add(pa);
22256                    }
22257                }
22258                if (removed.size() > 0) {
22259                    for (int r=0; r<removed.size(); r++) {
22260                        PreferredActivity pa = removed.get(r);
22261                        Slog.w(TAG, "Removing dangling preferred activity: "
22262                                + pa.mPref.mComponent);
22263                        pir.removeFilter(pa);
22264                    }
22265                    mSettings.writePackageRestrictionsLPr(
22266                            mSettings.mPreferredActivities.keyAt(i));
22267                }
22268            }
22269
22270            for (int userId : UserManagerService.getInstance().getUserIds()) {
22271                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22272                    grantPermissionsUserIds = ArrayUtils.appendInt(
22273                            grantPermissionsUserIds, userId);
22274                }
22275            }
22276        }
22277        sUserManager.systemReady();
22278
22279        // If we upgraded grant all default permissions before kicking off.
22280        for (int userId : grantPermissionsUserIds) {
22281            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22282        }
22283
22284        // If we did not grant default permissions, we preload from this the
22285        // default permission exceptions lazily to ensure we don't hit the
22286        // disk on a new user creation.
22287        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22288            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22289        }
22290
22291        // Kick off any messages waiting for system ready
22292        if (mPostSystemReadyMessages != null) {
22293            for (Message msg : mPostSystemReadyMessages) {
22294                msg.sendToTarget();
22295            }
22296            mPostSystemReadyMessages = null;
22297        }
22298
22299        // Watch for external volumes that come and go over time
22300        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22301        storage.registerListener(mStorageListener);
22302
22303        mInstallerService.systemReady();
22304        mPackageDexOptimizer.systemReady();
22305
22306        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22307                StorageManagerInternal.class);
22308        StorageManagerInternal.addExternalStoragePolicy(
22309                new StorageManagerInternal.ExternalStorageMountPolicy() {
22310            @Override
22311            public int getMountMode(int uid, String packageName) {
22312                if (Process.isIsolated(uid)) {
22313                    return Zygote.MOUNT_EXTERNAL_NONE;
22314                }
22315                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22316                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22317                }
22318                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22319                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22320                }
22321                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22322                    return Zygote.MOUNT_EXTERNAL_READ;
22323                }
22324                return Zygote.MOUNT_EXTERNAL_WRITE;
22325            }
22326
22327            @Override
22328            public boolean hasExternalStorage(int uid, String packageName) {
22329                return true;
22330            }
22331        });
22332
22333        // Now that we're mostly running, clean up stale users and apps
22334        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22335        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22336
22337        if (mPrivappPermissionsViolations != null) {
22338            Slog.wtf(TAG,"Signature|privileged permissions not in "
22339                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22340            mPrivappPermissionsViolations = null;
22341        }
22342    }
22343
22344    public void waitForAppDataPrepared() {
22345        if (mPrepareAppDataFuture == null) {
22346            return;
22347        }
22348        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22349        mPrepareAppDataFuture = null;
22350    }
22351
22352    @Override
22353    public boolean isSafeMode() {
22354        // allow instant applications
22355        return mSafeMode;
22356    }
22357
22358    @Override
22359    public boolean hasSystemUidErrors() {
22360        // allow instant applications
22361        return mHasSystemUidErrors;
22362    }
22363
22364    static String arrayToString(int[] array) {
22365        StringBuffer buf = new StringBuffer(128);
22366        buf.append('[');
22367        if (array != null) {
22368            for (int i=0; i<array.length; i++) {
22369                if (i > 0) buf.append(", ");
22370                buf.append(array[i]);
22371            }
22372        }
22373        buf.append(']');
22374        return buf.toString();
22375    }
22376
22377    static class DumpState {
22378        public static final int DUMP_LIBS = 1 << 0;
22379        public static final int DUMP_FEATURES = 1 << 1;
22380        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22381        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22382        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22383        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22384        public static final int DUMP_PERMISSIONS = 1 << 6;
22385        public static final int DUMP_PACKAGES = 1 << 7;
22386        public static final int DUMP_SHARED_USERS = 1 << 8;
22387        public static final int DUMP_MESSAGES = 1 << 9;
22388        public static final int DUMP_PROVIDERS = 1 << 10;
22389        public static final int DUMP_VERIFIERS = 1 << 11;
22390        public static final int DUMP_PREFERRED = 1 << 12;
22391        public static final int DUMP_PREFERRED_XML = 1 << 13;
22392        public static final int DUMP_KEYSETS = 1 << 14;
22393        public static final int DUMP_VERSION = 1 << 15;
22394        public static final int DUMP_INSTALLS = 1 << 16;
22395        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22396        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22397        public static final int DUMP_FROZEN = 1 << 19;
22398        public static final int DUMP_DEXOPT = 1 << 20;
22399        public static final int DUMP_COMPILER_STATS = 1 << 21;
22400        public static final int DUMP_CHANGES = 1 << 22;
22401        public static final int DUMP_VOLUMES = 1 << 23;
22402
22403        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22404
22405        private int mTypes;
22406
22407        private int mOptions;
22408
22409        private boolean mTitlePrinted;
22410
22411        private SharedUserSetting mSharedUser;
22412
22413        public boolean isDumping(int type) {
22414            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22415                return true;
22416            }
22417
22418            return (mTypes & type) != 0;
22419        }
22420
22421        public void setDump(int type) {
22422            mTypes |= type;
22423        }
22424
22425        public boolean isOptionEnabled(int option) {
22426            return (mOptions & option) != 0;
22427        }
22428
22429        public void setOptionEnabled(int option) {
22430            mOptions |= option;
22431        }
22432
22433        public boolean onTitlePrinted() {
22434            final boolean printed = mTitlePrinted;
22435            mTitlePrinted = true;
22436            return printed;
22437        }
22438
22439        public boolean getTitlePrinted() {
22440            return mTitlePrinted;
22441        }
22442
22443        public void setTitlePrinted(boolean enabled) {
22444            mTitlePrinted = enabled;
22445        }
22446
22447        public SharedUserSetting getSharedUser() {
22448            return mSharedUser;
22449        }
22450
22451        public void setSharedUser(SharedUserSetting user) {
22452            mSharedUser = user;
22453        }
22454    }
22455
22456    @Override
22457    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22458            FileDescriptor err, String[] args, ShellCallback callback,
22459            ResultReceiver resultReceiver) {
22460        (new PackageManagerShellCommand(this)).exec(
22461                this, in, out, err, args, callback, resultReceiver);
22462    }
22463
22464    @Override
22465    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22466        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22467
22468        DumpState dumpState = new DumpState();
22469        boolean fullPreferred = false;
22470        boolean checkin = false;
22471
22472        String packageName = null;
22473        ArraySet<String> permissionNames = null;
22474
22475        int opti = 0;
22476        while (opti < args.length) {
22477            String opt = args[opti];
22478            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22479                break;
22480            }
22481            opti++;
22482
22483            if ("-a".equals(opt)) {
22484                // Right now we only know how to print all.
22485            } else if ("-h".equals(opt)) {
22486                pw.println("Package manager dump options:");
22487                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22488                pw.println("    --checkin: dump for a checkin");
22489                pw.println("    -f: print details of intent filters");
22490                pw.println("    -h: print this help");
22491                pw.println("  cmd may be one of:");
22492                pw.println("    l[ibraries]: list known shared libraries");
22493                pw.println("    f[eatures]: list device features");
22494                pw.println("    k[eysets]: print known keysets");
22495                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22496                pw.println("    perm[issions]: dump permissions");
22497                pw.println("    permission [name ...]: dump declaration and use of given permission");
22498                pw.println("    pref[erred]: print preferred package settings");
22499                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22500                pw.println("    prov[iders]: dump content providers");
22501                pw.println("    p[ackages]: dump installed packages");
22502                pw.println("    s[hared-users]: dump shared user IDs");
22503                pw.println("    m[essages]: print collected runtime messages");
22504                pw.println("    v[erifiers]: print package verifier info");
22505                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22506                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22507                pw.println("    version: print database version info");
22508                pw.println("    write: write current settings now");
22509                pw.println("    installs: details about install sessions");
22510                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22511                pw.println("    dexopt: dump dexopt state");
22512                pw.println("    compiler-stats: dump compiler statistics");
22513                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22514                pw.println("    <package.name>: info about given package");
22515                return;
22516            } else if ("--checkin".equals(opt)) {
22517                checkin = true;
22518            } else if ("-f".equals(opt)) {
22519                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22520            } else if ("--proto".equals(opt)) {
22521                dumpProto(fd);
22522                return;
22523            } else {
22524                pw.println("Unknown argument: " + opt + "; use -h for help");
22525            }
22526        }
22527
22528        // Is the caller requesting to dump a particular piece of data?
22529        if (opti < args.length) {
22530            String cmd = args[opti];
22531            opti++;
22532            // Is this a package name?
22533            if ("android".equals(cmd) || cmd.contains(".")) {
22534                packageName = cmd;
22535                // When dumping a single package, we always dump all of its
22536                // filter information since the amount of data will be reasonable.
22537                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22538            } else if ("check-permission".equals(cmd)) {
22539                if (opti >= args.length) {
22540                    pw.println("Error: check-permission missing permission argument");
22541                    return;
22542                }
22543                String perm = args[opti];
22544                opti++;
22545                if (opti >= args.length) {
22546                    pw.println("Error: check-permission missing package argument");
22547                    return;
22548                }
22549
22550                String pkg = args[opti];
22551                opti++;
22552                int user = UserHandle.getUserId(Binder.getCallingUid());
22553                if (opti < args.length) {
22554                    try {
22555                        user = Integer.parseInt(args[opti]);
22556                    } catch (NumberFormatException e) {
22557                        pw.println("Error: check-permission user argument is not a number: "
22558                                + args[opti]);
22559                        return;
22560                    }
22561                }
22562
22563                // Normalize package name to handle renamed packages and static libs
22564                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22565
22566                pw.println(checkPermission(perm, pkg, user));
22567                return;
22568            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22569                dumpState.setDump(DumpState.DUMP_LIBS);
22570            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22571                dumpState.setDump(DumpState.DUMP_FEATURES);
22572            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22573                if (opti >= args.length) {
22574                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22575                            | DumpState.DUMP_SERVICE_RESOLVERS
22576                            | DumpState.DUMP_RECEIVER_RESOLVERS
22577                            | DumpState.DUMP_CONTENT_RESOLVERS);
22578                } else {
22579                    while (opti < args.length) {
22580                        String name = args[opti];
22581                        if ("a".equals(name) || "activity".equals(name)) {
22582                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22583                        } else if ("s".equals(name) || "service".equals(name)) {
22584                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22585                        } else if ("r".equals(name) || "receiver".equals(name)) {
22586                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22587                        } else if ("c".equals(name) || "content".equals(name)) {
22588                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22589                        } else {
22590                            pw.println("Error: unknown resolver table type: " + name);
22591                            return;
22592                        }
22593                        opti++;
22594                    }
22595                }
22596            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22597                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22598            } else if ("permission".equals(cmd)) {
22599                if (opti >= args.length) {
22600                    pw.println("Error: permission requires permission name");
22601                    return;
22602                }
22603                permissionNames = new ArraySet<>();
22604                while (opti < args.length) {
22605                    permissionNames.add(args[opti]);
22606                    opti++;
22607                }
22608                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22609                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22610            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22611                dumpState.setDump(DumpState.DUMP_PREFERRED);
22612            } else if ("preferred-xml".equals(cmd)) {
22613                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22614                if (opti < args.length && "--full".equals(args[opti])) {
22615                    fullPreferred = true;
22616                    opti++;
22617                }
22618            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22619                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22620            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22621                dumpState.setDump(DumpState.DUMP_PACKAGES);
22622            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22623                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22624            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22625                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22626            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22627                dumpState.setDump(DumpState.DUMP_MESSAGES);
22628            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22629                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22630            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22631                    || "intent-filter-verifiers".equals(cmd)) {
22632                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22633            } else if ("version".equals(cmd)) {
22634                dumpState.setDump(DumpState.DUMP_VERSION);
22635            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22636                dumpState.setDump(DumpState.DUMP_KEYSETS);
22637            } else if ("installs".equals(cmd)) {
22638                dumpState.setDump(DumpState.DUMP_INSTALLS);
22639            } else if ("frozen".equals(cmd)) {
22640                dumpState.setDump(DumpState.DUMP_FROZEN);
22641            } else if ("volumes".equals(cmd)) {
22642                dumpState.setDump(DumpState.DUMP_VOLUMES);
22643            } else if ("dexopt".equals(cmd)) {
22644                dumpState.setDump(DumpState.DUMP_DEXOPT);
22645            } else if ("compiler-stats".equals(cmd)) {
22646                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22647            } else if ("changes".equals(cmd)) {
22648                dumpState.setDump(DumpState.DUMP_CHANGES);
22649            } else if ("write".equals(cmd)) {
22650                synchronized (mPackages) {
22651                    mSettings.writeLPr();
22652                    pw.println("Settings written.");
22653                    return;
22654                }
22655            }
22656        }
22657
22658        if (checkin) {
22659            pw.println("vers,1");
22660        }
22661
22662        // reader
22663        synchronized (mPackages) {
22664            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22665                if (!checkin) {
22666                    if (dumpState.onTitlePrinted())
22667                        pw.println();
22668                    pw.println("Database versions:");
22669                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22670                }
22671            }
22672
22673            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22674                if (!checkin) {
22675                    if (dumpState.onTitlePrinted())
22676                        pw.println();
22677                    pw.println("Verifiers:");
22678                    pw.print("  Required: ");
22679                    pw.print(mRequiredVerifierPackage);
22680                    pw.print(" (uid=");
22681                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22682                            UserHandle.USER_SYSTEM));
22683                    pw.println(")");
22684                } else if (mRequiredVerifierPackage != null) {
22685                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22686                    pw.print(",");
22687                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22688                            UserHandle.USER_SYSTEM));
22689                }
22690            }
22691
22692            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22693                    packageName == null) {
22694                if (mIntentFilterVerifierComponent != null) {
22695                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22696                    if (!checkin) {
22697                        if (dumpState.onTitlePrinted())
22698                            pw.println();
22699                        pw.println("Intent Filter Verifier:");
22700                        pw.print("  Using: ");
22701                        pw.print(verifierPackageName);
22702                        pw.print(" (uid=");
22703                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22704                                UserHandle.USER_SYSTEM));
22705                        pw.println(")");
22706                    } else if (verifierPackageName != null) {
22707                        pw.print("ifv,"); pw.print(verifierPackageName);
22708                        pw.print(",");
22709                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22710                                UserHandle.USER_SYSTEM));
22711                    }
22712                } else {
22713                    pw.println();
22714                    pw.println("No Intent Filter Verifier available!");
22715                }
22716            }
22717
22718            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22719                boolean printedHeader = false;
22720                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22721                while (it.hasNext()) {
22722                    String libName = it.next();
22723                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22724                    if (versionedLib == null) {
22725                        continue;
22726                    }
22727                    final int versionCount = versionedLib.size();
22728                    for (int i = 0; i < versionCount; i++) {
22729                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22730                        if (!checkin) {
22731                            if (!printedHeader) {
22732                                if (dumpState.onTitlePrinted())
22733                                    pw.println();
22734                                pw.println("Libraries:");
22735                                printedHeader = true;
22736                            }
22737                            pw.print("  ");
22738                        } else {
22739                            pw.print("lib,");
22740                        }
22741                        pw.print(libEntry.info.getName());
22742                        if (libEntry.info.isStatic()) {
22743                            pw.print(" version=" + libEntry.info.getVersion());
22744                        }
22745                        if (!checkin) {
22746                            pw.print(" -> ");
22747                        }
22748                        if (libEntry.path != null) {
22749                            pw.print(" (jar) ");
22750                            pw.print(libEntry.path);
22751                        } else {
22752                            pw.print(" (apk) ");
22753                            pw.print(libEntry.apk);
22754                        }
22755                        pw.println();
22756                    }
22757                }
22758            }
22759
22760            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22761                if (dumpState.onTitlePrinted())
22762                    pw.println();
22763                if (!checkin) {
22764                    pw.println("Features:");
22765                }
22766
22767                synchronized (mAvailableFeatures) {
22768                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22769                        if (checkin) {
22770                            pw.print("feat,");
22771                            pw.print(feat.name);
22772                            pw.print(",");
22773                            pw.println(feat.version);
22774                        } else {
22775                            pw.print("  ");
22776                            pw.print(feat.name);
22777                            if (feat.version > 0) {
22778                                pw.print(" version=");
22779                                pw.print(feat.version);
22780                            }
22781                            pw.println();
22782                        }
22783                    }
22784                }
22785            }
22786
22787            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22788                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22789                        : "Activity Resolver Table:", "  ", packageName,
22790                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22791                    dumpState.setTitlePrinted(true);
22792                }
22793            }
22794            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22795                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22796                        : "Receiver Resolver Table:", "  ", packageName,
22797                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22798                    dumpState.setTitlePrinted(true);
22799                }
22800            }
22801            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22802                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22803                        : "Service Resolver Table:", "  ", packageName,
22804                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22805                    dumpState.setTitlePrinted(true);
22806                }
22807            }
22808            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22809                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22810                        : "Provider Resolver Table:", "  ", packageName,
22811                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22812                    dumpState.setTitlePrinted(true);
22813                }
22814            }
22815
22816            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22817                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22818                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22819                    int user = mSettings.mPreferredActivities.keyAt(i);
22820                    if (pir.dump(pw,
22821                            dumpState.getTitlePrinted()
22822                                ? "\nPreferred Activities User " + user + ":"
22823                                : "Preferred Activities User " + user + ":", "  ",
22824                            packageName, true, false)) {
22825                        dumpState.setTitlePrinted(true);
22826                    }
22827                }
22828            }
22829
22830            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22831                pw.flush();
22832                FileOutputStream fout = new FileOutputStream(fd);
22833                BufferedOutputStream str = new BufferedOutputStream(fout);
22834                XmlSerializer serializer = new FastXmlSerializer();
22835                try {
22836                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22837                    serializer.startDocument(null, true);
22838                    serializer.setFeature(
22839                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22840                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22841                    serializer.endDocument();
22842                    serializer.flush();
22843                } catch (IllegalArgumentException e) {
22844                    pw.println("Failed writing: " + e);
22845                } catch (IllegalStateException e) {
22846                    pw.println("Failed writing: " + e);
22847                } catch (IOException e) {
22848                    pw.println("Failed writing: " + e);
22849                }
22850            }
22851
22852            if (!checkin
22853                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22854                    && packageName == null) {
22855                pw.println();
22856                int count = mSettings.mPackages.size();
22857                if (count == 0) {
22858                    pw.println("No applications!");
22859                    pw.println();
22860                } else {
22861                    final String prefix = "  ";
22862                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22863                    if (allPackageSettings.size() == 0) {
22864                        pw.println("No domain preferred apps!");
22865                        pw.println();
22866                    } else {
22867                        pw.println("App verification status:");
22868                        pw.println();
22869                        count = 0;
22870                        for (PackageSetting ps : allPackageSettings) {
22871                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22872                            if (ivi == null || ivi.getPackageName() == null) continue;
22873                            pw.println(prefix + "Package: " + ivi.getPackageName());
22874                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22875                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22876                            pw.println();
22877                            count++;
22878                        }
22879                        if (count == 0) {
22880                            pw.println(prefix + "No app verification established.");
22881                            pw.println();
22882                        }
22883                        for (int userId : sUserManager.getUserIds()) {
22884                            pw.println("App linkages for user " + userId + ":");
22885                            pw.println();
22886                            count = 0;
22887                            for (PackageSetting ps : allPackageSettings) {
22888                                final long status = ps.getDomainVerificationStatusForUser(userId);
22889                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22890                                        && !DEBUG_DOMAIN_VERIFICATION) {
22891                                    continue;
22892                                }
22893                                pw.println(prefix + "Package: " + ps.name);
22894                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22895                                String statusStr = IntentFilterVerificationInfo.
22896                                        getStatusStringFromValue(status);
22897                                pw.println(prefix + "Status:  " + statusStr);
22898                                pw.println();
22899                                count++;
22900                            }
22901                            if (count == 0) {
22902                                pw.println(prefix + "No configured app linkages.");
22903                                pw.println();
22904                            }
22905                        }
22906                    }
22907                }
22908            }
22909
22910            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22911                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22912                if (packageName == null && permissionNames == null) {
22913                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22914                        if (iperm == 0) {
22915                            if (dumpState.onTitlePrinted())
22916                                pw.println();
22917                            pw.println("AppOp Permissions:");
22918                        }
22919                        pw.print("  AppOp Permission ");
22920                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22921                        pw.println(":");
22922                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22923                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22924                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22925                        }
22926                    }
22927                }
22928            }
22929
22930            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22931                boolean printedSomething = false;
22932                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22933                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22934                        continue;
22935                    }
22936                    if (!printedSomething) {
22937                        if (dumpState.onTitlePrinted())
22938                            pw.println();
22939                        pw.println("Registered ContentProviders:");
22940                        printedSomething = true;
22941                    }
22942                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22943                    pw.print("    "); pw.println(p.toString());
22944                }
22945                printedSomething = false;
22946                for (Map.Entry<String, PackageParser.Provider> entry :
22947                        mProvidersByAuthority.entrySet()) {
22948                    PackageParser.Provider p = entry.getValue();
22949                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22950                        continue;
22951                    }
22952                    if (!printedSomething) {
22953                        if (dumpState.onTitlePrinted())
22954                            pw.println();
22955                        pw.println("ContentProvider Authorities:");
22956                        printedSomething = true;
22957                    }
22958                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22959                    pw.print("    "); pw.println(p.toString());
22960                    if (p.info != null && p.info.applicationInfo != null) {
22961                        final String appInfo = p.info.applicationInfo.toString();
22962                        pw.print("      applicationInfo="); pw.println(appInfo);
22963                    }
22964                }
22965            }
22966
22967            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22968                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22969            }
22970
22971            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22972                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22973            }
22974
22975            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22976                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22977            }
22978
22979            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22980                if (dumpState.onTitlePrinted()) pw.println();
22981                pw.println("Package Changes:");
22982                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22983                final int K = mChangedPackages.size();
22984                for (int i = 0; i < K; i++) {
22985                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22986                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22987                    final int N = changes.size();
22988                    if (N == 0) {
22989                        pw.print("    "); pw.println("No packages changed");
22990                    } else {
22991                        for (int j = 0; j < N; j++) {
22992                            final String pkgName = changes.valueAt(j);
22993                            final int sequenceNumber = changes.keyAt(j);
22994                            pw.print("    ");
22995                            pw.print("seq=");
22996                            pw.print(sequenceNumber);
22997                            pw.print(", package=");
22998                            pw.println(pkgName);
22999                        }
23000                    }
23001                }
23002            }
23003
23004            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
23005                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
23006            }
23007
23008            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
23009                // XXX should handle packageName != null by dumping only install data that
23010                // the given package is involved with.
23011                if (dumpState.onTitlePrinted()) pw.println();
23012
23013                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23014                ipw.println();
23015                ipw.println("Frozen packages:");
23016                ipw.increaseIndent();
23017                if (mFrozenPackages.size() == 0) {
23018                    ipw.println("(none)");
23019                } else {
23020                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23021                        ipw.println(mFrozenPackages.valueAt(i));
23022                    }
23023                }
23024                ipw.decreaseIndent();
23025            }
23026
23027            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23028                if (dumpState.onTitlePrinted()) pw.println();
23029
23030                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23031                ipw.println();
23032                ipw.println("Loaded volumes:");
23033                ipw.increaseIndent();
23034                if (mLoadedVolumes.size() == 0) {
23035                    ipw.println("(none)");
23036                } else {
23037                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23038                        ipw.println(mLoadedVolumes.valueAt(i));
23039                    }
23040                }
23041                ipw.decreaseIndent();
23042            }
23043
23044            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23045                if (dumpState.onTitlePrinted()) pw.println();
23046                dumpDexoptStateLPr(pw, packageName);
23047            }
23048
23049            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23050                if (dumpState.onTitlePrinted()) pw.println();
23051                dumpCompilerStatsLPr(pw, packageName);
23052            }
23053
23054            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23055                if (dumpState.onTitlePrinted()) pw.println();
23056                mSettings.dumpReadMessagesLPr(pw, dumpState);
23057
23058                pw.println();
23059                pw.println("Package warning messages:");
23060                BufferedReader in = null;
23061                String line = null;
23062                try {
23063                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23064                    while ((line = in.readLine()) != null) {
23065                        if (line.contains("ignored: updated version")) continue;
23066                        pw.println(line);
23067                    }
23068                } catch (IOException ignored) {
23069                } finally {
23070                    IoUtils.closeQuietly(in);
23071                }
23072            }
23073
23074            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23075                BufferedReader in = null;
23076                String line = null;
23077                try {
23078                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23079                    while ((line = in.readLine()) != null) {
23080                        if (line.contains("ignored: updated version")) continue;
23081                        pw.print("msg,");
23082                        pw.println(line);
23083                    }
23084                } catch (IOException ignored) {
23085                } finally {
23086                    IoUtils.closeQuietly(in);
23087                }
23088            }
23089        }
23090
23091        // PackageInstaller should be called outside of mPackages lock
23092        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23093            // XXX should handle packageName != null by dumping only install data that
23094            // the given package is involved with.
23095            if (dumpState.onTitlePrinted()) pw.println();
23096            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23097        }
23098    }
23099
23100    private void dumpProto(FileDescriptor fd) {
23101        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23102
23103        synchronized (mPackages) {
23104            final long requiredVerifierPackageToken =
23105                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23106            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23107            proto.write(
23108                    PackageServiceDumpProto.PackageShortProto.UID,
23109                    getPackageUid(
23110                            mRequiredVerifierPackage,
23111                            MATCH_DEBUG_TRIAGED_MISSING,
23112                            UserHandle.USER_SYSTEM));
23113            proto.end(requiredVerifierPackageToken);
23114
23115            if (mIntentFilterVerifierComponent != null) {
23116                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23117                final long verifierPackageToken =
23118                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23119                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23120                proto.write(
23121                        PackageServiceDumpProto.PackageShortProto.UID,
23122                        getPackageUid(
23123                                verifierPackageName,
23124                                MATCH_DEBUG_TRIAGED_MISSING,
23125                                UserHandle.USER_SYSTEM));
23126                proto.end(verifierPackageToken);
23127            }
23128
23129            dumpSharedLibrariesProto(proto);
23130            dumpFeaturesProto(proto);
23131            mSettings.dumpPackagesProto(proto);
23132            mSettings.dumpSharedUsersProto(proto);
23133            dumpMessagesProto(proto);
23134        }
23135        proto.flush();
23136    }
23137
23138    private void dumpMessagesProto(ProtoOutputStream proto) {
23139        BufferedReader in = null;
23140        String line = null;
23141        try {
23142            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23143            while ((line = in.readLine()) != null) {
23144                if (line.contains("ignored: updated version")) continue;
23145                proto.write(PackageServiceDumpProto.MESSAGES, line);
23146            }
23147        } catch (IOException ignored) {
23148        } finally {
23149            IoUtils.closeQuietly(in);
23150        }
23151    }
23152
23153    private void dumpFeaturesProto(ProtoOutputStream proto) {
23154        synchronized (mAvailableFeatures) {
23155            final int count = mAvailableFeatures.size();
23156            for (int i = 0; i < count; i++) {
23157                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23158                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23159                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23160                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23161                proto.end(featureToken);
23162            }
23163        }
23164    }
23165
23166    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23167        final int count = mSharedLibraries.size();
23168        for (int i = 0; i < count; i++) {
23169            final String libName = mSharedLibraries.keyAt(i);
23170            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23171            if (versionedLib == null) {
23172                continue;
23173            }
23174            final int versionCount = versionedLib.size();
23175            for (int j = 0; j < versionCount; j++) {
23176                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23177                final long sharedLibraryToken =
23178                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23179                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23180                final boolean isJar = (libEntry.path != null);
23181                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23182                if (isJar) {
23183                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23184                } else {
23185                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23186                }
23187                proto.end(sharedLibraryToken);
23188            }
23189        }
23190    }
23191
23192    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23193        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23194        ipw.println();
23195        ipw.println("Dexopt state:");
23196        ipw.increaseIndent();
23197        Collection<PackageParser.Package> packages = null;
23198        if (packageName != null) {
23199            PackageParser.Package targetPackage = mPackages.get(packageName);
23200            if (targetPackage != null) {
23201                packages = Collections.singletonList(targetPackage);
23202            } else {
23203                ipw.println("Unable to find package: " + packageName);
23204                return;
23205            }
23206        } else {
23207            packages = mPackages.values();
23208        }
23209
23210        for (PackageParser.Package pkg : packages) {
23211            ipw.println("[" + pkg.packageName + "]");
23212            ipw.increaseIndent();
23213            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23214                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23215            ipw.decreaseIndent();
23216        }
23217    }
23218
23219    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23220        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23221        ipw.println();
23222        ipw.println("Compiler stats:");
23223        ipw.increaseIndent();
23224        Collection<PackageParser.Package> packages = null;
23225        if (packageName != null) {
23226            PackageParser.Package targetPackage = mPackages.get(packageName);
23227            if (targetPackage != null) {
23228                packages = Collections.singletonList(targetPackage);
23229            } else {
23230                ipw.println("Unable to find package: " + packageName);
23231                return;
23232            }
23233        } else {
23234            packages = mPackages.values();
23235        }
23236
23237        for (PackageParser.Package pkg : packages) {
23238            ipw.println("[" + pkg.packageName + "]");
23239            ipw.increaseIndent();
23240
23241            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23242            if (stats == null) {
23243                ipw.println("(No recorded stats)");
23244            } else {
23245                stats.dump(ipw);
23246            }
23247            ipw.decreaseIndent();
23248        }
23249    }
23250
23251    private String dumpDomainString(String packageName) {
23252        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23253                .getList();
23254        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23255
23256        ArraySet<String> result = new ArraySet<>();
23257        if (iviList.size() > 0) {
23258            for (IntentFilterVerificationInfo ivi : iviList) {
23259                for (String host : ivi.getDomains()) {
23260                    result.add(host);
23261                }
23262            }
23263        }
23264        if (filters != null && filters.size() > 0) {
23265            for (IntentFilter filter : filters) {
23266                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23267                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23268                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23269                    result.addAll(filter.getHostsList());
23270                }
23271            }
23272        }
23273
23274        StringBuilder sb = new StringBuilder(result.size() * 16);
23275        for (String domain : result) {
23276            if (sb.length() > 0) sb.append(" ");
23277            sb.append(domain);
23278        }
23279        return sb.toString();
23280    }
23281
23282    // ------- apps on sdcard specific code -------
23283    static final boolean DEBUG_SD_INSTALL = false;
23284
23285    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23286
23287    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23288
23289    private boolean mMediaMounted = false;
23290
23291    static String getEncryptKey() {
23292        try {
23293            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23294                    SD_ENCRYPTION_KEYSTORE_NAME);
23295            if (sdEncKey == null) {
23296                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23297                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23298                if (sdEncKey == null) {
23299                    Slog.e(TAG, "Failed to create encryption keys");
23300                    return null;
23301                }
23302            }
23303            return sdEncKey;
23304        } catch (NoSuchAlgorithmException nsae) {
23305            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23306            return null;
23307        } catch (IOException ioe) {
23308            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23309            return null;
23310        }
23311    }
23312
23313    /*
23314     * Update media status on PackageManager.
23315     */
23316    @Override
23317    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23318        enforceSystemOrRoot("Media status can only be updated by the system");
23319        // reader; this apparently protects mMediaMounted, but should probably
23320        // be a different lock in that case.
23321        synchronized (mPackages) {
23322            Log.i(TAG, "Updating external media status from "
23323                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23324                    + (mediaStatus ? "mounted" : "unmounted"));
23325            if (DEBUG_SD_INSTALL)
23326                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23327                        + ", mMediaMounted=" + mMediaMounted);
23328            if (mediaStatus == mMediaMounted) {
23329                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23330                        : 0, -1);
23331                mHandler.sendMessage(msg);
23332                return;
23333            }
23334            mMediaMounted = mediaStatus;
23335        }
23336        // Queue up an async operation since the package installation may take a
23337        // little while.
23338        mHandler.post(new Runnable() {
23339            public void run() {
23340                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23341            }
23342        });
23343    }
23344
23345    /**
23346     * Called by StorageManagerService when the initial ASECs to scan are available.
23347     * Should block until all the ASEC containers are finished being scanned.
23348     */
23349    public void scanAvailableAsecs() {
23350        updateExternalMediaStatusInner(true, false, false);
23351    }
23352
23353    /*
23354     * Collect information of applications on external media, map them against
23355     * existing containers and update information based on current mount status.
23356     * Please note that we always have to report status if reportStatus has been
23357     * set to true especially when unloading packages.
23358     */
23359    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23360            boolean externalStorage) {
23361        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23362        int[] uidArr = EmptyArray.INT;
23363
23364        final String[] list = PackageHelper.getSecureContainerList();
23365        if (ArrayUtils.isEmpty(list)) {
23366            Log.i(TAG, "No secure containers found");
23367        } else {
23368            // Process list of secure containers and categorize them
23369            // as active or stale based on their package internal state.
23370
23371            // reader
23372            synchronized (mPackages) {
23373                for (String cid : list) {
23374                    // Leave stages untouched for now; installer service owns them
23375                    if (PackageInstallerService.isStageName(cid)) continue;
23376
23377                    if (DEBUG_SD_INSTALL)
23378                        Log.i(TAG, "Processing container " + cid);
23379                    String pkgName = getAsecPackageName(cid);
23380                    if (pkgName == null) {
23381                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23382                        continue;
23383                    }
23384                    if (DEBUG_SD_INSTALL)
23385                        Log.i(TAG, "Looking for pkg : " + pkgName);
23386
23387                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23388                    if (ps == null) {
23389                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23390                        continue;
23391                    }
23392
23393                    /*
23394                     * Skip packages that are not external if we're unmounting
23395                     * external storage.
23396                     */
23397                    if (externalStorage && !isMounted && !isExternal(ps)) {
23398                        continue;
23399                    }
23400
23401                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23402                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23403                    // The package status is changed only if the code path
23404                    // matches between settings and the container id.
23405                    if (ps.codePathString != null
23406                            && ps.codePathString.startsWith(args.getCodePath())) {
23407                        if (DEBUG_SD_INSTALL) {
23408                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23409                                    + " at code path: " + ps.codePathString);
23410                        }
23411
23412                        // We do have a valid package installed on sdcard
23413                        processCids.put(args, ps.codePathString);
23414                        final int uid = ps.appId;
23415                        if (uid != -1) {
23416                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23417                        }
23418                    } else {
23419                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23420                                + ps.codePathString);
23421                    }
23422                }
23423            }
23424
23425            Arrays.sort(uidArr);
23426        }
23427
23428        // Process packages with valid entries.
23429        if (isMounted) {
23430            if (DEBUG_SD_INSTALL)
23431                Log.i(TAG, "Loading packages");
23432            loadMediaPackages(processCids, uidArr, externalStorage);
23433            startCleaningPackages();
23434            mInstallerService.onSecureContainersAvailable();
23435        } else {
23436            if (DEBUG_SD_INSTALL)
23437                Log.i(TAG, "Unloading packages");
23438            unloadMediaPackages(processCids, uidArr, reportStatus);
23439        }
23440    }
23441
23442    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23443            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23444        final int size = infos.size();
23445        final String[] packageNames = new String[size];
23446        final int[] packageUids = new int[size];
23447        for (int i = 0; i < size; i++) {
23448            final ApplicationInfo info = infos.get(i);
23449            packageNames[i] = info.packageName;
23450            packageUids[i] = info.uid;
23451        }
23452        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23453                finishedReceiver);
23454    }
23455
23456    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23457            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23458        sendResourcesChangedBroadcast(mediaStatus, replacing,
23459                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23460    }
23461
23462    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23463            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23464        int size = pkgList.length;
23465        if (size > 0) {
23466            // Send broadcasts here
23467            Bundle extras = new Bundle();
23468            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23469            if (uidArr != null) {
23470                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23471            }
23472            if (replacing) {
23473                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23474            }
23475            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23476                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23477            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23478        }
23479    }
23480
23481   /*
23482     * Look at potentially valid container ids from processCids If package
23483     * information doesn't match the one on record or package scanning fails,
23484     * the cid is added to list of removeCids. We currently don't delete stale
23485     * containers.
23486     */
23487    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23488            boolean externalStorage) {
23489        ArrayList<String> pkgList = new ArrayList<String>();
23490        Set<AsecInstallArgs> keys = processCids.keySet();
23491
23492        for (AsecInstallArgs args : keys) {
23493            String codePath = processCids.get(args);
23494            if (DEBUG_SD_INSTALL)
23495                Log.i(TAG, "Loading container : " + args.cid);
23496            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23497            try {
23498                // Make sure there are no container errors first.
23499                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23500                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23501                            + " when installing from sdcard");
23502                    continue;
23503                }
23504                // Check code path here.
23505                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23506                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23507                            + " does not match one in settings " + codePath);
23508                    continue;
23509                }
23510                // Parse package
23511                int parseFlags = mDefParseFlags;
23512                if (args.isExternalAsec()) {
23513                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23514                }
23515                if (args.isFwdLocked()) {
23516                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23517                }
23518
23519                synchronized (mInstallLock) {
23520                    PackageParser.Package pkg = null;
23521                    try {
23522                        // Sadly we don't know the package name yet to freeze it
23523                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23524                                SCAN_IGNORE_FROZEN, 0, null);
23525                    } catch (PackageManagerException e) {
23526                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23527                    }
23528                    // Scan the package
23529                    if (pkg != null) {
23530                        /*
23531                         * TODO why is the lock being held? doPostInstall is
23532                         * called in other places without the lock. This needs
23533                         * to be straightened out.
23534                         */
23535                        // writer
23536                        synchronized (mPackages) {
23537                            retCode = PackageManager.INSTALL_SUCCEEDED;
23538                            pkgList.add(pkg.packageName);
23539                            // Post process args
23540                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23541                                    pkg.applicationInfo.uid);
23542                        }
23543                    } else {
23544                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23545                    }
23546                }
23547
23548            } finally {
23549                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23550                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23551                }
23552            }
23553        }
23554        // writer
23555        synchronized (mPackages) {
23556            // If the platform SDK has changed since the last time we booted,
23557            // we need to re-grant app permission to catch any new ones that
23558            // appear. This is really a hack, and means that apps can in some
23559            // cases get permissions that the user didn't initially explicitly
23560            // allow... it would be nice to have some better way to handle
23561            // this situation.
23562            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23563                    : mSettings.getInternalVersion();
23564            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23565                    : StorageManager.UUID_PRIVATE_INTERNAL;
23566
23567            int updateFlags = UPDATE_PERMISSIONS_ALL;
23568            if (ver.sdkVersion != mSdkVersion) {
23569                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23570                        + mSdkVersion + "; regranting permissions for external");
23571                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23572            }
23573            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23574
23575            // Yay, everything is now upgraded
23576            ver.forceCurrent();
23577
23578            // can downgrade to reader
23579            // Persist settings
23580            mSettings.writeLPr();
23581        }
23582        // Send a broadcast to let everyone know we are done processing
23583        if (pkgList.size() > 0) {
23584            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23585        }
23586    }
23587
23588   /*
23589     * Utility method to unload a list of specified containers
23590     */
23591    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23592        // Just unmount all valid containers.
23593        for (AsecInstallArgs arg : cidArgs) {
23594            synchronized (mInstallLock) {
23595                arg.doPostDeleteLI(false);
23596           }
23597       }
23598   }
23599
23600    /*
23601     * Unload packages mounted on external media. This involves deleting package
23602     * data from internal structures, sending broadcasts about disabled packages,
23603     * gc'ing to free up references, unmounting all secure containers
23604     * corresponding to packages on external media, and posting a
23605     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23606     * that we always have to post this message if status has been requested no
23607     * matter what.
23608     */
23609    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23610            final boolean reportStatus) {
23611        if (DEBUG_SD_INSTALL)
23612            Log.i(TAG, "unloading media packages");
23613        ArrayList<String> pkgList = new ArrayList<String>();
23614        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23615        final Set<AsecInstallArgs> keys = processCids.keySet();
23616        for (AsecInstallArgs args : keys) {
23617            String pkgName = args.getPackageName();
23618            if (DEBUG_SD_INSTALL)
23619                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23620            // Delete package internally
23621            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23622            synchronized (mInstallLock) {
23623                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23624                final boolean res;
23625                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23626                        "unloadMediaPackages")) {
23627                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23628                            null);
23629                }
23630                if (res) {
23631                    pkgList.add(pkgName);
23632                } else {
23633                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23634                    failedList.add(args);
23635                }
23636            }
23637        }
23638
23639        // reader
23640        synchronized (mPackages) {
23641            // We didn't update the settings after removing each package;
23642            // write them now for all packages.
23643            mSettings.writeLPr();
23644        }
23645
23646        // We have to absolutely send UPDATED_MEDIA_STATUS only
23647        // after confirming that all the receivers processed the ordered
23648        // broadcast when packages get disabled, force a gc to clean things up.
23649        // and unload all the containers.
23650        if (pkgList.size() > 0) {
23651            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23652                    new IIntentReceiver.Stub() {
23653                public void performReceive(Intent intent, int resultCode, String data,
23654                        Bundle extras, boolean ordered, boolean sticky,
23655                        int sendingUser) throws RemoteException {
23656                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23657                            reportStatus ? 1 : 0, 1, keys);
23658                    mHandler.sendMessage(msg);
23659                }
23660            });
23661        } else {
23662            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23663                    keys);
23664            mHandler.sendMessage(msg);
23665        }
23666    }
23667
23668    private void loadPrivatePackages(final VolumeInfo vol) {
23669        mHandler.post(new Runnable() {
23670            @Override
23671            public void run() {
23672                loadPrivatePackagesInner(vol);
23673            }
23674        });
23675    }
23676
23677    private void loadPrivatePackagesInner(VolumeInfo vol) {
23678        final String volumeUuid = vol.fsUuid;
23679        if (TextUtils.isEmpty(volumeUuid)) {
23680            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23681            return;
23682        }
23683
23684        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23685        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23686        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23687
23688        final VersionInfo ver;
23689        final List<PackageSetting> packages;
23690        synchronized (mPackages) {
23691            ver = mSettings.findOrCreateVersion(volumeUuid);
23692            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23693        }
23694
23695        for (PackageSetting ps : packages) {
23696            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23697            synchronized (mInstallLock) {
23698                final PackageParser.Package pkg;
23699                try {
23700                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23701                    loaded.add(pkg.applicationInfo);
23702
23703                } catch (PackageManagerException e) {
23704                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23705                }
23706
23707                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23708                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23709                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23710                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23711                }
23712            }
23713        }
23714
23715        // Reconcile app data for all started/unlocked users
23716        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23717        final UserManager um = mContext.getSystemService(UserManager.class);
23718        UserManagerInternal umInternal = getUserManagerInternal();
23719        for (UserInfo user : um.getUsers()) {
23720            final int flags;
23721            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23722                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23723            } else if (umInternal.isUserRunning(user.id)) {
23724                flags = StorageManager.FLAG_STORAGE_DE;
23725            } else {
23726                continue;
23727            }
23728
23729            try {
23730                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23731                synchronized (mInstallLock) {
23732                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23733                }
23734            } catch (IllegalStateException e) {
23735                // Device was probably ejected, and we'll process that event momentarily
23736                Slog.w(TAG, "Failed to prepare storage: " + e);
23737            }
23738        }
23739
23740        synchronized (mPackages) {
23741            int updateFlags = UPDATE_PERMISSIONS_ALL;
23742            if (ver.sdkVersion != mSdkVersion) {
23743                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23744                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23745                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23746            }
23747            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23748
23749            // Yay, everything is now upgraded
23750            ver.forceCurrent();
23751
23752            mSettings.writeLPr();
23753        }
23754
23755        for (PackageFreezer freezer : freezers) {
23756            freezer.close();
23757        }
23758
23759        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23760        sendResourcesChangedBroadcast(true, false, loaded, null);
23761        mLoadedVolumes.add(vol.getId());
23762    }
23763
23764    private void unloadPrivatePackages(final VolumeInfo vol) {
23765        mHandler.post(new Runnable() {
23766            @Override
23767            public void run() {
23768                unloadPrivatePackagesInner(vol);
23769            }
23770        });
23771    }
23772
23773    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23774        final String volumeUuid = vol.fsUuid;
23775        if (TextUtils.isEmpty(volumeUuid)) {
23776            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23777            return;
23778        }
23779
23780        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23781        synchronized (mInstallLock) {
23782        synchronized (mPackages) {
23783            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23784            for (PackageSetting ps : packages) {
23785                if (ps.pkg == null) continue;
23786
23787                final ApplicationInfo info = ps.pkg.applicationInfo;
23788                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23789                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23790
23791                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23792                        "unloadPrivatePackagesInner")) {
23793                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23794                            false, null)) {
23795                        unloaded.add(info);
23796                    } else {
23797                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23798                    }
23799                }
23800
23801                // Try very hard to release any references to this package
23802                // so we don't risk the system server being killed due to
23803                // open FDs
23804                AttributeCache.instance().removePackage(ps.name);
23805            }
23806
23807            mSettings.writeLPr();
23808        }
23809        }
23810
23811        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23812        sendResourcesChangedBroadcast(false, false, unloaded, null);
23813        mLoadedVolumes.remove(vol.getId());
23814
23815        // Try very hard to release any references to this path so we don't risk
23816        // the system server being killed due to open FDs
23817        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23818
23819        for (int i = 0; i < 3; i++) {
23820            System.gc();
23821            System.runFinalization();
23822        }
23823    }
23824
23825    private void assertPackageKnown(String volumeUuid, String packageName)
23826            throws PackageManagerException {
23827        synchronized (mPackages) {
23828            // Normalize package name to handle renamed packages
23829            packageName = normalizePackageNameLPr(packageName);
23830
23831            final PackageSetting ps = mSettings.mPackages.get(packageName);
23832            if (ps == null) {
23833                throw new PackageManagerException("Package " + packageName + " is unknown");
23834            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23835                throw new PackageManagerException(
23836                        "Package " + packageName + " found on unknown volume " + volumeUuid
23837                                + "; expected volume " + ps.volumeUuid);
23838            }
23839        }
23840    }
23841
23842    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23843            throws PackageManagerException {
23844        synchronized (mPackages) {
23845            // Normalize package name to handle renamed packages
23846            packageName = normalizePackageNameLPr(packageName);
23847
23848            final PackageSetting ps = mSettings.mPackages.get(packageName);
23849            if (ps == null) {
23850                throw new PackageManagerException("Package " + packageName + " is unknown");
23851            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23852                throw new PackageManagerException(
23853                        "Package " + packageName + " found on unknown volume " + volumeUuid
23854                                + "; expected volume " + ps.volumeUuid);
23855            } else if (!ps.getInstalled(userId)) {
23856                throw new PackageManagerException(
23857                        "Package " + packageName + " not installed for user " + userId);
23858            }
23859        }
23860    }
23861
23862    private List<String> collectAbsoluteCodePaths() {
23863        synchronized (mPackages) {
23864            List<String> codePaths = new ArrayList<>();
23865            final int packageCount = mSettings.mPackages.size();
23866            for (int i = 0; i < packageCount; i++) {
23867                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23868                codePaths.add(ps.codePath.getAbsolutePath());
23869            }
23870            return codePaths;
23871        }
23872    }
23873
23874    /**
23875     * Examine all apps present on given mounted volume, and destroy apps that
23876     * aren't expected, either due to uninstallation or reinstallation on
23877     * another volume.
23878     */
23879    private void reconcileApps(String volumeUuid) {
23880        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23881        List<File> filesToDelete = null;
23882
23883        final File[] files = FileUtils.listFilesOrEmpty(
23884                Environment.getDataAppDirectory(volumeUuid));
23885        for (File file : files) {
23886            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23887                    && !PackageInstallerService.isStageName(file.getName());
23888            if (!isPackage) {
23889                // Ignore entries which are not packages
23890                continue;
23891            }
23892
23893            String absolutePath = file.getAbsolutePath();
23894
23895            boolean pathValid = false;
23896            final int absoluteCodePathCount = absoluteCodePaths.size();
23897            for (int i = 0; i < absoluteCodePathCount; i++) {
23898                String absoluteCodePath = absoluteCodePaths.get(i);
23899                if (absolutePath.startsWith(absoluteCodePath)) {
23900                    pathValid = true;
23901                    break;
23902                }
23903            }
23904
23905            if (!pathValid) {
23906                if (filesToDelete == null) {
23907                    filesToDelete = new ArrayList<>();
23908                }
23909                filesToDelete.add(file);
23910            }
23911        }
23912
23913        if (filesToDelete != null) {
23914            final int fileToDeleteCount = filesToDelete.size();
23915            for (int i = 0; i < fileToDeleteCount; i++) {
23916                File fileToDelete = filesToDelete.get(i);
23917                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23918                synchronized (mInstallLock) {
23919                    removeCodePathLI(fileToDelete);
23920                }
23921            }
23922        }
23923    }
23924
23925    /**
23926     * Reconcile all app data for the given user.
23927     * <p>
23928     * Verifies that directories exist and that ownership and labeling is
23929     * correct for all installed apps on all mounted volumes.
23930     */
23931    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23932        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23933        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23934            final String volumeUuid = vol.getFsUuid();
23935            synchronized (mInstallLock) {
23936                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23937            }
23938        }
23939    }
23940
23941    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23942            boolean migrateAppData) {
23943        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23944    }
23945
23946    /**
23947     * Reconcile all app data on given mounted volume.
23948     * <p>
23949     * Destroys app data that isn't expected, either due to uninstallation or
23950     * reinstallation on another volume.
23951     * <p>
23952     * Verifies that directories exist and that ownership and labeling is
23953     * correct for all installed apps.
23954     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23955     */
23956    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23957            boolean migrateAppData, boolean onlyCoreApps) {
23958        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23959                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23960        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23961
23962        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23963        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23964
23965        // First look for stale data that doesn't belong, and check if things
23966        // have changed since we did our last restorecon
23967        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23968            if (StorageManager.isFileEncryptedNativeOrEmulated()
23969                    && !StorageManager.isUserKeyUnlocked(userId)) {
23970                throw new RuntimeException(
23971                        "Yikes, someone asked us to reconcile CE storage while " + userId
23972                                + " was still locked; this would have caused massive data loss!");
23973            }
23974
23975            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23976            for (File file : files) {
23977                final String packageName = file.getName();
23978                try {
23979                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23980                } catch (PackageManagerException e) {
23981                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23982                    try {
23983                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23984                                StorageManager.FLAG_STORAGE_CE, 0);
23985                    } catch (InstallerException e2) {
23986                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23987                    }
23988                }
23989            }
23990        }
23991        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23992            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23993            for (File file : files) {
23994                final String packageName = file.getName();
23995                try {
23996                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23997                } catch (PackageManagerException e) {
23998                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23999                    try {
24000                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24001                                StorageManager.FLAG_STORAGE_DE, 0);
24002                    } catch (InstallerException e2) {
24003                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24004                    }
24005                }
24006            }
24007        }
24008
24009        // Ensure that data directories are ready to roll for all packages
24010        // installed for this volume and user
24011        final List<PackageSetting> packages;
24012        synchronized (mPackages) {
24013            packages = mSettings.getVolumePackagesLPr(volumeUuid);
24014        }
24015        int preparedCount = 0;
24016        for (PackageSetting ps : packages) {
24017            final String packageName = ps.name;
24018            if (ps.pkg == null) {
24019                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24020                // TODO: might be due to legacy ASEC apps; we should circle back
24021                // and reconcile again once they're scanned
24022                continue;
24023            }
24024            // Skip non-core apps if requested
24025            if (onlyCoreApps && !ps.pkg.coreApp) {
24026                result.add(packageName);
24027                continue;
24028            }
24029
24030            if (ps.getInstalled(userId)) {
24031                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24032                preparedCount++;
24033            }
24034        }
24035
24036        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24037        return result;
24038    }
24039
24040    /**
24041     * Prepare app data for the given app just after it was installed or
24042     * upgraded. This method carefully only touches users that it's installed
24043     * for, and it forces a restorecon to handle any seinfo changes.
24044     * <p>
24045     * Verifies that directories exist and that ownership and labeling is
24046     * correct for all installed apps. If there is an ownership mismatch, it
24047     * will try recovering system apps by wiping data; third-party app data is
24048     * left intact.
24049     * <p>
24050     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24051     */
24052    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24053        final PackageSetting ps;
24054        synchronized (mPackages) {
24055            ps = mSettings.mPackages.get(pkg.packageName);
24056            mSettings.writeKernelMappingLPr(ps);
24057        }
24058
24059        final UserManager um = mContext.getSystemService(UserManager.class);
24060        UserManagerInternal umInternal = getUserManagerInternal();
24061        for (UserInfo user : um.getUsers()) {
24062            final int flags;
24063            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24064                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24065            } else if (umInternal.isUserRunning(user.id)) {
24066                flags = StorageManager.FLAG_STORAGE_DE;
24067            } else {
24068                continue;
24069            }
24070
24071            if (ps.getInstalled(user.id)) {
24072                // TODO: when user data is locked, mark that we're still dirty
24073                prepareAppDataLIF(pkg, user.id, flags);
24074            }
24075        }
24076    }
24077
24078    /**
24079     * Prepare app data for the given app.
24080     * <p>
24081     * Verifies that directories exist and that ownership and labeling is
24082     * correct for all installed apps. If there is an ownership mismatch, this
24083     * will try recovering system apps by wiping data; third-party app data is
24084     * left intact.
24085     */
24086    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24087        if (pkg == null) {
24088            Slog.wtf(TAG, "Package was null!", new Throwable());
24089            return;
24090        }
24091        prepareAppDataLeafLIF(pkg, userId, flags);
24092        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24093        for (int i = 0; i < childCount; i++) {
24094            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24095        }
24096    }
24097
24098    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24099            boolean maybeMigrateAppData) {
24100        prepareAppDataLIF(pkg, userId, flags);
24101
24102        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24103            // We may have just shuffled around app data directories, so
24104            // prepare them one more time
24105            prepareAppDataLIF(pkg, userId, flags);
24106        }
24107    }
24108
24109    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24110        if (DEBUG_APP_DATA) {
24111            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24112                    + Integer.toHexString(flags));
24113        }
24114
24115        final String volumeUuid = pkg.volumeUuid;
24116        final String packageName = pkg.packageName;
24117        final ApplicationInfo app = pkg.applicationInfo;
24118        final int appId = UserHandle.getAppId(app.uid);
24119
24120        Preconditions.checkNotNull(app.seInfo);
24121
24122        long ceDataInode = -1;
24123        try {
24124            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24125                    appId, app.seInfo, app.targetSdkVersion);
24126        } catch (InstallerException e) {
24127            if (app.isSystemApp()) {
24128                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24129                        + ", but trying to recover: " + e);
24130                destroyAppDataLeafLIF(pkg, userId, flags);
24131                try {
24132                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24133                            appId, app.seInfo, app.targetSdkVersion);
24134                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24135                } catch (InstallerException e2) {
24136                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24137                }
24138            } else {
24139                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24140            }
24141        }
24142
24143        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24144            // TODO: mark this structure as dirty so we persist it!
24145            synchronized (mPackages) {
24146                final PackageSetting ps = mSettings.mPackages.get(packageName);
24147                if (ps != null) {
24148                    ps.setCeDataInode(ceDataInode, userId);
24149                }
24150            }
24151        }
24152
24153        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24154    }
24155
24156    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24157        if (pkg == null) {
24158            Slog.wtf(TAG, "Package was null!", new Throwable());
24159            return;
24160        }
24161        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24162        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24163        for (int i = 0; i < childCount; i++) {
24164            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24165        }
24166    }
24167
24168    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24169        final String volumeUuid = pkg.volumeUuid;
24170        final String packageName = pkg.packageName;
24171        final ApplicationInfo app = pkg.applicationInfo;
24172
24173        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24174            // Create a native library symlink only if we have native libraries
24175            // and if the native libraries are 32 bit libraries. We do not provide
24176            // this symlink for 64 bit libraries.
24177            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24178                final String nativeLibPath = app.nativeLibraryDir;
24179                try {
24180                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24181                            nativeLibPath, userId);
24182                } catch (InstallerException e) {
24183                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24184                }
24185            }
24186        }
24187    }
24188
24189    /**
24190     * For system apps on non-FBE devices, this method migrates any existing
24191     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24192     * requested by the app.
24193     */
24194    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24195        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24196                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24197            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24198                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24199            try {
24200                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24201                        storageTarget);
24202            } catch (InstallerException e) {
24203                logCriticalInfo(Log.WARN,
24204                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24205            }
24206            return true;
24207        } else {
24208            return false;
24209        }
24210    }
24211
24212    public PackageFreezer freezePackage(String packageName, String killReason) {
24213        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24214    }
24215
24216    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24217        return new PackageFreezer(packageName, userId, killReason);
24218    }
24219
24220    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24221            String killReason) {
24222        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24223    }
24224
24225    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24226            String killReason) {
24227        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24228            return new PackageFreezer();
24229        } else {
24230            return freezePackage(packageName, userId, killReason);
24231        }
24232    }
24233
24234    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24235            String killReason) {
24236        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24237    }
24238
24239    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24240            String killReason) {
24241        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24242            return new PackageFreezer();
24243        } else {
24244            return freezePackage(packageName, userId, killReason);
24245        }
24246    }
24247
24248    /**
24249     * Class that freezes and kills the given package upon creation, and
24250     * unfreezes it upon closing. This is typically used when doing surgery on
24251     * app code/data to prevent the app from running while you're working.
24252     */
24253    private class PackageFreezer implements AutoCloseable {
24254        private final String mPackageName;
24255        private final PackageFreezer[] mChildren;
24256
24257        private final boolean mWeFroze;
24258
24259        private final AtomicBoolean mClosed = new AtomicBoolean();
24260        private final CloseGuard mCloseGuard = CloseGuard.get();
24261
24262        /**
24263         * Create and return a stub freezer that doesn't actually do anything,
24264         * typically used when someone requested
24265         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24266         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24267         */
24268        public PackageFreezer() {
24269            mPackageName = null;
24270            mChildren = null;
24271            mWeFroze = false;
24272            mCloseGuard.open("close");
24273        }
24274
24275        public PackageFreezer(String packageName, int userId, String killReason) {
24276            synchronized (mPackages) {
24277                mPackageName = packageName;
24278                mWeFroze = mFrozenPackages.add(mPackageName);
24279
24280                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24281                if (ps != null) {
24282                    killApplication(ps.name, ps.appId, userId, killReason);
24283                }
24284
24285                final PackageParser.Package p = mPackages.get(packageName);
24286                if (p != null && p.childPackages != null) {
24287                    final int N = p.childPackages.size();
24288                    mChildren = new PackageFreezer[N];
24289                    for (int i = 0; i < N; i++) {
24290                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24291                                userId, killReason);
24292                    }
24293                } else {
24294                    mChildren = null;
24295                }
24296            }
24297            mCloseGuard.open("close");
24298        }
24299
24300        @Override
24301        protected void finalize() throws Throwable {
24302            try {
24303                if (mCloseGuard != null) {
24304                    mCloseGuard.warnIfOpen();
24305                }
24306
24307                close();
24308            } finally {
24309                super.finalize();
24310            }
24311        }
24312
24313        @Override
24314        public void close() {
24315            mCloseGuard.close();
24316            if (mClosed.compareAndSet(false, true)) {
24317                synchronized (mPackages) {
24318                    if (mWeFroze) {
24319                        mFrozenPackages.remove(mPackageName);
24320                    }
24321
24322                    if (mChildren != null) {
24323                        for (PackageFreezer freezer : mChildren) {
24324                            freezer.close();
24325                        }
24326                    }
24327                }
24328            }
24329        }
24330    }
24331
24332    /**
24333     * Verify that given package is currently frozen.
24334     */
24335    private void checkPackageFrozen(String packageName) {
24336        synchronized (mPackages) {
24337            if (!mFrozenPackages.contains(packageName)) {
24338                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24339            }
24340        }
24341    }
24342
24343    @Override
24344    public int movePackage(final String packageName, final String volumeUuid) {
24345        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24346
24347        final int callingUid = Binder.getCallingUid();
24348        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24349        final int moveId = mNextMoveId.getAndIncrement();
24350        mHandler.post(new Runnable() {
24351            @Override
24352            public void run() {
24353                try {
24354                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24355                } catch (PackageManagerException e) {
24356                    Slog.w(TAG, "Failed to move " + packageName, e);
24357                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24358                }
24359            }
24360        });
24361        return moveId;
24362    }
24363
24364    private void movePackageInternal(final String packageName, final String volumeUuid,
24365            final int moveId, final int callingUid, UserHandle user)
24366                    throws PackageManagerException {
24367        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24368        final PackageManager pm = mContext.getPackageManager();
24369
24370        final boolean currentAsec;
24371        final String currentVolumeUuid;
24372        final File codeFile;
24373        final String installerPackageName;
24374        final String packageAbiOverride;
24375        final int appId;
24376        final String seinfo;
24377        final String label;
24378        final int targetSdkVersion;
24379        final PackageFreezer freezer;
24380        final int[] installedUserIds;
24381
24382        // reader
24383        synchronized (mPackages) {
24384            final PackageParser.Package pkg = mPackages.get(packageName);
24385            final PackageSetting ps = mSettings.mPackages.get(packageName);
24386            if (pkg == null
24387                    || ps == null
24388                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24389                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24390            }
24391            if (pkg.applicationInfo.isSystemApp()) {
24392                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24393                        "Cannot move system application");
24394            }
24395
24396            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24397            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24398                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24399            if (isInternalStorage && !allow3rdPartyOnInternal) {
24400                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24401                        "3rd party apps are not allowed on internal storage");
24402            }
24403
24404            if (pkg.applicationInfo.isExternalAsec()) {
24405                currentAsec = true;
24406                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24407            } else if (pkg.applicationInfo.isForwardLocked()) {
24408                currentAsec = true;
24409                currentVolumeUuid = "forward_locked";
24410            } else {
24411                currentAsec = false;
24412                currentVolumeUuid = ps.volumeUuid;
24413
24414                final File probe = new File(pkg.codePath);
24415                final File probeOat = new File(probe, "oat");
24416                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24417                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24418                            "Move only supported for modern cluster style installs");
24419                }
24420            }
24421
24422            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24423                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24424                        "Package already moved to " + volumeUuid);
24425            }
24426            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24427                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24428                        "Device admin cannot be moved");
24429            }
24430
24431            if (mFrozenPackages.contains(packageName)) {
24432                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24433                        "Failed to move already frozen package");
24434            }
24435
24436            codeFile = new File(pkg.codePath);
24437            installerPackageName = ps.installerPackageName;
24438            packageAbiOverride = ps.cpuAbiOverrideString;
24439            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24440            seinfo = pkg.applicationInfo.seInfo;
24441            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24442            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24443            freezer = freezePackage(packageName, "movePackageInternal");
24444            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24445        }
24446
24447        final Bundle extras = new Bundle();
24448        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24449        extras.putString(Intent.EXTRA_TITLE, label);
24450        mMoveCallbacks.notifyCreated(moveId, extras);
24451
24452        int installFlags;
24453        final boolean moveCompleteApp;
24454        final File measurePath;
24455
24456        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24457            installFlags = INSTALL_INTERNAL;
24458            moveCompleteApp = !currentAsec;
24459            measurePath = Environment.getDataAppDirectory(volumeUuid);
24460        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24461            installFlags = INSTALL_EXTERNAL;
24462            moveCompleteApp = false;
24463            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24464        } else {
24465            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24466            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24467                    || !volume.isMountedWritable()) {
24468                freezer.close();
24469                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24470                        "Move location not mounted private volume");
24471            }
24472
24473            Preconditions.checkState(!currentAsec);
24474
24475            installFlags = INSTALL_INTERNAL;
24476            moveCompleteApp = true;
24477            measurePath = Environment.getDataAppDirectory(volumeUuid);
24478        }
24479
24480        // If we're moving app data around, we need all the users unlocked
24481        if (moveCompleteApp) {
24482            for (int userId : installedUserIds) {
24483                if (StorageManager.isFileEncryptedNativeOrEmulated()
24484                        && !StorageManager.isUserKeyUnlocked(userId)) {
24485                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24486                            "User " + userId + " must be unlocked");
24487                }
24488            }
24489        }
24490
24491        final PackageStats stats = new PackageStats(null, -1);
24492        synchronized (mInstaller) {
24493            for (int userId : installedUserIds) {
24494                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24495                    freezer.close();
24496                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24497                            "Failed to measure package size");
24498                }
24499            }
24500        }
24501
24502        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24503                + stats.dataSize);
24504
24505        final long startFreeBytes = measurePath.getUsableSpace();
24506        final long sizeBytes;
24507        if (moveCompleteApp) {
24508            sizeBytes = stats.codeSize + stats.dataSize;
24509        } else {
24510            sizeBytes = stats.codeSize;
24511        }
24512
24513        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24514            freezer.close();
24515            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24516                    "Not enough free space to move");
24517        }
24518
24519        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24520
24521        final CountDownLatch installedLatch = new CountDownLatch(1);
24522        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24523            @Override
24524            public void onUserActionRequired(Intent intent) throws RemoteException {
24525                throw new IllegalStateException();
24526            }
24527
24528            @Override
24529            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24530                    Bundle extras) throws RemoteException {
24531                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24532                        + PackageManager.installStatusToString(returnCode, msg));
24533
24534                installedLatch.countDown();
24535                freezer.close();
24536
24537                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24538                switch (status) {
24539                    case PackageInstaller.STATUS_SUCCESS:
24540                        mMoveCallbacks.notifyStatusChanged(moveId,
24541                                PackageManager.MOVE_SUCCEEDED);
24542                        break;
24543                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24544                        mMoveCallbacks.notifyStatusChanged(moveId,
24545                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24546                        break;
24547                    default:
24548                        mMoveCallbacks.notifyStatusChanged(moveId,
24549                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24550                        break;
24551                }
24552            }
24553        };
24554
24555        final MoveInfo move;
24556        if (moveCompleteApp) {
24557            // Kick off a thread to report progress estimates
24558            new Thread() {
24559                @Override
24560                public void run() {
24561                    while (true) {
24562                        try {
24563                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24564                                break;
24565                            }
24566                        } catch (InterruptedException ignored) {
24567                        }
24568
24569                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24570                        final int progress = 10 + (int) MathUtils.constrain(
24571                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24572                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24573                    }
24574                }
24575            }.start();
24576
24577            final String dataAppName = codeFile.getName();
24578            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24579                    dataAppName, appId, seinfo, targetSdkVersion);
24580        } else {
24581            move = null;
24582        }
24583
24584        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24585
24586        final Message msg = mHandler.obtainMessage(INIT_COPY);
24587        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24588        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24589                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24590                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24591                PackageManager.INSTALL_REASON_UNKNOWN);
24592        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24593        msg.obj = params;
24594
24595        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24596                System.identityHashCode(msg.obj));
24597        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24598                System.identityHashCode(msg.obj));
24599
24600        mHandler.sendMessage(msg);
24601    }
24602
24603    @Override
24604    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24605        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24606
24607        final int realMoveId = mNextMoveId.getAndIncrement();
24608        final Bundle extras = new Bundle();
24609        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24610        mMoveCallbacks.notifyCreated(realMoveId, extras);
24611
24612        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24613            @Override
24614            public void onCreated(int moveId, Bundle extras) {
24615                // Ignored
24616            }
24617
24618            @Override
24619            public void onStatusChanged(int moveId, int status, long estMillis) {
24620                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24621            }
24622        };
24623
24624        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24625        storage.setPrimaryStorageUuid(volumeUuid, callback);
24626        return realMoveId;
24627    }
24628
24629    @Override
24630    public int getMoveStatus(int moveId) {
24631        mContext.enforceCallingOrSelfPermission(
24632                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24633        return mMoveCallbacks.mLastStatus.get(moveId);
24634    }
24635
24636    @Override
24637    public void registerMoveCallback(IPackageMoveObserver callback) {
24638        mContext.enforceCallingOrSelfPermission(
24639                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24640        mMoveCallbacks.register(callback);
24641    }
24642
24643    @Override
24644    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24645        mContext.enforceCallingOrSelfPermission(
24646                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24647        mMoveCallbacks.unregister(callback);
24648    }
24649
24650    @Override
24651    public boolean setInstallLocation(int loc) {
24652        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24653                null);
24654        if (getInstallLocation() == loc) {
24655            return true;
24656        }
24657        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24658                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24659            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24660                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24661            return true;
24662        }
24663        return false;
24664   }
24665
24666    @Override
24667    public int getInstallLocation() {
24668        // allow instant app access
24669        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24670                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24671                PackageHelper.APP_INSTALL_AUTO);
24672    }
24673
24674    /** Called by UserManagerService */
24675    void cleanUpUser(UserManagerService userManager, int userHandle) {
24676        synchronized (mPackages) {
24677            mDirtyUsers.remove(userHandle);
24678            mUserNeedsBadging.delete(userHandle);
24679            mSettings.removeUserLPw(userHandle);
24680            mPendingBroadcasts.remove(userHandle);
24681            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24682            removeUnusedPackagesLPw(userManager, userHandle);
24683        }
24684    }
24685
24686    /**
24687     * We're removing userHandle and would like to remove any downloaded packages
24688     * that are no longer in use by any other user.
24689     * @param userHandle the user being removed
24690     */
24691    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24692        final boolean DEBUG_CLEAN_APKS = false;
24693        int [] users = userManager.getUserIds();
24694        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24695        while (psit.hasNext()) {
24696            PackageSetting ps = psit.next();
24697            if (ps.pkg == null) {
24698                continue;
24699            }
24700            final String packageName = ps.pkg.packageName;
24701            // Skip over if system app
24702            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24703                continue;
24704            }
24705            if (DEBUG_CLEAN_APKS) {
24706                Slog.i(TAG, "Checking package " + packageName);
24707            }
24708            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24709            if (keep) {
24710                if (DEBUG_CLEAN_APKS) {
24711                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24712                }
24713            } else {
24714                for (int i = 0; i < users.length; i++) {
24715                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24716                        keep = true;
24717                        if (DEBUG_CLEAN_APKS) {
24718                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24719                                    + users[i]);
24720                        }
24721                        break;
24722                    }
24723                }
24724            }
24725            if (!keep) {
24726                if (DEBUG_CLEAN_APKS) {
24727                    Slog.i(TAG, "  Removing package " + packageName);
24728                }
24729                mHandler.post(new Runnable() {
24730                    public void run() {
24731                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24732                                userHandle, 0);
24733                    } //end run
24734                });
24735            }
24736        }
24737    }
24738
24739    /** Called by UserManagerService */
24740    void createNewUser(int userId, String[] disallowedPackages) {
24741        synchronized (mInstallLock) {
24742            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24743        }
24744        synchronized (mPackages) {
24745            scheduleWritePackageRestrictionsLocked(userId);
24746            scheduleWritePackageListLocked(userId);
24747            applyFactoryDefaultBrowserLPw(userId);
24748            primeDomainVerificationsLPw(userId);
24749        }
24750    }
24751
24752    void onNewUserCreated(final int userId) {
24753        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24754        // If permission review for legacy apps is required, we represent
24755        // dagerous permissions for such apps as always granted runtime
24756        // permissions to keep per user flag state whether review is needed.
24757        // Hence, if a new user is added we have to propagate dangerous
24758        // permission grants for these legacy apps.
24759        if (mPermissionReviewRequired) {
24760            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24761                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24762        }
24763    }
24764
24765    @Override
24766    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24767        mContext.enforceCallingOrSelfPermission(
24768                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24769                "Only package verification agents can read the verifier device identity");
24770
24771        synchronized (mPackages) {
24772            return mSettings.getVerifierDeviceIdentityLPw();
24773        }
24774    }
24775
24776    @Override
24777    public void setPermissionEnforced(String permission, boolean enforced) {
24778        // TODO: Now that we no longer change GID for storage, this should to away.
24779        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24780                "setPermissionEnforced");
24781        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24782            synchronized (mPackages) {
24783                if (mSettings.mReadExternalStorageEnforced == null
24784                        || mSettings.mReadExternalStorageEnforced != enforced) {
24785                    mSettings.mReadExternalStorageEnforced = enforced;
24786                    mSettings.writeLPr();
24787                }
24788            }
24789            // kill any non-foreground processes so we restart them and
24790            // grant/revoke the GID.
24791            final IActivityManager am = ActivityManager.getService();
24792            if (am != null) {
24793                final long token = Binder.clearCallingIdentity();
24794                try {
24795                    am.killProcessesBelowForeground("setPermissionEnforcement");
24796                } catch (RemoteException e) {
24797                } finally {
24798                    Binder.restoreCallingIdentity(token);
24799                }
24800            }
24801        } else {
24802            throw new IllegalArgumentException("No selective enforcement for " + permission);
24803        }
24804    }
24805
24806    @Override
24807    @Deprecated
24808    public boolean isPermissionEnforced(String permission) {
24809        // allow instant applications
24810        return true;
24811    }
24812
24813    @Override
24814    public boolean isStorageLow() {
24815        // allow instant applications
24816        final long token = Binder.clearCallingIdentity();
24817        try {
24818            final DeviceStorageMonitorInternal
24819                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24820            if (dsm != null) {
24821                return dsm.isMemoryLow();
24822            } else {
24823                return false;
24824            }
24825        } finally {
24826            Binder.restoreCallingIdentity(token);
24827        }
24828    }
24829
24830    @Override
24831    public IPackageInstaller getPackageInstaller() {
24832        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24833            return null;
24834        }
24835        return mInstallerService;
24836    }
24837
24838    private boolean userNeedsBadging(int userId) {
24839        int index = mUserNeedsBadging.indexOfKey(userId);
24840        if (index < 0) {
24841            final UserInfo userInfo;
24842            final long token = Binder.clearCallingIdentity();
24843            try {
24844                userInfo = sUserManager.getUserInfo(userId);
24845            } finally {
24846                Binder.restoreCallingIdentity(token);
24847            }
24848            final boolean b;
24849            if (userInfo != null && userInfo.isManagedProfile()) {
24850                b = true;
24851            } else {
24852                b = false;
24853            }
24854            mUserNeedsBadging.put(userId, b);
24855            return b;
24856        }
24857        return mUserNeedsBadging.valueAt(index);
24858    }
24859
24860    @Override
24861    public KeySet getKeySetByAlias(String packageName, String alias) {
24862        if (packageName == null || alias == null) {
24863            return null;
24864        }
24865        synchronized(mPackages) {
24866            final PackageParser.Package pkg = mPackages.get(packageName);
24867            if (pkg == null) {
24868                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24869                throw new IllegalArgumentException("Unknown package: " + packageName);
24870            }
24871            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24872            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24873                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24874                throw new IllegalArgumentException("Unknown package: " + packageName);
24875            }
24876            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24877            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24878        }
24879    }
24880
24881    @Override
24882    public KeySet getSigningKeySet(String packageName) {
24883        if (packageName == null) {
24884            return null;
24885        }
24886        synchronized(mPackages) {
24887            final int callingUid = Binder.getCallingUid();
24888            final int callingUserId = UserHandle.getUserId(callingUid);
24889            final PackageParser.Package pkg = mPackages.get(packageName);
24890            if (pkg == null) {
24891                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24892                throw new IllegalArgumentException("Unknown package: " + packageName);
24893            }
24894            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24895            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24896                // filter and pretend the package doesn't exist
24897                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24898                        + ", uid:" + callingUid);
24899                throw new IllegalArgumentException("Unknown package: " + packageName);
24900            }
24901            if (pkg.applicationInfo.uid != callingUid
24902                    && Process.SYSTEM_UID != callingUid) {
24903                throw new SecurityException("May not access signing KeySet of other apps.");
24904            }
24905            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24906            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24907        }
24908    }
24909
24910    @Override
24911    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24912        final int callingUid = Binder.getCallingUid();
24913        if (getInstantAppPackageName(callingUid) != null) {
24914            return false;
24915        }
24916        if (packageName == null || ks == null) {
24917            return false;
24918        }
24919        synchronized(mPackages) {
24920            final PackageParser.Package pkg = mPackages.get(packageName);
24921            if (pkg == null
24922                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24923                            UserHandle.getUserId(callingUid))) {
24924                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24925                throw new IllegalArgumentException("Unknown package: " + packageName);
24926            }
24927            IBinder ksh = ks.getToken();
24928            if (ksh instanceof KeySetHandle) {
24929                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24930                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24931            }
24932            return false;
24933        }
24934    }
24935
24936    @Override
24937    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24938        final int callingUid = Binder.getCallingUid();
24939        if (getInstantAppPackageName(callingUid) != null) {
24940            return false;
24941        }
24942        if (packageName == null || ks == null) {
24943            return false;
24944        }
24945        synchronized(mPackages) {
24946            final PackageParser.Package pkg = mPackages.get(packageName);
24947            if (pkg == null
24948                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24949                            UserHandle.getUserId(callingUid))) {
24950                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24951                throw new IllegalArgumentException("Unknown package: " + packageName);
24952            }
24953            IBinder ksh = ks.getToken();
24954            if (ksh instanceof KeySetHandle) {
24955                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24956                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24957            }
24958            return false;
24959        }
24960    }
24961
24962    private void deletePackageIfUnusedLPr(final String packageName) {
24963        PackageSetting ps = mSettings.mPackages.get(packageName);
24964        if (ps == null) {
24965            return;
24966        }
24967        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24968            // TODO Implement atomic delete if package is unused
24969            // It is currently possible that the package will be deleted even if it is installed
24970            // after this method returns.
24971            mHandler.post(new Runnable() {
24972                public void run() {
24973                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24974                            0, PackageManager.DELETE_ALL_USERS);
24975                }
24976            });
24977        }
24978    }
24979
24980    /**
24981     * Check and throw if the given before/after packages would be considered a
24982     * downgrade.
24983     */
24984    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24985            throws PackageManagerException {
24986        if (after.versionCode < before.mVersionCode) {
24987            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24988                    "Update version code " + after.versionCode + " is older than current "
24989                    + before.mVersionCode);
24990        } else if (after.versionCode == before.mVersionCode) {
24991            if (after.baseRevisionCode < before.baseRevisionCode) {
24992                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24993                        "Update base revision code " + after.baseRevisionCode
24994                        + " is older than current " + before.baseRevisionCode);
24995            }
24996
24997            if (!ArrayUtils.isEmpty(after.splitNames)) {
24998                for (int i = 0; i < after.splitNames.length; i++) {
24999                    final String splitName = after.splitNames[i];
25000                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
25001                    if (j != -1) {
25002                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
25003                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25004                                    "Update split " + splitName + " revision code "
25005                                    + after.splitRevisionCodes[i] + " is older than current "
25006                                    + before.splitRevisionCodes[j]);
25007                        }
25008                    }
25009                }
25010            }
25011        }
25012    }
25013
25014    private static class MoveCallbacks extends Handler {
25015        private static final int MSG_CREATED = 1;
25016        private static final int MSG_STATUS_CHANGED = 2;
25017
25018        private final RemoteCallbackList<IPackageMoveObserver>
25019                mCallbacks = new RemoteCallbackList<>();
25020
25021        private final SparseIntArray mLastStatus = new SparseIntArray();
25022
25023        public MoveCallbacks(Looper looper) {
25024            super(looper);
25025        }
25026
25027        public void register(IPackageMoveObserver callback) {
25028            mCallbacks.register(callback);
25029        }
25030
25031        public void unregister(IPackageMoveObserver callback) {
25032            mCallbacks.unregister(callback);
25033        }
25034
25035        @Override
25036        public void handleMessage(Message msg) {
25037            final SomeArgs args = (SomeArgs) msg.obj;
25038            final int n = mCallbacks.beginBroadcast();
25039            for (int i = 0; i < n; i++) {
25040                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25041                try {
25042                    invokeCallback(callback, msg.what, args);
25043                } catch (RemoteException ignored) {
25044                }
25045            }
25046            mCallbacks.finishBroadcast();
25047            args.recycle();
25048        }
25049
25050        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25051                throws RemoteException {
25052            switch (what) {
25053                case MSG_CREATED: {
25054                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25055                    break;
25056                }
25057                case MSG_STATUS_CHANGED: {
25058                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25059                    break;
25060                }
25061            }
25062        }
25063
25064        private void notifyCreated(int moveId, Bundle extras) {
25065            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25066
25067            final SomeArgs args = SomeArgs.obtain();
25068            args.argi1 = moveId;
25069            args.arg2 = extras;
25070            obtainMessage(MSG_CREATED, args).sendToTarget();
25071        }
25072
25073        private void notifyStatusChanged(int moveId, int status) {
25074            notifyStatusChanged(moveId, status, -1);
25075        }
25076
25077        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25078            Slog.v(TAG, "Move " + moveId + " status " + status);
25079
25080            final SomeArgs args = SomeArgs.obtain();
25081            args.argi1 = moveId;
25082            args.argi2 = status;
25083            args.arg3 = estMillis;
25084            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25085
25086            synchronized (mLastStatus) {
25087                mLastStatus.put(moveId, status);
25088            }
25089        }
25090    }
25091
25092    private final static class OnPermissionChangeListeners extends Handler {
25093        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25094
25095        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25096                new RemoteCallbackList<>();
25097
25098        public OnPermissionChangeListeners(Looper looper) {
25099            super(looper);
25100        }
25101
25102        @Override
25103        public void handleMessage(Message msg) {
25104            switch (msg.what) {
25105                case MSG_ON_PERMISSIONS_CHANGED: {
25106                    final int uid = msg.arg1;
25107                    handleOnPermissionsChanged(uid);
25108                } break;
25109            }
25110        }
25111
25112        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25113            mPermissionListeners.register(listener);
25114
25115        }
25116
25117        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25118            mPermissionListeners.unregister(listener);
25119        }
25120
25121        public void onPermissionsChanged(int uid) {
25122            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25123                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25124            }
25125        }
25126
25127        private void handleOnPermissionsChanged(int uid) {
25128            final int count = mPermissionListeners.beginBroadcast();
25129            try {
25130                for (int i = 0; i < count; i++) {
25131                    IOnPermissionsChangeListener callback = mPermissionListeners
25132                            .getBroadcastItem(i);
25133                    try {
25134                        callback.onPermissionsChanged(uid);
25135                    } catch (RemoteException e) {
25136                        Log.e(TAG, "Permission listener is dead", e);
25137                    }
25138                }
25139            } finally {
25140                mPermissionListeners.finishBroadcast();
25141            }
25142        }
25143    }
25144
25145    private class PackageManagerNative extends IPackageManagerNative.Stub {
25146        @Override
25147        public String[] getNamesForUids(int[] uids) throws RemoteException {
25148            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25149            // massage results so they can be parsed by the native binder
25150            for (int i = results.length - 1; i >= 0; --i) {
25151                if (results[i] == null) {
25152                    results[i] = "";
25153                }
25154            }
25155            return results;
25156        }
25157    }
25158
25159    private class PackageManagerInternalImpl extends PackageManagerInternal {
25160        @Override
25161        public void setLocationPackagesProvider(PackagesProvider provider) {
25162            synchronized (mPackages) {
25163                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25164            }
25165        }
25166
25167        @Override
25168        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25169            synchronized (mPackages) {
25170                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25171            }
25172        }
25173
25174        @Override
25175        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25176            synchronized (mPackages) {
25177                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25178            }
25179        }
25180
25181        @Override
25182        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25183            synchronized (mPackages) {
25184                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25185            }
25186        }
25187
25188        @Override
25189        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25190            synchronized (mPackages) {
25191                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25192            }
25193        }
25194
25195        @Override
25196        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25197            synchronized (mPackages) {
25198                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25199            }
25200        }
25201
25202        @Override
25203        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25204            synchronized (mPackages) {
25205                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25206                        packageName, userId);
25207            }
25208        }
25209
25210        @Override
25211        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25212            synchronized (mPackages) {
25213                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25214                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25215                        packageName, userId);
25216            }
25217        }
25218
25219        @Override
25220        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25221            synchronized (mPackages) {
25222                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25223                        packageName, userId);
25224            }
25225        }
25226
25227        @Override
25228        public void setKeepUninstalledPackages(final List<String> packageList) {
25229            Preconditions.checkNotNull(packageList);
25230            List<String> removedFromList = null;
25231            synchronized (mPackages) {
25232                if (mKeepUninstalledPackages != null) {
25233                    final int packagesCount = mKeepUninstalledPackages.size();
25234                    for (int i = 0; i < packagesCount; i++) {
25235                        String oldPackage = mKeepUninstalledPackages.get(i);
25236                        if (packageList != null && packageList.contains(oldPackage)) {
25237                            continue;
25238                        }
25239                        if (removedFromList == null) {
25240                            removedFromList = new ArrayList<>();
25241                        }
25242                        removedFromList.add(oldPackage);
25243                    }
25244                }
25245                mKeepUninstalledPackages = new ArrayList<>(packageList);
25246                if (removedFromList != null) {
25247                    final int removedCount = removedFromList.size();
25248                    for (int i = 0; i < removedCount; i++) {
25249                        deletePackageIfUnusedLPr(removedFromList.get(i));
25250                    }
25251                }
25252            }
25253        }
25254
25255        @Override
25256        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25257            synchronized (mPackages) {
25258                // If we do not support permission review, done.
25259                if (!mPermissionReviewRequired) {
25260                    return false;
25261                }
25262
25263                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25264                if (packageSetting == null) {
25265                    return false;
25266                }
25267
25268                // Permission review applies only to apps not supporting the new permission model.
25269                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25270                    return false;
25271                }
25272
25273                // Legacy apps have the permission and get user consent on launch.
25274                PermissionsState permissionsState = packageSetting.getPermissionsState();
25275                return permissionsState.isPermissionReviewRequired(userId);
25276            }
25277        }
25278
25279        @Override
25280        public PackageInfo getPackageInfo(
25281                String packageName, int flags, int filterCallingUid, int userId) {
25282            return PackageManagerService.this
25283                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25284                            flags, filterCallingUid, userId);
25285        }
25286
25287        @Override
25288        public ApplicationInfo getApplicationInfo(
25289                String packageName, int flags, int filterCallingUid, int userId) {
25290            return PackageManagerService.this
25291                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25292        }
25293
25294        @Override
25295        public ActivityInfo getActivityInfo(
25296                ComponentName component, int flags, int filterCallingUid, int userId) {
25297            return PackageManagerService.this
25298                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25299        }
25300
25301        @Override
25302        public List<ResolveInfo> queryIntentActivities(
25303                Intent intent, int flags, int filterCallingUid, int userId) {
25304            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25305            return PackageManagerService.this
25306                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25307                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25308        }
25309
25310        @Override
25311        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25312                int userId) {
25313            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25314        }
25315
25316        @Override
25317        public void setDeviceAndProfileOwnerPackages(
25318                int deviceOwnerUserId, String deviceOwnerPackage,
25319                SparseArray<String> profileOwnerPackages) {
25320            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25321                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25322        }
25323
25324        @Override
25325        public boolean isPackageDataProtected(int userId, String packageName) {
25326            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25327        }
25328
25329        @Override
25330        public boolean isPackageEphemeral(int userId, String packageName) {
25331            synchronized (mPackages) {
25332                final PackageSetting ps = mSettings.mPackages.get(packageName);
25333                return ps != null ? ps.getInstantApp(userId) : false;
25334            }
25335        }
25336
25337        @Override
25338        public boolean wasPackageEverLaunched(String packageName, int userId) {
25339            synchronized (mPackages) {
25340                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25341            }
25342        }
25343
25344        @Override
25345        public void grantRuntimePermission(String packageName, String name, int userId,
25346                boolean overridePolicy) {
25347            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25348                    overridePolicy);
25349        }
25350
25351        @Override
25352        public void revokeRuntimePermission(String packageName, String name, int userId,
25353                boolean overridePolicy) {
25354            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25355                    overridePolicy);
25356        }
25357
25358        @Override
25359        public String getNameForUid(int uid) {
25360            return PackageManagerService.this.getNameForUid(uid);
25361        }
25362
25363        @Override
25364        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25365                Intent origIntent, String resolvedType, String callingPackage,
25366                Bundle verificationBundle, int userId) {
25367            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25368                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25369                    userId);
25370        }
25371
25372        @Override
25373        public void grantEphemeralAccess(int userId, Intent intent,
25374                int targetAppId, int ephemeralAppId) {
25375            synchronized (mPackages) {
25376                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25377                        targetAppId, ephemeralAppId);
25378            }
25379        }
25380
25381        @Override
25382        public boolean isInstantAppInstallerComponent(ComponentName component) {
25383            synchronized (mPackages) {
25384                return mInstantAppInstallerActivity != null
25385                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25386            }
25387        }
25388
25389        @Override
25390        public void pruneInstantApps() {
25391            mInstantAppRegistry.pruneInstantApps();
25392        }
25393
25394        @Override
25395        public String getSetupWizardPackageName() {
25396            return mSetupWizardPackage;
25397        }
25398
25399        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25400            if (policy != null) {
25401                mExternalSourcesPolicy = policy;
25402            }
25403        }
25404
25405        @Override
25406        public boolean isPackagePersistent(String packageName) {
25407            synchronized (mPackages) {
25408                PackageParser.Package pkg = mPackages.get(packageName);
25409                return pkg != null
25410                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25411                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25412                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25413                        : false;
25414            }
25415        }
25416
25417        @Override
25418        public List<PackageInfo> getOverlayPackages(int userId) {
25419            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25420            synchronized (mPackages) {
25421                for (PackageParser.Package p : mPackages.values()) {
25422                    if (p.mOverlayTarget != null) {
25423                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25424                        if (pkg != null) {
25425                            overlayPackages.add(pkg);
25426                        }
25427                    }
25428                }
25429            }
25430            return overlayPackages;
25431        }
25432
25433        @Override
25434        public List<String> getTargetPackageNames(int userId) {
25435            List<String> targetPackages = new ArrayList<>();
25436            synchronized (mPackages) {
25437                for (PackageParser.Package p : mPackages.values()) {
25438                    if (p.mOverlayTarget == null) {
25439                        targetPackages.add(p.packageName);
25440                    }
25441                }
25442            }
25443            return targetPackages;
25444        }
25445
25446        @Override
25447        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25448                @Nullable List<String> overlayPackageNames) {
25449            synchronized (mPackages) {
25450                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25451                    Slog.e(TAG, "failed to find package " + targetPackageName);
25452                    return false;
25453                }
25454                ArrayList<String> overlayPaths = null;
25455                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25456                    final int N = overlayPackageNames.size();
25457                    overlayPaths = new ArrayList<>(N);
25458                    for (int i = 0; i < N; i++) {
25459                        final String packageName = overlayPackageNames.get(i);
25460                        final PackageParser.Package pkg = mPackages.get(packageName);
25461                        if (pkg == null) {
25462                            Slog.e(TAG, "failed to find package " + packageName);
25463                            return false;
25464                        }
25465                        overlayPaths.add(pkg.baseCodePath);
25466                    }
25467                }
25468
25469                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25470                ps.setOverlayPaths(overlayPaths, userId);
25471                return true;
25472            }
25473        }
25474
25475        @Override
25476        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25477                int flags, int userId) {
25478            return resolveIntentInternal(
25479                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25480        }
25481
25482        @Override
25483        public ResolveInfo resolveService(Intent intent, String resolvedType,
25484                int flags, int userId, int callingUid) {
25485            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25486        }
25487
25488        @Override
25489        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25490            synchronized (mPackages) {
25491                mIsolatedOwners.put(isolatedUid, ownerUid);
25492            }
25493        }
25494
25495        @Override
25496        public void removeIsolatedUid(int isolatedUid) {
25497            synchronized (mPackages) {
25498                mIsolatedOwners.delete(isolatedUid);
25499            }
25500        }
25501
25502        @Override
25503        public int getUidTargetSdkVersion(int uid) {
25504            synchronized (mPackages) {
25505                return getUidTargetSdkVersionLockedLPr(uid);
25506            }
25507        }
25508
25509        @Override
25510        public boolean canAccessInstantApps(int callingUid, int userId) {
25511            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25512        }
25513
25514        @Override
25515        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25516            synchronized (mPackages) {
25517                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25518            }
25519        }
25520
25521        @Override
25522        public void notifyPackageUse(String packageName, int reason) {
25523            synchronized (mPackages) {
25524                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25525            }
25526        }
25527    }
25528
25529    @Override
25530    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25531        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25532        synchronized (mPackages) {
25533            final long identity = Binder.clearCallingIdentity();
25534            try {
25535                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25536                        packageNames, userId);
25537            } finally {
25538                Binder.restoreCallingIdentity(identity);
25539            }
25540        }
25541    }
25542
25543    @Override
25544    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25545        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25546        synchronized (mPackages) {
25547            final long identity = Binder.clearCallingIdentity();
25548            try {
25549                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25550                        packageNames, userId);
25551            } finally {
25552                Binder.restoreCallingIdentity(identity);
25553            }
25554        }
25555    }
25556
25557    private static void enforceSystemOrPhoneCaller(String tag) {
25558        int callingUid = Binder.getCallingUid();
25559        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25560            throw new SecurityException(
25561                    "Cannot call " + tag + " from UID " + callingUid);
25562        }
25563    }
25564
25565    boolean isHistoricalPackageUsageAvailable() {
25566        return mPackageUsage.isHistoricalPackageUsageAvailable();
25567    }
25568
25569    /**
25570     * Return a <b>copy</b> of the collection of packages known to the package manager.
25571     * @return A copy of the values of mPackages.
25572     */
25573    Collection<PackageParser.Package> getPackages() {
25574        synchronized (mPackages) {
25575            return new ArrayList<>(mPackages.values());
25576        }
25577    }
25578
25579    /**
25580     * Logs process start information (including base APK hash) to the security log.
25581     * @hide
25582     */
25583    @Override
25584    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25585            String apkFile, int pid) {
25586        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25587            return;
25588        }
25589        if (!SecurityLog.isLoggingEnabled()) {
25590            return;
25591        }
25592        Bundle data = new Bundle();
25593        data.putLong("startTimestamp", System.currentTimeMillis());
25594        data.putString("processName", processName);
25595        data.putInt("uid", uid);
25596        data.putString("seinfo", seinfo);
25597        data.putString("apkFile", apkFile);
25598        data.putInt("pid", pid);
25599        Message msg = mProcessLoggingHandler.obtainMessage(
25600                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25601        msg.setData(data);
25602        mProcessLoggingHandler.sendMessage(msg);
25603    }
25604
25605    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25606        return mCompilerStats.getPackageStats(pkgName);
25607    }
25608
25609    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25610        return getOrCreateCompilerPackageStats(pkg.packageName);
25611    }
25612
25613    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25614        return mCompilerStats.getOrCreatePackageStats(pkgName);
25615    }
25616
25617    public void deleteCompilerPackageStats(String pkgName) {
25618        mCompilerStats.deletePackageStats(pkgName);
25619    }
25620
25621    @Override
25622    public int getInstallReason(String packageName, int userId) {
25623        final int callingUid = Binder.getCallingUid();
25624        enforceCrossUserPermission(callingUid, userId,
25625                true /* requireFullPermission */, false /* checkShell */,
25626                "get install reason");
25627        synchronized (mPackages) {
25628            final PackageSetting ps = mSettings.mPackages.get(packageName);
25629            if (filterAppAccessLPr(ps, callingUid, userId)) {
25630                return PackageManager.INSTALL_REASON_UNKNOWN;
25631            }
25632            if (ps != null) {
25633                return ps.getInstallReason(userId);
25634            }
25635        }
25636        return PackageManager.INSTALL_REASON_UNKNOWN;
25637    }
25638
25639    @Override
25640    public boolean canRequestPackageInstalls(String packageName, int userId) {
25641        return canRequestPackageInstallsInternal(packageName, 0, userId,
25642                true /* throwIfPermNotDeclared*/);
25643    }
25644
25645    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25646            boolean throwIfPermNotDeclared) {
25647        int callingUid = Binder.getCallingUid();
25648        int uid = getPackageUid(packageName, 0, userId);
25649        if (callingUid != uid && callingUid != Process.ROOT_UID
25650                && callingUid != Process.SYSTEM_UID) {
25651            throw new SecurityException(
25652                    "Caller uid " + callingUid + " does not own package " + packageName);
25653        }
25654        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25655        if (info == null) {
25656            return false;
25657        }
25658        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25659            return false;
25660        }
25661        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25662        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25663        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25664            if (throwIfPermNotDeclared) {
25665                throw new SecurityException("Need to declare " + appOpPermission
25666                        + " to call this api");
25667            } else {
25668                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25669                return false;
25670            }
25671        }
25672        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25673            return false;
25674        }
25675        if (mExternalSourcesPolicy != null) {
25676            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25677            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25678                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25679            }
25680        }
25681        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25682    }
25683
25684    @Override
25685    public ComponentName getInstantAppResolverSettingsComponent() {
25686        return mInstantAppResolverSettingsComponent;
25687    }
25688
25689    @Override
25690    public ComponentName getInstantAppInstallerComponent() {
25691        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25692            return null;
25693        }
25694        return mInstantAppInstallerActivity == null
25695                ? null : mInstantAppInstallerActivity.getComponentName();
25696    }
25697
25698    @Override
25699    public String getInstantAppAndroidId(String packageName, int userId) {
25700        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25701                "getInstantAppAndroidId");
25702        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25703                true /* requireFullPermission */, false /* checkShell */,
25704                "getInstantAppAndroidId");
25705        // Make sure the target is an Instant App.
25706        if (!isInstantApp(packageName, userId)) {
25707            return null;
25708        }
25709        synchronized (mPackages) {
25710            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25711        }
25712    }
25713
25714    boolean canHaveOatDir(String packageName) {
25715        synchronized (mPackages) {
25716            PackageParser.Package p = mPackages.get(packageName);
25717            if (p == null) {
25718                return false;
25719            }
25720            return p.canHaveOatDir();
25721        }
25722    }
25723
25724    private String getOatDir(PackageParser.Package pkg) {
25725        if (!pkg.canHaveOatDir()) {
25726            return null;
25727        }
25728        File codePath = new File(pkg.codePath);
25729        if (codePath.isDirectory()) {
25730            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25731        }
25732        return null;
25733    }
25734
25735    void deleteOatArtifactsOfPackage(String packageName) {
25736        final String[] instructionSets;
25737        final List<String> codePaths;
25738        final String oatDir;
25739        final PackageParser.Package pkg;
25740        synchronized (mPackages) {
25741            pkg = mPackages.get(packageName);
25742        }
25743        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25744        codePaths = pkg.getAllCodePaths();
25745        oatDir = getOatDir(pkg);
25746
25747        for (String codePath : codePaths) {
25748            for (String isa : instructionSets) {
25749                try {
25750                    mInstaller.deleteOdex(codePath, isa, oatDir);
25751                } catch (InstallerException e) {
25752                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25753                }
25754            }
25755        }
25756    }
25757
25758    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25759        Set<String> unusedPackages = new HashSet<>();
25760        long currentTimeInMillis = System.currentTimeMillis();
25761        synchronized (mPackages) {
25762            for (PackageParser.Package pkg : mPackages.values()) {
25763                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25764                if (ps == null) {
25765                    continue;
25766                }
25767                PackageDexUsage.PackageUseInfo packageUseInfo =
25768                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25769                if (PackageManagerServiceUtils
25770                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25771                                downgradeTimeThresholdMillis, packageUseInfo,
25772                                pkg.getLatestPackageUseTimeInMills(),
25773                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25774                    unusedPackages.add(pkg.packageName);
25775                }
25776            }
25777        }
25778        return unusedPackages;
25779    }
25780}
25781
25782interface PackageSender {
25783    void sendPackageBroadcast(final String action, final String pkg,
25784        final Bundle extras, final int flags, final String targetPkg,
25785        final IIntentReceiver finishedReceiver, final int[] userIds);
25786    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25787        boolean includeStopped, int appId, int... userIds);
25788}
25789