PackageManagerService.java revision 4f41e849f1b7d6d037439d60eace1b134165a148
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.PARSE_IS_OEM;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
109
110import android.Manifest;
111import android.annotation.IntDef;
112import android.annotation.NonNull;
113import android.annotation.Nullable;
114import android.app.ActivityManager;
115import android.app.AppOpsManager;
116import android.app.IActivityManager;
117import android.app.ResourcesManager;
118import android.app.admin.IDevicePolicyManager;
119import android.app.admin.SecurityLog;
120import android.app.backup.IBackupManager;
121import android.content.BroadcastReceiver;
122import android.content.ComponentName;
123import android.content.ContentResolver;
124import android.content.Context;
125import android.content.IIntentReceiver;
126import android.content.Intent;
127import android.content.IntentFilter;
128import android.content.IntentSender;
129import android.content.IntentSender.SendIntentException;
130import android.content.ServiceConnection;
131import android.content.pm.ActivityInfo;
132import android.content.pm.ApplicationInfo;
133import android.content.pm.AppsQueryHelper;
134import android.content.pm.AuxiliaryResolveInfo;
135import android.content.pm.ChangedPackages;
136import android.content.pm.ComponentInfo;
137import android.content.pm.FallbackCategoryProvider;
138import android.content.pm.FeatureInfo;
139import android.content.pm.IDexModuleRegisterCallback;
140import android.content.pm.IOnPermissionsChangeListener;
141import android.content.pm.IPackageDataObserver;
142import android.content.pm.IPackageDeleteObserver;
143import android.content.pm.IPackageDeleteObserver2;
144import android.content.pm.IPackageInstallObserver2;
145import android.content.pm.IPackageInstaller;
146import android.content.pm.IPackageManager;
147import android.content.pm.IPackageManagerNative;
148import android.content.pm.IPackageMoveObserver;
149import android.content.pm.IPackageStatsObserver;
150import android.content.pm.InstantAppInfo;
151import android.content.pm.InstantAppRequest;
152import android.content.pm.InstantAppResolveInfo;
153import android.content.pm.InstrumentationInfo;
154import android.content.pm.IntentFilterVerificationInfo;
155import android.content.pm.KeySet;
156import android.content.pm.PackageCleanItem;
157import android.content.pm.PackageInfo;
158import android.content.pm.PackageInfoLite;
159import android.content.pm.PackageInstaller;
160import android.content.pm.PackageManager;
161import android.content.pm.PackageManagerInternal;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageParser;
164import android.content.pm.PackageParser.ActivityIntentInfo;
165import android.content.pm.PackageParser.Package;
166import android.content.pm.PackageParser.PackageLite;
167import android.content.pm.PackageParser.PackageParserException;
168import android.content.pm.PackageStats;
169import android.content.pm.PackageUserState;
170import android.content.pm.ParceledListSlice;
171import android.content.pm.PermissionGroupInfo;
172import android.content.pm.PermissionInfo;
173import android.content.pm.ProviderInfo;
174import android.content.pm.ResolveInfo;
175import android.content.pm.ServiceInfo;
176import android.content.pm.SharedLibraryInfo;
177import android.content.pm.Signature;
178import android.content.pm.UserInfo;
179import android.content.pm.VerifierDeviceIdentity;
180import android.content.pm.VerifierInfo;
181import android.content.pm.VersionedPackage;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.DisplayMetrics;
233import android.util.EventLog;
234import android.util.ExceptionUtils;
235import android.util.Log;
236import android.util.LogPrinter;
237import android.util.MathUtils;
238import android.util.PackageUtils;
239import android.util.Pair;
240import android.util.PrintStreamPrinter;
241import android.util.Slog;
242import android.util.SparseArray;
243import android.util.SparseBooleanArray;
244import android.util.SparseIntArray;
245import android.util.TimingsTraceLog;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.Settings.DatabaseVersion;
286import com.android.server.pm.Settings.VersionInfo;
287import com.android.server.pm.dex.DexManager;
288import com.android.server.pm.dex.DexoptOptions;
289import com.android.server.pm.dex.PackageDexUsage;
290import com.android.server.pm.permission.BasePermission;
291import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
292import com.android.server.pm.permission.PermissionManagerService;
293import com.android.server.pm.permission.PermissionManagerInternal;
294import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
295import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
296import com.android.server.pm.permission.PermissionsState;
297import com.android.server.pm.permission.PermissionsState.PermissionState;
298import com.android.server.storage.DeviceStorageMonitorInternal;
299
300import dalvik.system.CloseGuard;
301import dalvik.system.DexFile;
302import dalvik.system.VMRuntime;
303
304import libcore.io.IoUtils;
305import libcore.io.Streams;
306import libcore.util.EmptyArray;
307
308import org.xmlpull.v1.XmlPullParser;
309import org.xmlpull.v1.XmlPullParserException;
310import org.xmlpull.v1.XmlSerializer;
311
312import java.io.BufferedOutputStream;
313import java.io.BufferedReader;
314import java.io.ByteArrayInputStream;
315import java.io.ByteArrayOutputStream;
316import java.io.File;
317import java.io.FileDescriptor;
318import java.io.FileInputStream;
319import java.io.FileOutputStream;
320import java.io.FileReader;
321import java.io.FilenameFilter;
322import java.io.IOException;
323import java.io.InputStream;
324import java.io.OutputStream;
325import java.io.PrintWriter;
326import java.lang.annotation.Retention;
327import java.lang.annotation.RetentionPolicy;
328import java.nio.charset.StandardCharsets;
329import java.security.DigestInputStream;
330import java.security.MessageDigest;
331import java.security.NoSuchAlgorithmException;
332import java.security.PublicKey;
333import java.security.SecureRandom;
334import java.security.cert.Certificate;
335import java.security.cert.CertificateEncodingException;
336import java.security.cert.CertificateException;
337import java.text.SimpleDateFormat;
338import java.util.ArrayList;
339import java.util.Arrays;
340import java.util.Collection;
341import java.util.Collections;
342import java.util.Comparator;
343import java.util.Date;
344import java.util.HashMap;
345import java.util.HashSet;
346import java.util.Iterator;
347import java.util.LinkedHashSet;
348import java.util.List;
349import java.util.Map;
350import java.util.Objects;
351import java.util.Set;
352import java.util.concurrent.CountDownLatch;
353import java.util.concurrent.Future;
354import java.util.concurrent.TimeUnit;
355import java.util.concurrent.atomic.AtomicBoolean;
356import java.util.concurrent.atomic.AtomicInteger;
357import java.util.zip.GZIPInputStream;
358
359/**
360 * Keep track of all those APKs everywhere.
361 * <p>
362 * Internally there are two important locks:
363 * <ul>
364 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
365 * and other related state. It is a fine-grained lock that should only be held
366 * momentarily, as it's one of the most contended locks in the system.
367 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
368 * operations typically involve heavy lifting of application data on disk. Since
369 * {@code installd} is single-threaded, and it's operations can often be slow,
370 * this lock should never be acquired while already holding {@link #mPackages}.
371 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
372 * holding {@link #mInstallLock}.
373 * </ul>
374 * Many internal methods rely on the caller to hold the appropriate locks, and
375 * this contract is expressed through method name suffixes:
376 * <ul>
377 * <li>fooLI(): the caller must hold {@link #mInstallLock}
378 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
379 * being modified must be frozen
380 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
381 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
382 * </ul>
383 * <p>
384 * Because this class is very central to the platform's security; please run all
385 * CTS and unit tests whenever making modifications:
386 *
387 * <pre>
388 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
389 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
390 * </pre>
391 */
392public class PackageManagerService extends IPackageManager.Stub
393        implements PackageSender {
394    static final String TAG = "PackageManager";
395    public static final boolean DEBUG_SETTINGS = false;
396    static final boolean DEBUG_PREFERRED = false;
397    static final boolean DEBUG_UPGRADE = false;
398    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
399    private static final boolean DEBUG_BACKUP = false;
400    private static final boolean DEBUG_INSTALL = false;
401    public static final boolean DEBUG_REMOVE = false;
402    private static final boolean DEBUG_BROADCASTS = false;
403    private static final boolean DEBUG_SHOW_INFO = false;
404    private static final boolean DEBUG_PACKAGE_INFO = false;
405    private static final boolean DEBUG_INTENT_MATCHING = false;
406    public static final boolean DEBUG_PACKAGE_SCANNING = false;
407    private static final boolean DEBUG_VERIFY = false;
408    private static final boolean DEBUG_FILTERS = false;
409    public static final boolean DEBUG_PERMISSIONS = false;
410    private static final boolean DEBUG_SHARED_LIBRARIES = false;
411    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
412
413    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
414    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
415    // user, but by default initialize to this.
416    public static final boolean DEBUG_DEXOPT = false;
417
418    private static final boolean DEBUG_ABI_SELECTION = false;
419    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
420    private static final boolean DEBUG_TRIAGED_MISSING = false;
421    private static final boolean DEBUG_APP_DATA = false;
422
423    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
424    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
425
426    private static final boolean HIDE_EPHEMERAL_APIS = false;
427
428    private static final boolean ENABLE_FREE_CACHE_V2 =
429            SystemProperties.getBoolean("fw.free_cache_v2", true);
430
431    private static final int RADIO_UID = Process.PHONE_UID;
432    private static final int LOG_UID = Process.LOG_UID;
433    private static final int NFC_UID = Process.NFC_UID;
434    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
435    private static final int SHELL_UID = Process.SHELL_UID;
436
437    // Suffix used during package installation when copying/moving
438    // package apks to install directory.
439    private static final String INSTALL_PACKAGE_SUFFIX = "-";
440
441    static final int SCAN_NO_DEX = 1<<1;
442    static final int SCAN_FORCE_DEX = 1<<2;
443    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
444    static final int SCAN_NEW_INSTALL = 1<<4;
445    static final int SCAN_UPDATE_TIME = 1<<5;
446    static final int SCAN_BOOTING = 1<<6;
447    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
448    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
449    static final int SCAN_REPLACING = 1<<9;
450    static final int SCAN_REQUIRE_KNOWN = 1<<10;
451    static final int SCAN_MOVE = 1<<11;
452    static final int SCAN_INITIAL = 1<<12;
453    static final int SCAN_CHECK_ONLY = 1<<13;
454    static final int SCAN_DONT_KILL_APP = 1<<14;
455    static final int SCAN_IGNORE_FROZEN = 1<<15;
456    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
457    static final int SCAN_AS_INSTANT_APP = 1<<17;
458    static final int SCAN_AS_FULL_APP = 1<<18;
459    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
460    /** Should not be with the scan flags */
461    static final int FLAGS_REMOVE_CHATTY = 1<<31;
462
463    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
464    /** Extension of the compressed packages */
465    private final static String COMPRESSED_EXTENSION = ".gz";
466    /** Suffix of stub packages on the system partition */
467    private final static String STUB_SUFFIX = "-Stub";
468
469    private static final int[] EMPTY_INT_ARRAY = new int[0];
470
471    private static final int TYPE_UNKNOWN = 0;
472    private static final int TYPE_ACTIVITY = 1;
473    private static final int TYPE_RECEIVER = 2;
474    private static final int TYPE_SERVICE = 3;
475    private static final int TYPE_PROVIDER = 4;
476    @IntDef(prefix = { "TYPE_" }, value = {
477            TYPE_UNKNOWN,
478            TYPE_ACTIVITY,
479            TYPE_RECEIVER,
480            TYPE_SERVICE,
481            TYPE_PROVIDER,
482    })
483    @Retention(RetentionPolicy.SOURCE)
484    public @interface ComponentType {}
485
486    /**
487     * Timeout (in milliseconds) after which the watchdog should declare that
488     * our handler thread is wedged.  The usual default for such things is one
489     * minute but we sometimes do very lengthy I/O operations on this thread,
490     * such as installing multi-gigabyte applications, so ours needs to be longer.
491     */
492    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
493
494    /**
495     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
496     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
497     * settings entry if available, otherwise we use the hardcoded default.  If it's been
498     * more than this long since the last fstrim, we force one during the boot sequence.
499     *
500     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
501     * one gets run at the next available charging+idle time.  This final mandatory
502     * no-fstrim check kicks in only of the other scheduling criteria is never met.
503     */
504    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
505
506    /**
507     * Whether verification is enabled by default.
508     */
509    private static final boolean DEFAULT_VERIFY_ENABLE = true;
510
511    /**
512     * The default maximum time to wait for the verification agent to return in
513     * milliseconds.
514     */
515    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
516
517    /**
518     * The default response for package verification timeout.
519     *
520     * This can be either PackageManager.VERIFICATION_ALLOW or
521     * PackageManager.VERIFICATION_REJECT.
522     */
523    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
524
525    static final String PLATFORM_PACKAGE_NAME = "android";
526
527    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
528
529    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
530            DEFAULT_CONTAINER_PACKAGE,
531            "com.android.defcontainer.DefaultContainerService");
532
533    private static final String KILL_APP_REASON_GIDS_CHANGED =
534            "permission grant or revoke changed gids";
535
536    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
537            "permissions revoked";
538
539    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
540
541    private static final String PACKAGE_SCHEME = "package";
542
543    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
544
545    /** Permission grant: not grant the permission. */
546    private static final int GRANT_DENIED = 1;
547
548    /** Permission grant: grant the permission as an install permission. */
549    private static final int GRANT_INSTALL = 2;
550
551    /** Permission grant: grant the permission as a runtime one. */
552    private static final int GRANT_RUNTIME = 3;
553
554    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
555    private static final int GRANT_UPGRADE = 4;
556
557    /** Canonical intent used to identify what counts as a "web browser" app */
558    private static final Intent sBrowserIntent;
559    static {
560        sBrowserIntent = new Intent();
561        sBrowserIntent.setAction(Intent.ACTION_VIEW);
562        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
563        sBrowserIntent.setData(Uri.parse("http:"));
564    }
565
566    /**
567     * The set of all protected actions [i.e. those actions for which a high priority
568     * intent filter is disallowed].
569     */
570    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
571    static {
572        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
573        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
574        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
575        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
576    }
577
578    // Compilation reasons.
579    public static final int REASON_FIRST_BOOT = 0;
580    public static final int REASON_BOOT = 1;
581    public static final int REASON_INSTALL = 2;
582    public static final int REASON_BACKGROUND_DEXOPT = 3;
583    public static final int REASON_AB_OTA = 4;
584    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
585    public static final int REASON_SHARED = 6;
586
587    public static final int REASON_LAST = REASON_SHARED;
588
589    /** All dangerous permission names in the same order as the events in MetricsEvent */
590    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
591            Manifest.permission.READ_CALENDAR,
592            Manifest.permission.WRITE_CALENDAR,
593            Manifest.permission.CAMERA,
594            Manifest.permission.READ_CONTACTS,
595            Manifest.permission.WRITE_CONTACTS,
596            Manifest.permission.GET_ACCOUNTS,
597            Manifest.permission.ACCESS_FINE_LOCATION,
598            Manifest.permission.ACCESS_COARSE_LOCATION,
599            Manifest.permission.RECORD_AUDIO,
600            Manifest.permission.READ_PHONE_STATE,
601            Manifest.permission.CALL_PHONE,
602            Manifest.permission.READ_CALL_LOG,
603            Manifest.permission.WRITE_CALL_LOG,
604            Manifest.permission.ADD_VOICEMAIL,
605            Manifest.permission.USE_SIP,
606            Manifest.permission.PROCESS_OUTGOING_CALLS,
607            Manifest.permission.READ_CELL_BROADCASTS,
608            Manifest.permission.BODY_SENSORS,
609            Manifest.permission.SEND_SMS,
610            Manifest.permission.RECEIVE_SMS,
611            Manifest.permission.READ_SMS,
612            Manifest.permission.RECEIVE_WAP_PUSH,
613            Manifest.permission.RECEIVE_MMS,
614            Manifest.permission.READ_EXTERNAL_STORAGE,
615            Manifest.permission.WRITE_EXTERNAL_STORAGE,
616            Manifest.permission.READ_PHONE_NUMBERS,
617            Manifest.permission.ANSWER_PHONE_CALLS);
618
619
620    /**
621     * Version number for the package parser cache. Increment this whenever the format or
622     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
623     */
624    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
625
626    /**
627     * Whether the package parser cache is enabled.
628     */
629    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
630
631    final ServiceThread mHandlerThread;
632
633    final PackageHandler mHandler;
634
635    private final ProcessLoggingHandler mProcessLoggingHandler;
636
637    /**
638     * Messages for {@link #mHandler} that need to wait for system ready before
639     * being dispatched.
640     */
641    private ArrayList<Message> mPostSystemReadyMessages;
642
643    final int mSdkVersion = Build.VERSION.SDK_INT;
644
645    final Context mContext;
646    final boolean mFactoryTest;
647    final boolean mOnlyCore;
648    final DisplayMetrics mMetrics;
649    final int mDefParseFlags;
650    final String[] mSeparateProcesses;
651    final boolean mIsUpgrade;
652    final boolean mIsPreNUpgrade;
653    final boolean mIsPreNMR1Upgrade;
654
655    // Have we told the Activity Manager to whitelist the default container service by uid yet?
656    @GuardedBy("mPackages")
657    boolean mDefaultContainerWhitelisted = false;
658
659    @GuardedBy("mPackages")
660    private boolean mDexOptDialogShown;
661
662    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
663    // LOCK HELD.  Can be called with mInstallLock held.
664    @GuardedBy("mInstallLock")
665    final Installer mInstaller;
666
667    /** Directory where installed third-party apps stored */
668    final File mAppInstallDir;
669
670    /**
671     * Directory to which applications installed internally have their
672     * 32 bit native libraries copied.
673     */
674    private File mAppLib32InstallDir;
675
676    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
677    // apps.
678    final File mDrmAppPrivateInstallDir;
679
680    // ----------------------------------------------------------------
681
682    // Lock for state used when installing and doing other long running
683    // operations.  Methods that must be called with this lock held have
684    // the suffix "LI".
685    final Object mInstallLock = new Object();
686
687    // ----------------------------------------------------------------
688
689    // Keys are String (package name), values are Package.  This also serves
690    // as the lock for the global state.  Methods that must be called with
691    // this lock held have the prefix "LP".
692    @GuardedBy("mPackages")
693    final ArrayMap<String, PackageParser.Package> mPackages =
694            new ArrayMap<String, PackageParser.Package>();
695
696    final ArrayMap<String, Set<String>> mKnownCodebase =
697            new ArrayMap<String, Set<String>>();
698
699    // Keys are isolated uids and values are the uid of the application
700    // that created the isolated proccess.
701    @GuardedBy("mPackages")
702    final SparseIntArray mIsolatedOwners = new SparseIntArray();
703
704    /**
705     * Tracks new system packages [received in an OTA] that we expect to
706     * find updated user-installed versions. Keys are package name, values
707     * are package location.
708     */
709    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
710    /**
711     * Tracks high priority intent filters for protected actions. During boot, certain
712     * filter actions are protected and should never be allowed to have a high priority
713     * intent filter for them. However, there is one, and only one exception -- the
714     * setup wizard. It must be able to define a high priority intent filter for these
715     * actions to ensure there are no escapes from the wizard. We need to delay processing
716     * of these during boot as we need to look at all of the system packages in order
717     * to know which component is the setup wizard.
718     */
719    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
720    /**
721     * Whether or not processing protected filters should be deferred.
722     */
723    private boolean mDeferProtectedFilters = true;
724
725    /**
726     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
727     */
728    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
729    /**
730     * Whether or not system app permissions should be promoted from install to runtime.
731     */
732    boolean mPromoteSystemApps;
733
734    @GuardedBy("mPackages")
735    final Settings mSettings;
736
737    /**
738     * Set of package names that are currently "frozen", which means active
739     * surgery is being done on the code/data for that package. The platform
740     * will refuse to launch frozen packages to avoid race conditions.
741     *
742     * @see PackageFreezer
743     */
744    @GuardedBy("mPackages")
745    final ArraySet<String> mFrozenPackages = new ArraySet<>();
746
747    final ProtectedPackages mProtectedPackages;
748
749    @GuardedBy("mLoadedVolumes")
750    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
751
752    boolean mFirstBoot;
753
754    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
755
756    // System configuration read by SystemConfig.
757    final int[] mGlobalGids;
758    final SparseArray<ArraySet<String>> mSystemPermissions;
759    @GuardedBy("mAvailableFeatures")
760    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
761
762    // If mac_permissions.xml was found for seinfo labeling.
763    boolean mFoundPolicyFile;
764
765    private final InstantAppRegistry mInstantAppRegistry;
766
767    @GuardedBy("mPackages")
768    int mChangedPackagesSequenceNumber;
769    /**
770     * List of changed [installed, removed or updated] packages.
771     * mapping from user id -> sequence number -> package name
772     */
773    @GuardedBy("mPackages")
774    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
775    /**
776     * The sequence number of the last change to a package.
777     * mapping from user id -> package name -> sequence number
778     */
779    @GuardedBy("mPackages")
780    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
781
782    class PackageParserCallback implements PackageParser.Callback {
783        @Override public final boolean hasFeature(String feature) {
784            return PackageManagerService.this.hasSystemFeature(feature, 0);
785        }
786
787        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
788                Collection<PackageParser.Package> allPackages, String targetPackageName) {
789            List<PackageParser.Package> overlayPackages = null;
790            for (PackageParser.Package p : allPackages) {
791                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
792                    if (overlayPackages == null) {
793                        overlayPackages = new ArrayList<PackageParser.Package>();
794                    }
795                    overlayPackages.add(p);
796                }
797            }
798            if (overlayPackages != null) {
799                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
800                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
801                        return p1.mOverlayPriority - p2.mOverlayPriority;
802                    }
803                };
804                Collections.sort(overlayPackages, cmp);
805            }
806            return overlayPackages;
807        }
808
809        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
810                String targetPackageName, String targetPath) {
811            if ("android".equals(targetPackageName)) {
812                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
813                // native AssetManager.
814                return null;
815            }
816            List<PackageParser.Package> overlayPackages =
817                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
818            if (overlayPackages == null || overlayPackages.isEmpty()) {
819                return null;
820            }
821            List<String> overlayPathList = null;
822            for (PackageParser.Package overlayPackage : overlayPackages) {
823                if (targetPath == null) {
824                    if (overlayPathList == null) {
825                        overlayPathList = new ArrayList<String>();
826                    }
827                    overlayPathList.add(overlayPackage.baseCodePath);
828                    continue;
829                }
830
831                try {
832                    // Creates idmaps for system to parse correctly the Android manifest of the
833                    // target package.
834                    //
835                    // OverlayManagerService will update each of them with a correct gid from its
836                    // target package app id.
837                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
838                            UserHandle.getSharedAppGid(
839                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
840                    if (overlayPathList == null) {
841                        overlayPathList = new ArrayList<String>();
842                    }
843                    overlayPathList.add(overlayPackage.baseCodePath);
844                } catch (InstallerException e) {
845                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
846                            overlayPackage.baseCodePath);
847                }
848            }
849            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
850        }
851
852        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
853            synchronized (mPackages) {
854                return getStaticOverlayPathsLocked(
855                        mPackages.values(), targetPackageName, targetPath);
856            }
857        }
858
859        @Override public final String[] getOverlayApks(String targetPackageName) {
860            return getStaticOverlayPaths(targetPackageName, null);
861        }
862
863        @Override public final String[] getOverlayPaths(String targetPackageName,
864                String targetPath) {
865            return getStaticOverlayPaths(targetPackageName, targetPath);
866        }
867    }
868
869    class ParallelPackageParserCallback extends PackageParserCallback {
870        List<PackageParser.Package> mOverlayPackages = null;
871
872        void findStaticOverlayPackages() {
873            synchronized (mPackages) {
874                for (PackageParser.Package p : mPackages.values()) {
875                    if (p.mIsStaticOverlay) {
876                        if (mOverlayPackages == null) {
877                            mOverlayPackages = new ArrayList<PackageParser.Package>();
878                        }
879                        mOverlayPackages.add(p);
880                    }
881                }
882            }
883        }
884
885        @Override
886        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
887            // We can trust mOverlayPackages without holding mPackages because package uninstall
888            // can't happen while running parallel parsing.
889            // Moreover holding mPackages on each parsing thread causes dead-lock.
890            return mOverlayPackages == null ? null :
891                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
892        }
893    }
894
895    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
896    final ParallelPackageParserCallback mParallelPackageParserCallback =
897            new ParallelPackageParserCallback();
898
899    public static final class SharedLibraryEntry {
900        public final @Nullable String path;
901        public final @Nullable String apk;
902        public final @NonNull SharedLibraryInfo info;
903
904        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
905                String declaringPackageName, int declaringPackageVersionCode) {
906            path = _path;
907            apk = _apk;
908            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
909                    declaringPackageName, declaringPackageVersionCode), null);
910        }
911    }
912
913    // Currently known shared libraries.
914    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
915    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
916            new ArrayMap<>();
917
918    // All available activities, for your resolving pleasure.
919    final ActivityIntentResolver mActivities =
920            new ActivityIntentResolver();
921
922    // All available receivers, for your resolving pleasure.
923    final ActivityIntentResolver mReceivers =
924            new ActivityIntentResolver();
925
926    // All available services, for your resolving pleasure.
927    final ServiceIntentResolver mServices = new ServiceIntentResolver();
928
929    // All available providers, for your resolving pleasure.
930    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
931
932    // Mapping from provider base names (first directory in content URI codePath)
933    // to the provider information.
934    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
935            new ArrayMap<String, PackageParser.Provider>();
936
937    // Mapping from instrumentation class names to info about them.
938    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
939            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
940
941    // Mapping from permission names to info about them.
942    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
943            new ArrayMap<String, PackageParser.PermissionGroup>();
944
945    // Packages whose data we have transfered into another package, thus
946    // should no longer exist.
947    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
948
949    // Broadcast actions that are only available to the system.
950    @GuardedBy("mProtectedBroadcasts")
951    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
952
953    /** List of packages waiting for verification. */
954    final SparseArray<PackageVerificationState> mPendingVerification
955            = new SparseArray<PackageVerificationState>();
956
957    final PackageInstallerService mInstallerService;
958
959    private final PackageDexOptimizer mPackageDexOptimizer;
960    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
961    // is used by other apps).
962    private final DexManager mDexManager;
963
964    private AtomicInteger mNextMoveId = new AtomicInteger();
965    private final MoveCallbacks mMoveCallbacks;
966
967    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
968
969    // Cache of users who need badging.
970    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
971
972    /** Token for keys in mPendingVerification. */
973    private int mPendingVerificationToken = 0;
974
975    volatile boolean mSystemReady;
976    volatile boolean mSafeMode;
977    volatile boolean mHasSystemUidErrors;
978    private volatile boolean mEphemeralAppsDisabled;
979
980    ApplicationInfo mAndroidApplication;
981    final ActivityInfo mResolveActivity = new ActivityInfo();
982    final ResolveInfo mResolveInfo = new ResolveInfo();
983    ComponentName mResolveComponentName;
984    PackageParser.Package mPlatformPackage;
985    ComponentName mCustomResolverComponentName;
986
987    boolean mResolverReplaced = false;
988
989    private final @Nullable ComponentName mIntentFilterVerifierComponent;
990    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
991
992    private int mIntentFilterVerificationToken = 0;
993
994    /** The service connection to the ephemeral resolver */
995    final EphemeralResolverConnection mInstantAppResolverConnection;
996    /** Component used to show resolver settings for Instant Apps */
997    final ComponentName mInstantAppResolverSettingsComponent;
998
999    /** Activity used to install instant applications */
1000    ActivityInfo mInstantAppInstallerActivity;
1001    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1002
1003    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1004            = new SparseArray<IntentFilterVerificationState>();
1005
1006    // TODO remove this and go through mPermissonManager directly
1007    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1008    private final PermissionManagerInternal mPermissionManager;
1009
1010    // List of packages names to keep cached, even if they are uninstalled for all users
1011    private List<String> mKeepUninstalledPackages;
1012
1013    private UserManagerInternal mUserManagerInternal;
1014
1015    private DeviceIdleController.LocalService mDeviceIdleController;
1016
1017    private File mCacheDir;
1018
1019    private ArraySet<String> mPrivappPermissionsViolations;
1020
1021    private Future<?> mPrepareAppDataFuture;
1022
1023    private static class IFVerificationParams {
1024        PackageParser.Package pkg;
1025        boolean replacing;
1026        int userId;
1027        int verifierUid;
1028
1029        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1030                int _userId, int _verifierUid) {
1031            pkg = _pkg;
1032            replacing = _replacing;
1033            userId = _userId;
1034            replacing = _replacing;
1035            verifierUid = _verifierUid;
1036        }
1037    }
1038
1039    private interface IntentFilterVerifier<T extends IntentFilter> {
1040        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1041                                               T filter, String packageName);
1042        void startVerifications(int userId);
1043        void receiveVerificationResponse(int verificationId);
1044    }
1045
1046    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1047        private Context mContext;
1048        private ComponentName mIntentFilterVerifierComponent;
1049        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1050
1051        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1052            mContext = context;
1053            mIntentFilterVerifierComponent = verifierComponent;
1054        }
1055
1056        private String getDefaultScheme() {
1057            return IntentFilter.SCHEME_HTTPS;
1058        }
1059
1060        @Override
1061        public void startVerifications(int userId) {
1062            // Launch verifications requests
1063            int count = mCurrentIntentFilterVerifications.size();
1064            for (int n=0; n<count; n++) {
1065                int verificationId = mCurrentIntentFilterVerifications.get(n);
1066                final IntentFilterVerificationState ivs =
1067                        mIntentFilterVerificationStates.get(verificationId);
1068
1069                String packageName = ivs.getPackageName();
1070
1071                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1072                final int filterCount = filters.size();
1073                ArraySet<String> domainsSet = new ArraySet<>();
1074                for (int m=0; m<filterCount; m++) {
1075                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1076                    domainsSet.addAll(filter.getHostsList());
1077                }
1078                synchronized (mPackages) {
1079                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1080                            packageName, domainsSet) != null) {
1081                        scheduleWriteSettingsLocked();
1082                    }
1083                }
1084                sendVerificationRequest(verificationId, ivs);
1085            }
1086            mCurrentIntentFilterVerifications.clear();
1087        }
1088
1089        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1090            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1091            verificationIntent.putExtra(
1092                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1093                    verificationId);
1094            verificationIntent.putExtra(
1095                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1096                    getDefaultScheme());
1097            verificationIntent.putExtra(
1098                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1099                    ivs.getHostsString());
1100            verificationIntent.putExtra(
1101                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1102                    ivs.getPackageName());
1103            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1104            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1105
1106            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1107            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1108                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1109                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1110
1111            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1112            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1113                    "Sending IntentFilter verification broadcast");
1114        }
1115
1116        public void receiveVerificationResponse(int verificationId) {
1117            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1118
1119            final boolean verified = ivs.isVerified();
1120
1121            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1122            final int count = filters.size();
1123            if (DEBUG_DOMAIN_VERIFICATION) {
1124                Slog.i(TAG, "Received verification response " + verificationId
1125                        + " for " + count + " filters, verified=" + verified);
1126            }
1127            for (int n=0; n<count; n++) {
1128                PackageParser.ActivityIntentInfo filter = filters.get(n);
1129                filter.setVerified(verified);
1130
1131                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1132                        + " verified with result:" + verified + " and hosts:"
1133                        + ivs.getHostsString());
1134            }
1135
1136            mIntentFilterVerificationStates.remove(verificationId);
1137
1138            final String packageName = ivs.getPackageName();
1139            IntentFilterVerificationInfo ivi = null;
1140
1141            synchronized (mPackages) {
1142                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1143            }
1144            if (ivi == null) {
1145                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1146                        + verificationId + " packageName:" + packageName);
1147                return;
1148            }
1149            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1150                    "Updating IntentFilterVerificationInfo for package " + packageName
1151                            +" verificationId:" + verificationId);
1152
1153            synchronized (mPackages) {
1154                if (verified) {
1155                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1156                } else {
1157                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1158                }
1159                scheduleWriteSettingsLocked();
1160
1161                final int userId = ivs.getUserId();
1162                if (userId != UserHandle.USER_ALL) {
1163                    final int userStatus =
1164                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1165
1166                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1167                    boolean needUpdate = false;
1168
1169                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1170                    // already been set by the User thru the Disambiguation dialog
1171                    switch (userStatus) {
1172                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1173                            if (verified) {
1174                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1175                            } else {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1177                            }
1178                            needUpdate = true;
1179                            break;
1180
1181                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1182                            if (verified) {
1183                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1184                                needUpdate = true;
1185                            }
1186                            break;
1187
1188                        default:
1189                            // Nothing to do
1190                    }
1191
1192                    if (needUpdate) {
1193                        mSettings.updateIntentFilterVerificationStatusLPw(
1194                                packageName, updatedStatus, userId);
1195                        scheduleWritePackageRestrictionsLocked(userId);
1196                    }
1197                }
1198            }
1199        }
1200
1201        @Override
1202        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1203                    ActivityIntentInfo filter, String packageName) {
1204            if (!hasValidDomains(filter)) {
1205                return false;
1206            }
1207            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1208            if (ivs == null) {
1209                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1210                        packageName);
1211            }
1212            if (DEBUG_DOMAIN_VERIFICATION) {
1213                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1214            }
1215            ivs.addFilter(filter);
1216            return true;
1217        }
1218
1219        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1220                int userId, int verificationId, String packageName) {
1221            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1222                    verifierUid, userId, packageName);
1223            ivs.setPendingState();
1224            synchronized (mPackages) {
1225                mIntentFilterVerificationStates.append(verificationId, ivs);
1226                mCurrentIntentFilterVerifications.add(verificationId);
1227            }
1228            return ivs;
1229        }
1230    }
1231
1232    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1233        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1234                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1235                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1236    }
1237
1238    // Set of pending broadcasts for aggregating enable/disable of components.
1239    static class PendingPackageBroadcasts {
1240        // for each user id, a map of <package name -> components within that package>
1241        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1242
1243        public PendingPackageBroadcasts() {
1244            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1245        }
1246
1247        public ArrayList<String> get(int userId, String packageName) {
1248            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1249            return packages.get(packageName);
1250        }
1251
1252        public void put(int userId, String packageName, ArrayList<String> components) {
1253            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1254            packages.put(packageName, components);
1255        }
1256
1257        public void remove(int userId, String packageName) {
1258            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1259            if (packages != null) {
1260                packages.remove(packageName);
1261            }
1262        }
1263
1264        public void remove(int userId) {
1265            mUidMap.remove(userId);
1266        }
1267
1268        public int userIdCount() {
1269            return mUidMap.size();
1270        }
1271
1272        public int userIdAt(int n) {
1273            return mUidMap.keyAt(n);
1274        }
1275
1276        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1277            return mUidMap.get(userId);
1278        }
1279
1280        public int size() {
1281            // total number of pending broadcast entries across all userIds
1282            int num = 0;
1283            for (int i = 0; i< mUidMap.size(); i++) {
1284                num += mUidMap.valueAt(i).size();
1285            }
1286            return num;
1287        }
1288
1289        public void clear() {
1290            mUidMap.clear();
1291        }
1292
1293        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1294            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1295            if (map == null) {
1296                map = new ArrayMap<String, ArrayList<String>>();
1297                mUidMap.put(userId, map);
1298            }
1299            return map;
1300        }
1301    }
1302    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1303
1304    // Service Connection to remote media container service to copy
1305    // package uri's from external media onto secure containers
1306    // or internal storage.
1307    private IMediaContainerService mContainerService = null;
1308
1309    static final int SEND_PENDING_BROADCAST = 1;
1310    static final int MCS_BOUND = 3;
1311    static final int END_COPY = 4;
1312    static final int INIT_COPY = 5;
1313    static final int MCS_UNBIND = 6;
1314    static final int START_CLEANING_PACKAGE = 7;
1315    static final int FIND_INSTALL_LOC = 8;
1316    static final int POST_INSTALL = 9;
1317    static final int MCS_RECONNECT = 10;
1318    static final int MCS_GIVE_UP = 11;
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 WRITE_SETTINGS: {
1718                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1719                    synchronized (mPackages) {
1720                        removeMessages(WRITE_SETTINGS);
1721                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1722                        mSettings.writeLPr();
1723                        mDirtyUsers.clear();
1724                    }
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1726                } break;
1727                case WRITE_PACKAGE_RESTRICTIONS: {
1728                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1729                    synchronized (mPackages) {
1730                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1731                        for (int userId : mDirtyUsers) {
1732                            mSettings.writePackageRestrictionsLPr(userId);
1733                        }
1734                        mDirtyUsers.clear();
1735                    }
1736                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1737                } break;
1738                case WRITE_PACKAGE_LIST: {
1739                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1740                    synchronized (mPackages) {
1741                        removeMessages(WRITE_PACKAGE_LIST);
1742                        mSettings.writePackageListLPr(msg.arg1);
1743                    }
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1745                } break;
1746                case CHECK_PENDING_VERIFICATION: {
1747                    final int verificationId = msg.arg1;
1748                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1749
1750                    if ((state != null) && !state.timeoutExtended()) {
1751                        final InstallArgs args = state.getInstallArgs();
1752                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1753
1754                        Slog.i(TAG, "Verification timed out for " + originUri);
1755                        mPendingVerification.remove(verificationId);
1756
1757                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1758
1759                        final UserHandle user = args.getUser();
1760                        if (getDefaultVerificationResponse(user)
1761                                == PackageManager.VERIFICATION_ALLOW) {
1762                            Slog.i(TAG, "Continuing with installation of " + originUri);
1763                            state.setVerifierResponse(Binder.getCallingUid(),
1764                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1765                            broadcastPackageVerified(verificationId, originUri,
1766                                    PackageManager.VERIFICATION_ALLOW, user);
1767                            try {
1768                                ret = args.copyApk(mContainerService, true);
1769                            } catch (RemoteException e) {
1770                                Slog.e(TAG, "Could not contact the ContainerService");
1771                            }
1772                        } else {
1773                            broadcastPackageVerified(verificationId, originUri,
1774                                    PackageManager.VERIFICATION_REJECT, user);
1775                        }
1776
1777                        Trace.asyncTraceEnd(
1778                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1779
1780                        processPendingInstall(args, ret);
1781                        mHandler.sendEmptyMessage(MCS_UNBIND);
1782                    }
1783                    break;
1784                }
1785                case PACKAGE_VERIFIED: {
1786                    final int verificationId = msg.arg1;
1787
1788                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1789                    if (state == null) {
1790                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1791                        break;
1792                    }
1793
1794                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1795
1796                    state.setVerifierResponse(response.callerUid, response.code);
1797
1798                    if (state.isVerificationComplete()) {
1799                        mPendingVerification.remove(verificationId);
1800
1801                        final InstallArgs args = state.getInstallArgs();
1802                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1803
1804                        int ret;
1805                        if (state.isInstallAllowed()) {
1806                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1807                            broadcastPackageVerified(verificationId, originUri,
1808                                    response.code, state.getInstallArgs().getUser());
1809                            try {
1810                                ret = args.copyApk(mContainerService, true);
1811                            } catch (RemoteException e) {
1812                                Slog.e(TAG, "Could not contact the ContainerService");
1813                            }
1814                        } else {
1815                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1816                        }
1817
1818                        Trace.asyncTraceEnd(
1819                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1820
1821                        processPendingInstall(args, ret);
1822                        mHandler.sendEmptyMessage(MCS_UNBIND);
1823                    }
1824
1825                    break;
1826                }
1827                case START_INTENT_FILTER_VERIFICATIONS: {
1828                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1829                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1830                            params.replacing, params.pkg);
1831                    break;
1832                }
1833                case INTENT_FILTER_VERIFIED: {
1834                    final int verificationId = msg.arg1;
1835
1836                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1837                            verificationId);
1838                    if (state == null) {
1839                        Slog.w(TAG, "Invalid IntentFilter verification token "
1840                                + verificationId + " received");
1841                        break;
1842                    }
1843
1844                    final int userId = state.getUserId();
1845
1846                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1847                            "Processing IntentFilter verification with token:"
1848                            + verificationId + " and userId:" + userId);
1849
1850                    final IntentFilterVerificationResponse response =
1851                            (IntentFilterVerificationResponse) msg.obj;
1852
1853                    state.setVerifierResponse(response.callerUid, response.code);
1854
1855                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1856                            "IntentFilter verification with token:" + verificationId
1857                            + " and userId:" + userId
1858                            + " is settings verifier response with response code:"
1859                            + response.code);
1860
1861                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1862                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1863                                + response.getFailedDomainsString());
1864                    }
1865
1866                    if (state.isVerificationComplete()) {
1867                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1868                    } else {
1869                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1870                                "IntentFilter verification with token:" + verificationId
1871                                + " was not said to be complete");
1872                    }
1873
1874                    break;
1875                }
1876                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1877                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1878                            mInstantAppResolverConnection,
1879                            (InstantAppRequest) msg.obj,
1880                            mInstantAppInstallerActivity,
1881                            mHandler);
1882                }
1883            }
1884        }
1885    }
1886
1887    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1888        @Override
1889        public void onGidsChanged(int appId, int userId) {
1890            mHandler.post(new Runnable() {
1891                @Override
1892                public void run() {
1893                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1894                }
1895            });
1896        }
1897        @Override
1898        public void onPermissionGranted(int uid, int userId) {
1899            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1900
1901            // Not critical; if this is lost, the application has to request again.
1902            synchronized (mPackages) {
1903                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1904            }
1905        }
1906        @Override
1907        public void onInstallPermissionGranted() {
1908            synchronized (mPackages) {
1909                scheduleWriteSettingsLocked();
1910            }
1911        }
1912        @Override
1913        public void onPermissionRevoked(int uid, int userId) {
1914            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1915
1916            synchronized (mPackages) {
1917                // Critical; after this call the application should never have the permission
1918                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1919            }
1920
1921            final int appId = UserHandle.getAppId(uid);
1922            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1923        }
1924        @Override
1925        public void onInstallPermissionRevoked() {
1926            synchronized (mPackages) {
1927                scheduleWriteSettingsLocked();
1928            }
1929        }
1930        @Override
1931        public void onPermissionUpdated(int userId) {
1932            synchronized (mPackages) {
1933                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1934            }
1935        }
1936        @Override
1937        public void onInstallPermissionUpdated() {
1938            synchronized (mPackages) {
1939                scheduleWriteSettingsLocked();
1940            }
1941        }
1942        @Override
1943        public void onPermissionRemoved() {
1944            synchronized (mPackages) {
1945                mSettings.writeLPr();
1946            }
1947        }
1948    };
1949
1950    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1951            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1952            boolean launchedForRestore, String installerPackage,
1953            IPackageInstallObserver2 installObserver) {
1954        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1955            // Send the removed broadcasts
1956            if (res.removedInfo != null) {
1957                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1958            }
1959
1960            // Now that we successfully installed the package, grant runtime
1961            // permissions if requested before broadcasting the install. Also
1962            // for legacy apps in permission review mode we clear the permission
1963            // review flag which is used to emulate runtime permissions for
1964            // legacy apps.
1965            if (grantPermissions) {
1966                final int callingUid = Binder.getCallingUid();
1967                mPermissionManager.grantRequestedRuntimePermissions(
1968                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1969                        mPermissionCallback);
1970            }
1971
1972            final boolean update = res.removedInfo != null
1973                    && res.removedInfo.removedPackage != null;
1974            final String installerPackageName =
1975                    res.installerPackageName != null
1976                            ? res.installerPackageName
1977                            : res.removedInfo != null
1978                                    ? res.removedInfo.installerPackageName
1979                                    : null;
1980
1981            // If this is the first time we have child packages for a disabled privileged
1982            // app that had no children, we grant requested runtime permissions to the new
1983            // children if the parent on the system image had them already granted.
1984            if (res.pkg.parentPackage != null) {
1985                final int callingUid = Binder.getCallingUid();
1986                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1987                        res.pkg, callingUid, mPermissionCallback);
1988            }
1989
1990            synchronized (mPackages) {
1991                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1992            }
1993
1994            final String packageName = res.pkg.applicationInfo.packageName;
1995
1996            // Determine the set of users who are adding this package for
1997            // the first time vs. those who are seeing an update.
1998            int[] firstUsers = EMPTY_INT_ARRAY;
1999            int[] updateUsers = EMPTY_INT_ARRAY;
2000            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2001            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2002            for (int newUser : res.newUsers) {
2003                if (ps.getInstantApp(newUser)) {
2004                    continue;
2005                }
2006                if (allNewUsers) {
2007                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2008                    continue;
2009                }
2010                boolean isNew = true;
2011                for (int origUser : res.origUsers) {
2012                    if (origUser == newUser) {
2013                        isNew = false;
2014                        break;
2015                    }
2016                }
2017                if (isNew) {
2018                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2019                } else {
2020                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
2021                }
2022            }
2023
2024            // Send installed broadcasts if the package is not a static shared lib.
2025            if (res.pkg.staticSharedLibName == null) {
2026                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2027
2028                // Send added for users that see the package for the first time
2029                // sendPackageAddedForNewUsers also deals with system apps
2030                int appId = UserHandle.getAppId(res.uid);
2031                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2032                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2033                        virtualPreload /*startReceiver*/, appId, firstUsers);
2034
2035                // Send added for users that don't see the package for the first time
2036                Bundle extras = new Bundle(1);
2037                extras.putInt(Intent.EXTRA_UID, res.uid);
2038                if (update) {
2039                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2040                }
2041                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2042                        extras, 0 /*flags*/,
2043                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2044                if (installerPackageName != null) {
2045                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2046                            extras, 0 /*flags*/,
2047                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2048                }
2049
2050                // Send replaced for users that don't see the package for the first time
2051                if (update) {
2052                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2053                            packageName, extras, 0 /*flags*/,
2054                            null /*targetPackage*/, null /*finishedReceiver*/,
2055                            updateUsers);
2056                    if (installerPackageName != null) {
2057                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2058                                extras, 0 /*flags*/,
2059                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2060                    }
2061                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2062                            null /*package*/, null /*extras*/, 0 /*flags*/,
2063                            packageName /*targetPackage*/,
2064                            null /*finishedReceiver*/, updateUsers);
2065                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2066                    // First-install and we did a restore, so we're responsible for the
2067                    // first-launch broadcast.
2068                    if (DEBUG_BACKUP) {
2069                        Slog.i(TAG, "Post-restore of " + packageName
2070                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2071                    }
2072                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2073                }
2074
2075                // Send broadcast package appeared if forward locked/external for all users
2076                // treat asec-hosted packages like removable media on upgrade
2077                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2078                    if (DEBUG_INSTALL) {
2079                        Slog.i(TAG, "upgrading pkg " + res.pkg
2080                                + " is ASEC-hosted -> AVAILABLE");
2081                    }
2082                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2083                    ArrayList<String> pkgList = new ArrayList<>(1);
2084                    pkgList.add(packageName);
2085                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2086                }
2087            }
2088
2089            // Work that needs to happen on first install within each user
2090            if (firstUsers != null && firstUsers.length > 0) {
2091                synchronized (mPackages) {
2092                    for (int userId : firstUsers) {
2093                        // If this app is a browser and it's newly-installed for some
2094                        // users, clear any default-browser state in those users. The
2095                        // app's nature doesn't depend on the user, so we can just check
2096                        // its browser nature in any user and generalize.
2097                        if (packageIsBrowser(packageName, userId)) {
2098                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2099                        }
2100
2101                        // We may also need to apply pending (restored) runtime
2102                        // permission grants within these users.
2103                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2104                    }
2105                }
2106            }
2107
2108            // Log current value of "unknown sources" setting
2109            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2110                    getUnknownSourcesSettings());
2111
2112            // Remove the replaced package's older resources safely now
2113            // We delete after a gc for applications  on sdcard.
2114            if (res.removedInfo != null && res.removedInfo.args != null) {
2115                Runtime.getRuntime().gc();
2116                synchronized (mInstallLock) {
2117                    res.removedInfo.args.doPostDeleteLI(true);
2118                }
2119            } else {
2120                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2121                // and not block here.
2122                VMRuntime.getRuntime().requestConcurrentGC();
2123            }
2124
2125            // Notify DexManager that the package was installed for new users.
2126            // The updated users should already be indexed and the package code paths
2127            // should not change.
2128            // Don't notify the manager for ephemeral apps as they are not expected to
2129            // survive long enough to benefit of background optimizations.
2130            for (int userId : firstUsers) {
2131                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2132                // There's a race currently where some install events may interleave with an uninstall.
2133                // This can lead to package info being null (b/36642664).
2134                if (info != null) {
2135                    mDexManager.notifyPackageInstalled(info, userId);
2136                }
2137            }
2138        }
2139
2140        // If someone is watching installs - notify them
2141        if (installObserver != null) {
2142            try {
2143                Bundle extras = extrasForInstallResult(res);
2144                installObserver.onPackageInstalled(res.name, res.returnCode,
2145                        res.returnMsg, extras);
2146            } catch (RemoteException e) {
2147                Slog.i(TAG, "Observer no longer exists.");
2148            }
2149        }
2150    }
2151
2152    private StorageEventListener mStorageListener = new StorageEventListener() {
2153        @Override
2154        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2155            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2156                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2157                    final String volumeUuid = vol.getFsUuid();
2158
2159                    // Clean up any users or apps that were removed or recreated
2160                    // while this volume was missing
2161                    sUserManager.reconcileUsers(volumeUuid);
2162                    reconcileApps(volumeUuid);
2163
2164                    // Clean up any install sessions that expired or were
2165                    // cancelled while this volume was missing
2166                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2167
2168                    loadPrivatePackages(vol);
2169
2170                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2171                    unloadPrivatePackages(vol);
2172                }
2173            }
2174        }
2175
2176        @Override
2177        public void onVolumeForgotten(String fsUuid) {
2178            if (TextUtils.isEmpty(fsUuid)) {
2179                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2180                return;
2181            }
2182
2183            // Remove any apps installed on the forgotten volume
2184            synchronized (mPackages) {
2185                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2186                for (PackageSetting ps : packages) {
2187                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2188                    deletePackageVersioned(new VersionedPackage(ps.name,
2189                            PackageManager.VERSION_CODE_HIGHEST),
2190                            new LegacyPackageDeleteObserver(null).getBinder(),
2191                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2192                    // Try very hard to release any references to this package
2193                    // so we don't risk the system server being killed due to
2194                    // open FDs
2195                    AttributeCache.instance().removePackage(ps.name);
2196                }
2197
2198                mSettings.onVolumeForgotten(fsUuid);
2199                mSettings.writeLPr();
2200            }
2201        }
2202    };
2203
2204    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2205        Bundle extras = null;
2206        switch (res.returnCode) {
2207            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2208                extras = new Bundle();
2209                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2210                        res.origPermission);
2211                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2212                        res.origPackage);
2213                break;
2214            }
2215            case PackageManager.INSTALL_SUCCEEDED: {
2216                extras = new Bundle();
2217                extras.putBoolean(Intent.EXTRA_REPLACING,
2218                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2219                break;
2220            }
2221        }
2222        return extras;
2223    }
2224
2225    void scheduleWriteSettingsLocked() {
2226        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2227            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2228        }
2229    }
2230
2231    void scheduleWritePackageListLocked(int userId) {
2232        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2233            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2234            msg.arg1 = userId;
2235            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2236        }
2237    }
2238
2239    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2240        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2241        scheduleWritePackageRestrictionsLocked(userId);
2242    }
2243
2244    void scheduleWritePackageRestrictionsLocked(int userId) {
2245        final int[] userIds = (userId == UserHandle.USER_ALL)
2246                ? sUserManager.getUserIds() : new int[]{userId};
2247        for (int nextUserId : userIds) {
2248            if (!sUserManager.exists(nextUserId)) return;
2249            mDirtyUsers.add(nextUserId);
2250            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2251                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2252            }
2253        }
2254    }
2255
2256    public static PackageManagerService main(Context context, Installer installer,
2257            boolean factoryTest, boolean onlyCore) {
2258        // Self-check for initial settings.
2259        PackageManagerServiceCompilerMapping.checkProperties();
2260
2261        PackageManagerService m = new PackageManagerService(context, installer,
2262                factoryTest, onlyCore);
2263        m.enableSystemUserPackages();
2264        ServiceManager.addService("package", m);
2265        final PackageManagerNative pmn = m.new PackageManagerNative();
2266        ServiceManager.addService("package_native", pmn);
2267        return m;
2268    }
2269
2270    private void enableSystemUserPackages() {
2271        if (!UserManager.isSplitSystemUser()) {
2272            return;
2273        }
2274        // For system user, enable apps based on the following conditions:
2275        // - app is whitelisted or belong to one of these groups:
2276        //   -- system app which has no launcher icons
2277        //   -- system app which has INTERACT_ACROSS_USERS permission
2278        //   -- system IME app
2279        // - app is not in the blacklist
2280        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2281        Set<String> enableApps = new ArraySet<>();
2282        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2283                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2284                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2285        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2286        enableApps.addAll(wlApps);
2287        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2288                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2289        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2290        enableApps.removeAll(blApps);
2291        Log.i(TAG, "Applications installed for system user: " + enableApps);
2292        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2293                UserHandle.SYSTEM);
2294        final int allAppsSize = allAps.size();
2295        synchronized (mPackages) {
2296            for (int i = 0; i < allAppsSize; i++) {
2297                String pName = allAps.get(i);
2298                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2299                // Should not happen, but we shouldn't be failing if it does
2300                if (pkgSetting == null) {
2301                    continue;
2302                }
2303                boolean install = enableApps.contains(pName);
2304                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2305                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2306                            + " for system user");
2307                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2308                }
2309            }
2310            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2311        }
2312    }
2313
2314    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2315        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2316                Context.DISPLAY_SERVICE);
2317        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2318    }
2319
2320    /**
2321     * Requests that files preopted on a secondary system partition be copied to the data partition
2322     * if possible.  Note that the actual copying of the files is accomplished by init for security
2323     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2324     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2325     */
2326    private static void requestCopyPreoptedFiles() {
2327        final int WAIT_TIME_MS = 100;
2328        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2329        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2330            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2331            // We will wait for up to 100 seconds.
2332            final long timeStart = SystemClock.uptimeMillis();
2333            final long timeEnd = timeStart + 100 * 1000;
2334            long timeNow = timeStart;
2335            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2336                try {
2337                    Thread.sleep(WAIT_TIME_MS);
2338                } catch (InterruptedException e) {
2339                    // Do nothing
2340                }
2341                timeNow = SystemClock.uptimeMillis();
2342                if (timeNow > timeEnd) {
2343                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2344                    Slog.wtf(TAG, "cppreopt did not finish!");
2345                    break;
2346                }
2347            }
2348
2349            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2350        }
2351    }
2352
2353    public PackageManagerService(Context context, Installer installer,
2354            boolean factoryTest, boolean onlyCore) {
2355        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2356        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2357        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2358                SystemClock.uptimeMillis());
2359
2360        if (mSdkVersion <= 0) {
2361            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2362        }
2363
2364        mContext = context;
2365
2366        mPermissionReviewRequired = context.getResources().getBoolean(
2367                R.bool.config_permissionReviewRequired);
2368
2369        mFactoryTest = factoryTest;
2370        mOnlyCore = onlyCore;
2371        mMetrics = new DisplayMetrics();
2372        mInstaller = installer;
2373
2374        // Create sub-components that provide services / data. Order here is important.
2375        synchronized (mInstallLock) {
2376        synchronized (mPackages) {
2377            // Expose private service for system components to use.
2378            LocalServices.addService(
2379                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2380            sUserManager = new UserManagerService(context, this,
2381                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2382            mPermissionManager = PermissionManagerService.create(context,
2383                    new DefaultPermissionGrantedCallback() {
2384                        @Override
2385                        public void onDefaultRuntimePermissionsGranted(int userId) {
2386                            synchronized(mPackages) {
2387                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2388                            }
2389                        }
2390                    }, mPackages /*externalLock*/);
2391            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2392            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2393        }
2394        }
2395        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2396                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2397        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2398                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407
2408        String separateProcesses = SystemProperties.get("debug.separate_processes");
2409        if (separateProcesses != null && separateProcesses.length() > 0) {
2410            if ("*".equals(separateProcesses)) {
2411                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2412                mSeparateProcesses = null;
2413                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2414            } else {
2415                mDefParseFlags = 0;
2416                mSeparateProcesses = separateProcesses.split(",");
2417                Slog.w(TAG, "Running with debug.separate_processes: "
2418                        + separateProcesses);
2419            }
2420        } else {
2421            mDefParseFlags = 0;
2422            mSeparateProcesses = null;
2423        }
2424
2425        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2426                "*dexopt*");
2427        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2428        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2429
2430        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2431                FgThread.get().getLooper());
2432
2433        getDefaultDisplayMetrics(context, mMetrics);
2434
2435        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2436        SystemConfig systemConfig = SystemConfig.getInstance();
2437        mGlobalGids = systemConfig.getGlobalGids();
2438        mSystemPermissions = systemConfig.getSystemPermissions();
2439        mAvailableFeatures = systemConfig.getAvailableFeatures();
2440        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2441
2442        mProtectedPackages = new ProtectedPackages(mContext);
2443
2444        synchronized (mInstallLock) {
2445        // writer
2446        synchronized (mPackages) {
2447            mHandlerThread = new ServiceThread(TAG,
2448                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2449            mHandlerThread.start();
2450            mHandler = new PackageHandler(mHandlerThread.getLooper());
2451            mProcessLoggingHandler = new ProcessLoggingHandler();
2452            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2453            mInstantAppRegistry = new InstantAppRegistry(this);
2454
2455            File dataDir = Environment.getDataDirectory();
2456            mAppInstallDir = new File(dataDir, "app");
2457            mAppLib32InstallDir = new File(dataDir, "app-lib");
2458            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2459
2460            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2461            final int builtInLibCount = libConfig.size();
2462            for (int i = 0; i < builtInLibCount; i++) {
2463                String name = libConfig.keyAt(i);
2464                String path = libConfig.valueAt(i);
2465                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2466                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2467            }
2468
2469            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2470
2471            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2472            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2473            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2474
2475            // Clean up orphaned packages for which the code path doesn't exist
2476            // and they are an update to a system app - caused by bug/32321269
2477            final int packageSettingCount = mSettings.mPackages.size();
2478            for (int i = packageSettingCount - 1; i >= 0; i--) {
2479                PackageSetting ps = mSettings.mPackages.valueAt(i);
2480                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2481                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2482                    mSettings.mPackages.removeAt(i);
2483                    mSettings.enableSystemPackageLPw(ps.name);
2484                }
2485            }
2486
2487            if (mFirstBoot) {
2488                requestCopyPreoptedFiles();
2489            }
2490
2491            String customResolverActivity = Resources.getSystem().getString(
2492                    R.string.config_customResolverActivity);
2493            if (TextUtils.isEmpty(customResolverActivity)) {
2494                customResolverActivity = null;
2495            } else {
2496                mCustomResolverComponentName = ComponentName.unflattenFromString(
2497                        customResolverActivity);
2498            }
2499
2500            long startTime = SystemClock.uptimeMillis();
2501
2502            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2503                    startTime);
2504
2505            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2506            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2507
2508            if (bootClassPath == null) {
2509                Slog.w(TAG, "No BOOTCLASSPATH found!");
2510            }
2511
2512            if (systemServerClassPath == null) {
2513                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2514            }
2515
2516            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2517
2518            final VersionInfo ver = mSettings.getInternalVersion();
2519            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2520            if (mIsUpgrade) {
2521                logCriticalInfo(Log.INFO,
2522                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2523            }
2524
2525            // when upgrading from pre-M, promote system app permissions from install to runtime
2526            mPromoteSystemApps =
2527                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2528
2529            // When upgrading from pre-N, we need to handle package extraction like first boot,
2530            // as there is no profiling data available.
2531            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2532
2533            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2534
2535            // save off the names of pre-existing system packages prior to scanning; we don't
2536            // want to automatically grant runtime permissions for new system apps
2537            if (mPromoteSystemApps) {
2538                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2539                while (pkgSettingIter.hasNext()) {
2540                    PackageSetting ps = pkgSettingIter.next();
2541                    if (isSystemApp(ps)) {
2542                        mExistingSystemPackages.add(ps.name);
2543                    }
2544                }
2545            }
2546
2547            mCacheDir = preparePackageParserCache(mIsUpgrade);
2548
2549            // Set flag to monitor and not change apk file paths when
2550            // scanning install directories.
2551            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2552
2553            if (mIsUpgrade || mFirstBoot) {
2554                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2555            }
2556
2557            // Collect vendor overlay packages. (Do this before scanning any apps.)
2558            // For security and version matching reason, only consider
2559            // overlay packages if they reside in the right directory.
2560            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2561                    | PackageParser.PARSE_IS_SYSTEM
2562                    | PackageParser.PARSE_IS_SYSTEM_DIR
2563                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2564
2565            mParallelPackageParserCallback.findStaticOverlayPackages();
2566
2567            // Find base frameworks (resource packages without code).
2568            scanDirTracedLI(frameworkDir, mDefParseFlags
2569                    | PackageParser.PARSE_IS_SYSTEM
2570                    | PackageParser.PARSE_IS_SYSTEM_DIR
2571                    | PackageParser.PARSE_IS_PRIVILEGED,
2572                    scanFlags | SCAN_NO_DEX, 0);
2573
2574            // Collected privileged system packages.
2575            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2576            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2577                    | PackageParser.PARSE_IS_SYSTEM
2578                    | PackageParser.PARSE_IS_SYSTEM_DIR
2579                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2580
2581            // Collect ordinary system packages.
2582            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2583            scanDirTracedLI(systemAppDir, mDefParseFlags
2584                    | PackageParser.PARSE_IS_SYSTEM
2585                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2586
2587            // Collect all vendor packages.
2588            File vendorAppDir = new File("/vendor/app");
2589            try {
2590                vendorAppDir = vendorAppDir.getCanonicalFile();
2591            } catch (IOException e) {
2592                // failed to look up canonical path, continue with original one
2593            }
2594            scanDirTracedLI(vendorAppDir, mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2597
2598            // Collect all OEM packages.
2599            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2600            scanDirTracedLI(oemAppDir, mDefParseFlags
2601                    | PackageParser.PARSE_IS_SYSTEM
2602                    | PackageParser.PARSE_IS_SYSTEM_DIR
2603                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2604
2605            // Prune any system packages that no longer exist.
2606            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2607            // Stub packages must either be replaced with full versions in the /data
2608            // partition or be disabled.
2609            final List<String> stubSystemApps = new ArrayList<>();
2610            if (!mOnlyCore) {
2611                // do this first before mucking with mPackages for the "expecting better" case
2612                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2613                while (pkgIterator.hasNext()) {
2614                    final PackageParser.Package pkg = pkgIterator.next();
2615                    if (pkg.isStub) {
2616                        stubSystemApps.add(pkg.packageName);
2617                    }
2618                }
2619
2620                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2621                while (psit.hasNext()) {
2622                    PackageSetting ps = psit.next();
2623
2624                    /*
2625                     * If this is not a system app, it can't be a
2626                     * disable system app.
2627                     */
2628                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2629                        continue;
2630                    }
2631
2632                    /*
2633                     * If the package is scanned, it's not erased.
2634                     */
2635                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2636                    if (scannedPkg != null) {
2637                        /*
2638                         * If the system app is both scanned and in the
2639                         * disabled packages list, then it must have been
2640                         * added via OTA. Remove it from the currently
2641                         * scanned package so the previously user-installed
2642                         * application can be scanned.
2643                         */
2644                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2645                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2646                                    + ps.name + "; removing system app.  Last known codePath="
2647                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2648                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2649                                    + scannedPkg.mVersionCode);
2650                            removePackageLI(scannedPkg, true);
2651                            mExpectingBetter.put(ps.name, ps.codePath);
2652                        }
2653
2654                        continue;
2655                    }
2656
2657                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2658                        psit.remove();
2659                        logCriticalInfo(Log.WARN, "System package " + ps.name
2660                                + " no longer exists; it's data will be wiped");
2661                        // Actual deletion of code and data will be handled by later
2662                        // reconciliation step
2663                    } else {
2664                        // we still have a disabled system package, but, it still might have
2665                        // been removed. check the code path still exists and check there's
2666                        // still a package. the latter can happen if an OTA keeps the same
2667                        // code path, but, changes the package name.
2668                        final PackageSetting disabledPs =
2669                                mSettings.getDisabledSystemPkgLPr(ps.name);
2670                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2671                                || disabledPs.pkg == null) {
2672                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2673                        }
2674                    }
2675                }
2676            }
2677
2678            //look for any incomplete package installations
2679            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2680            for (int i = 0; i < deletePkgsList.size(); i++) {
2681                // Actual deletion of code and data will be handled by later
2682                // reconciliation step
2683                final String packageName = deletePkgsList.get(i).name;
2684                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2685                synchronized (mPackages) {
2686                    mSettings.removePackageLPw(packageName);
2687                }
2688            }
2689
2690            //delete tmp files
2691            deleteTempPackageFiles();
2692
2693            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2694
2695            // Remove any shared userIDs that have no associated packages
2696            mSettings.pruneSharedUsersLPw();
2697            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2698            final int systemPackagesCount = mPackages.size();
2699            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2700                    + " ms, packageCount: " + systemPackagesCount
2701                    + " , timePerPackage: "
2702                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2703                    + " , cached: " + cachedSystemApps);
2704            if (mIsUpgrade && systemPackagesCount > 0) {
2705                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2706                        ((int) systemScanTime) / systemPackagesCount);
2707            }
2708            if (!mOnlyCore) {
2709                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2710                        SystemClock.uptimeMillis());
2711                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2712
2713                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2714                        | PackageParser.PARSE_FORWARD_LOCK,
2715                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2716
2717                // Remove disable package settings for updated system apps that were
2718                // removed via an OTA. If the update is no longer present, remove the
2719                // app completely. Otherwise, revoke their system privileges.
2720                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2721                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2722                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2723
2724                    final String msg;
2725                    if (deletedPkg == null) {
2726                        // should have found an update, but, we didn't; remove everything
2727                        msg = "Updated system package " + deletedAppName
2728                                + " no longer exists; removing its data";
2729                        // Actual deletion of code and data will be handled by later
2730                        // reconciliation step
2731                    } else {
2732                        // found an update; revoke system privileges
2733                        msg = "Updated system package + " + deletedAppName
2734                                + " no longer exists; revoking system privileges";
2735
2736                        // Don't do anything if a stub is removed from the system image. If
2737                        // we were to remove the uncompressed version from the /data partition,
2738                        // this is where it'd be done.
2739
2740                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2741                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2742                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2743                    }
2744                    logCriticalInfo(Log.WARN, msg);
2745                }
2746
2747                /*
2748                 * Make sure all system apps that we expected to appear on
2749                 * the userdata partition actually showed up. If they never
2750                 * appeared, crawl back and revive the system version.
2751                 */
2752                for (int i = 0; i < mExpectingBetter.size(); i++) {
2753                    final String packageName = mExpectingBetter.keyAt(i);
2754                    if (!mPackages.containsKey(packageName)) {
2755                        final File scanFile = mExpectingBetter.valueAt(i);
2756
2757                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2758                                + " but never showed up; reverting to system");
2759
2760                        int reparseFlags = mDefParseFlags;
2761                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2762                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2763                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2764                                    | PackageParser.PARSE_IS_PRIVILEGED;
2765                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2766                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2767                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2768                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2769                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2770                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2771                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2772                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2773                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2774                                    | PackageParser.PARSE_IS_OEM;
2775                        } else {
2776                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2777                            continue;
2778                        }
2779
2780                        mSettings.enableSystemPackageLPw(packageName);
2781
2782                        try {
2783                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2784                        } catch (PackageManagerException e) {
2785                            Slog.e(TAG, "Failed to parse original system package: "
2786                                    + e.getMessage());
2787                        }
2788                    }
2789                }
2790
2791                // Uncompress and install any stubbed system applications.
2792                // This must be done last to ensure all stubs are replaced or disabled.
2793                decompressSystemApplications(stubSystemApps, scanFlags);
2794
2795                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2796                                - cachedSystemApps;
2797
2798                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2799                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2800                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2801                        + " ms, packageCount: " + dataPackagesCount
2802                        + " , timePerPackage: "
2803                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2804                        + " , cached: " + cachedNonSystemApps);
2805                if (mIsUpgrade && dataPackagesCount > 0) {
2806                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2807                            ((int) dataScanTime) / dataPackagesCount);
2808                }
2809            }
2810            mExpectingBetter.clear();
2811
2812            // Resolve the storage manager.
2813            mStorageManagerPackage = getStorageManagerPackageName();
2814
2815            // Resolve protected action filters. Only the setup wizard is allowed to
2816            // have a high priority filter for these actions.
2817            mSetupWizardPackage = getSetupWizardPackageName();
2818            if (mProtectedFilters.size() > 0) {
2819                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2820                    Slog.i(TAG, "No setup wizard;"
2821                        + " All protected intents capped to priority 0");
2822                }
2823                for (ActivityIntentInfo filter : mProtectedFilters) {
2824                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2825                        if (DEBUG_FILTERS) {
2826                            Slog.i(TAG, "Found setup wizard;"
2827                                + " allow priority " + filter.getPriority() + ";"
2828                                + " package: " + filter.activity.info.packageName
2829                                + " activity: " + filter.activity.className
2830                                + " priority: " + filter.getPriority());
2831                        }
2832                        // skip setup wizard; allow it to keep the high priority filter
2833                        continue;
2834                    }
2835                    if (DEBUG_FILTERS) {
2836                        Slog.i(TAG, "Protected action; cap priority to 0;"
2837                                + " package: " + filter.activity.info.packageName
2838                                + " activity: " + filter.activity.className
2839                                + " origPrio: " + filter.getPriority());
2840                    }
2841                    filter.setPriority(0);
2842                }
2843            }
2844            mDeferProtectedFilters = false;
2845            mProtectedFilters.clear();
2846
2847            // Now that we know all of the shared libraries, update all clients to have
2848            // the correct library paths.
2849            updateAllSharedLibrariesLPw(null);
2850
2851            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2852                // NOTE: We ignore potential failures here during a system scan (like
2853                // the rest of the commands above) because there's precious little we
2854                // can do about it. A settings error is reported, though.
2855                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2856            }
2857
2858            // Now that we know all the packages we are keeping,
2859            // read and update their last usage times.
2860            mPackageUsage.read(mPackages);
2861            mCompilerStats.read();
2862
2863            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2864                    SystemClock.uptimeMillis());
2865            Slog.i(TAG, "Time to scan packages: "
2866                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2867                    + " seconds");
2868
2869            // If the platform SDK has changed since the last time we booted,
2870            // we need to re-grant app permission to catch any new ones that
2871            // appear.  This is really a hack, and means that apps can in some
2872            // cases get permissions that the user didn't initially explicitly
2873            // allow...  it would be nice to have some better way to handle
2874            // this situation.
2875            int updateFlags = UPDATE_PERMISSIONS_ALL;
2876            if (ver.sdkVersion != mSdkVersion) {
2877                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2878                        + mSdkVersion + "; regranting permissions for internal storage");
2879                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2880            }
2881            updatePermissionsLocked(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2882            ver.sdkVersion = mSdkVersion;
2883
2884            // If this is the first boot or an update from pre-M, and it is a normal
2885            // boot, then we need to initialize the default preferred apps across
2886            // all defined users.
2887            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2888                for (UserInfo user : sUserManager.getUsers(true)) {
2889                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2890                    applyFactoryDefaultBrowserLPw(user.id);
2891                    primeDomainVerificationsLPw(user.id);
2892                }
2893            }
2894
2895            // Prepare storage for system user really early during boot,
2896            // since core system apps like SettingsProvider and SystemUI
2897            // can't wait for user to start
2898            final int storageFlags;
2899            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2900                storageFlags = StorageManager.FLAG_STORAGE_DE;
2901            } else {
2902                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2903            }
2904            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2905                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2906                    true /* onlyCoreApps */);
2907            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2908                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2909                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2910                traceLog.traceBegin("AppDataFixup");
2911                try {
2912                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2913                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2914                } catch (InstallerException e) {
2915                    Slog.w(TAG, "Trouble fixing GIDs", e);
2916                }
2917                traceLog.traceEnd();
2918
2919                traceLog.traceBegin("AppDataPrepare");
2920                if (deferPackages == null || deferPackages.isEmpty()) {
2921                    return;
2922                }
2923                int count = 0;
2924                for (String pkgName : deferPackages) {
2925                    PackageParser.Package pkg = null;
2926                    synchronized (mPackages) {
2927                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2928                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2929                            pkg = ps.pkg;
2930                        }
2931                    }
2932                    if (pkg != null) {
2933                        synchronized (mInstallLock) {
2934                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2935                                    true /* maybeMigrateAppData */);
2936                        }
2937                        count++;
2938                    }
2939                }
2940                traceLog.traceEnd();
2941                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2942            }, "prepareAppData");
2943
2944            // If this is first boot after an OTA, and a normal boot, then
2945            // we need to clear code cache directories.
2946            // Note that we do *not* clear the application profiles. These remain valid
2947            // across OTAs and are used to drive profile verification (post OTA) and
2948            // profile compilation (without waiting to collect a fresh set of profiles).
2949            if (mIsUpgrade && !onlyCore) {
2950                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2951                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2952                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2953                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2954                        // No apps are running this early, so no need to freeze
2955                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2956                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2957                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2958                    }
2959                }
2960                ver.fingerprint = Build.FINGERPRINT;
2961            }
2962
2963            checkDefaultBrowser();
2964
2965            // clear only after permissions and other defaults have been updated
2966            mExistingSystemPackages.clear();
2967            mPromoteSystemApps = false;
2968
2969            // All the changes are done during package scanning.
2970            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2971
2972            // can downgrade to reader
2973            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2974            mSettings.writeLPr();
2975            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2976            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2977                    SystemClock.uptimeMillis());
2978
2979            if (!mOnlyCore) {
2980                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2981                mRequiredInstallerPackage = getRequiredInstallerLPr();
2982                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2983                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2984                if (mIntentFilterVerifierComponent != null) {
2985                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2986                            mIntentFilterVerifierComponent);
2987                } else {
2988                    mIntentFilterVerifier = null;
2989                }
2990                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2991                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2992                        SharedLibraryInfo.VERSION_UNDEFINED);
2993                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2994                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2995                        SharedLibraryInfo.VERSION_UNDEFINED);
2996            } else {
2997                mRequiredVerifierPackage = null;
2998                mRequiredInstallerPackage = null;
2999                mRequiredUninstallerPackage = null;
3000                mIntentFilterVerifierComponent = null;
3001                mIntentFilterVerifier = null;
3002                mServicesSystemSharedLibraryPackageName = null;
3003                mSharedSystemSharedLibraryPackageName = null;
3004            }
3005
3006            mInstallerService = new PackageInstallerService(context, this);
3007            final Pair<ComponentName, String> instantAppResolverComponent =
3008                    getInstantAppResolverLPr();
3009            if (instantAppResolverComponent != null) {
3010                if (DEBUG_EPHEMERAL) {
3011                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3012                }
3013                mInstantAppResolverConnection = new EphemeralResolverConnection(
3014                        mContext, instantAppResolverComponent.first,
3015                        instantAppResolverComponent.second);
3016                mInstantAppResolverSettingsComponent =
3017                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3018            } else {
3019                mInstantAppResolverConnection = null;
3020                mInstantAppResolverSettingsComponent = null;
3021            }
3022            updateInstantAppInstallerLocked(null);
3023
3024            // Read and update the usage of dex files.
3025            // Do this at the end of PM init so that all the packages have their
3026            // data directory reconciled.
3027            // At this point we know the code paths of the packages, so we can validate
3028            // the disk file and build the internal cache.
3029            // The usage file is expected to be small so loading and verifying it
3030            // should take a fairly small time compare to the other activities (e.g. package
3031            // scanning).
3032            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3033            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3034            for (int userId : currentUserIds) {
3035                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3036            }
3037            mDexManager.load(userPackages);
3038            if (mIsUpgrade) {
3039                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3040                        (int) (SystemClock.uptimeMillis() - startTime));
3041            }
3042        } // synchronized (mPackages)
3043        } // synchronized (mInstallLock)
3044
3045        // Now after opening every single application zip, make sure they
3046        // are all flushed.  Not really needed, but keeps things nice and
3047        // tidy.
3048        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3049        Runtime.getRuntime().gc();
3050        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3051
3052        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3053        FallbackCategoryProvider.loadFallbacks();
3054        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3055
3056        // The initial scanning above does many calls into installd while
3057        // holding the mPackages lock, but we're mostly interested in yelling
3058        // once we have a booted system.
3059        mInstaller.setWarnIfHeld(mPackages);
3060
3061        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3062    }
3063
3064    /**
3065     * Uncompress and install stub applications.
3066     * <p>In order to save space on the system partition, some applications are shipped in a
3067     * compressed form. In addition the compressed bits for the full application, the
3068     * system image contains a tiny stub comprised of only the Android manifest.
3069     * <p>During the first boot, attempt to uncompress and install the full application. If
3070     * the application can't be installed for any reason, disable the stub and prevent
3071     * uncompressing the full application during future boots.
3072     * <p>In order to forcefully attempt an installation of a full application, go to app
3073     * settings and enable the application.
3074     */
3075    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3076        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3077            final String pkgName = stubSystemApps.get(i);
3078            // skip if the system package is already disabled
3079            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3080                stubSystemApps.remove(i);
3081                continue;
3082            }
3083            // skip if the package isn't installed (?!); this should never happen
3084            final PackageParser.Package pkg = mPackages.get(pkgName);
3085            if (pkg == null) {
3086                stubSystemApps.remove(i);
3087                continue;
3088            }
3089            // skip if the package has been disabled by the user
3090            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3091            if (ps != null) {
3092                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3093                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3094                    stubSystemApps.remove(i);
3095                    continue;
3096                }
3097            }
3098
3099            if (DEBUG_COMPRESSION) {
3100                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3101            }
3102
3103            // uncompress the binary to its eventual destination on /data
3104            final File scanFile = decompressPackage(pkg);
3105            if (scanFile == null) {
3106                continue;
3107            }
3108
3109            // install the package to replace the stub on /system
3110            try {
3111                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3112                removePackageLI(pkg, true /*chatty*/);
3113                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3114                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3115                        UserHandle.USER_SYSTEM, "android");
3116                stubSystemApps.remove(i);
3117                continue;
3118            } catch (PackageManagerException e) {
3119                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3120            }
3121
3122            // any failed attempt to install the package will be cleaned up later
3123        }
3124
3125        // disable any stub still left; these failed to install the full application
3126        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3127            final String pkgName = stubSystemApps.get(i);
3128            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3129            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3130                    UserHandle.USER_SYSTEM, "android");
3131            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3132        }
3133    }
3134
3135    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3136        if (DEBUG_COMPRESSION) {
3137            Slog.i(TAG, "Decompress file"
3138                    + "; src: " + srcFile.getAbsolutePath()
3139                    + ", dst: " + dstFile.getAbsolutePath());
3140        }
3141        try (
3142                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3143                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3144        ) {
3145            Streams.copy(fileIn, fileOut);
3146            Os.chmod(dstFile.getAbsolutePath(), 0644);
3147            return PackageManager.INSTALL_SUCCEEDED;
3148        } catch (IOException e) {
3149            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3150                    + "; src: " + srcFile.getAbsolutePath()
3151                    + ", dst: " + dstFile.getAbsolutePath());
3152        }
3153        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3154    }
3155
3156    private File[] getCompressedFiles(String codePath) {
3157        final File stubCodePath = new File(codePath);
3158        final String stubName = stubCodePath.getName();
3159
3160        // The layout of a compressed package on a given partition is as follows :
3161        //
3162        // Compressed artifacts:
3163        //
3164        // /partition/ModuleName/foo.gz
3165        // /partation/ModuleName/bar.gz
3166        //
3167        // Stub artifact:
3168        //
3169        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3170        //
3171        // In other words, stub is on the same partition as the compressed artifacts
3172        // and in a directory that's suffixed with "-Stub".
3173        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3174        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3175            return null;
3176        }
3177
3178        final File stubParentDir = stubCodePath.getParentFile();
3179        if (stubParentDir == null) {
3180            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3181            return null;
3182        }
3183
3184        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3185        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3186            @Override
3187            public boolean accept(File dir, String name) {
3188                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3189            }
3190        });
3191
3192        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3193            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3194        }
3195
3196        return files;
3197    }
3198
3199    private boolean compressedFileExists(String codePath) {
3200        final File[] compressedFiles = getCompressedFiles(codePath);
3201        return compressedFiles != null && compressedFiles.length > 0;
3202    }
3203
3204    /**
3205     * Decompresses the given package on the system image onto
3206     * the /data partition.
3207     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3208     */
3209    private File decompressPackage(PackageParser.Package pkg) {
3210        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3211        if (compressedFiles == null || compressedFiles.length == 0) {
3212            if (DEBUG_COMPRESSION) {
3213                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3214            }
3215            return null;
3216        }
3217        final File dstCodePath =
3218                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3219        int ret = PackageManager.INSTALL_SUCCEEDED;
3220        try {
3221            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3222            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3223            for (File srcFile : compressedFiles) {
3224                final String srcFileName = srcFile.getName();
3225                final String dstFileName = srcFileName.substring(
3226                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3227                final File dstFile = new File(dstCodePath, dstFileName);
3228                ret = decompressFile(srcFile, dstFile);
3229                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3230                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3231                            + "; pkg: " + pkg.packageName
3232                            + ", file: " + dstFileName);
3233                    break;
3234                }
3235            }
3236        } catch (ErrnoException e) {
3237            logCriticalInfo(Log.ERROR, "Failed to decompress"
3238                    + "; pkg: " + pkg.packageName
3239                    + ", err: " + e.errno);
3240        }
3241        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3242            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3243            NativeLibraryHelper.Handle handle = null;
3244            try {
3245                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3246                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3247                        null /*abiOverride*/);
3248            } catch (IOException e) {
3249                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3250                        + "; pkg: " + pkg.packageName);
3251                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3252            } finally {
3253                IoUtils.closeQuietly(handle);
3254            }
3255        }
3256        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3257            if (dstCodePath == null || !dstCodePath.exists()) {
3258                return null;
3259            }
3260            removeCodePathLI(dstCodePath);
3261            return null;
3262        }
3263
3264        return dstCodePath;
3265    }
3266
3267    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3268        // we're only interested in updating the installer appliction when 1) it's not
3269        // already set or 2) the modified package is the installer
3270        if (mInstantAppInstallerActivity != null
3271                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3272                        .equals(modifiedPackage)) {
3273            return;
3274        }
3275        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3276    }
3277
3278    private static File preparePackageParserCache(boolean isUpgrade) {
3279        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3280            return null;
3281        }
3282
3283        // Disable package parsing on eng builds to allow for faster incremental development.
3284        if (Build.IS_ENG) {
3285            return null;
3286        }
3287
3288        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3289            Slog.i(TAG, "Disabling package parser cache due to system property.");
3290            return null;
3291        }
3292
3293        // The base directory for the package parser cache lives under /data/system/.
3294        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3295                "package_cache");
3296        if (cacheBaseDir == null) {
3297            return null;
3298        }
3299
3300        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3301        // This also serves to "GC" unused entries when the package cache version changes (which
3302        // can only happen during upgrades).
3303        if (isUpgrade) {
3304            FileUtils.deleteContents(cacheBaseDir);
3305        }
3306
3307
3308        // Return the versioned package cache directory. This is something like
3309        // "/data/system/package_cache/1"
3310        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3311
3312        // The following is a workaround to aid development on non-numbered userdebug
3313        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3314        // the system partition is newer.
3315        //
3316        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3317        // that starts with "eng." to signify that this is an engineering build and not
3318        // destined for release.
3319        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3320            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3321
3322            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3323            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3324            // in general and should not be used for production changes. In this specific case,
3325            // we know that they will work.
3326            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3327            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3328                FileUtils.deleteContents(cacheBaseDir);
3329                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3330            }
3331        }
3332
3333        return cacheDir;
3334    }
3335
3336    @Override
3337    public boolean isFirstBoot() {
3338        // allow instant applications
3339        return mFirstBoot;
3340    }
3341
3342    @Override
3343    public boolean isOnlyCoreApps() {
3344        // allow instant applications
3345        return mOnlyCore;
3346    }
3347
3348    @Override
3349    public boolean isUpgrade() {
3350        // allow instant applications
3351        // The system property allows testing ota flow when upgraded to the same image.
3352        return mIsUpgrade || SystemProperties.getBoolean(
3353                "persist.pm.mock-upgrade", false /* default */);
3354    }
3355
3356    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3357        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3358
3359        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3360                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3361                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3362        if (matches.size() == 1) {
3363            return matches.get(0).getComponentInfo().packageName;
3364        } else if (matches.size() == 0) {
3365            Log.e(TAG, "There should probably be a verifier, but, none were found");
3366            return null;
3367        }
3368        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3369    }
3370
3371    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3372        synchronized (mPackages) {
3373            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3374            if (libraryEntry == null) {
3375                throw new IllegalStateException("Missing required shared library:" + name);
3376            }
3377            return libraryEntry.apk;
3378        }
3379    }
3380
3381    private @NonNull String getRequiredInstallerLPr() {
3382        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3383        intent.addCategory(Intent.CATEGORY_DEFAULT);
3384        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3385
3386        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3387                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3388                UserHandle.USER_SYSTEM);
3389        if (matches.size() == 1) {
3390            ResolveInfo resolveInfo = matches.get(0);
3391            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3392                throw new RuntimeException("The installer must be a privileged app");
3393            }
3394            return matches.get(0).getComponentInfo().packageName;
3395        } else {
3396            throw new RuntimeException("There must be exactly one installer; found " + matches);
3397        }
3398    }
3399
3400    private @NonNull String getRequiredUninstallerLPr() {
3401        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3402        intent.addCategory(Intent.CATEGORY_DEFAULT);
3403        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3404
3405        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3406                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3407                UserHandle.USER_SYSTEM);
3408        if (resolveInfo == null ||
3409                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3410            throw new RuntimeException("There must be exactly one uninstaller; found "
3411                    + resolveInfo);
3412        }
3413        return resolveInfo.getComponentInfo().packageName;
3414    }
3415
3416    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3417        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3418
3419        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3420                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3421                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3422        ResolveInfo best = null;
3423        final int N = matches.size();
3424        for (int i = 0; i < N; i++) {
3425            final ResolveInfo cur = matches.get(i);
3426            final String packageName = cur.getComponentInfo().packageName;
3427            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3428                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3429                continue;
3430            }
3431
3432            if (best == null || cur.priority > best.priority) {
3433                best = cur;
3434            }
3435        }
3436
3437        if (best != null) {
3438            return best.getComponentInfo().getComponentName();
3439        }
3440        Slog.w(TAG, "Intent filter verifier not found");
3441        return null;
3442    }
3443
3444    @Override
3445    public @Nullable ComponentName getInstantAppResolverComponent() {
3446        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3447            return null;
3448        }
3449        synchronized (mPackages) {
3450            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3451            if (instantAppResolver == null) {
3452                return null;
3453            }
3454            return instantAppResolver.first;
3455        }
3456    }
3457
3458    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3459        final String[] packageArray =
3460                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3461        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3462            if (DEBUG_EPHEMERAL) {
3463                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3464            }
3465            return null;
3466        }
3467
3468        final int callingUid = Binder.getCallingUid();
3469        final int resolveFlags =
3470                MATCH_DIRECT_BOOT_AWARE
3471                | MATCH_DIRECT_BOOT_UNAWARE
3472                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3473        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3474        final Intent resolverIntent = new Intent(actionName);
3475        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3476                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3477        // temporarily look for the old action
3478        if (resolvers.size() == 0) {
3479            if (DEBUG_EPHEMERAL) {
3480                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3481            }
3482            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3483            resolverIntent.setAction(actionName);
3484            resolvers = queryIntentServicesInternal(resolverIntent, null,
3485                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3486        }
3487        final int N = resolvers.size();
3488        if (N == 0) {
3489            if (DEBUG_EPHEMERAL) {
3490                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3491            }
3492            return null;
3493        }
3494
3495        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3496        for (int i = 0; i < N; i++) {
3497            final ResolveInfo info = resolvers.get(i);
3498
3499            if (info.serviceInfo == null) {
3500                continue;
3501            }
3502
3503            final String packageName = info.serviceInfo.packageName;
3504            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3505                if (DEBUG_EPHEMERAL) {
3506                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3507                            + " pkg: " + packageName + ", info:" + info);
3508                }
3509                continue;
3510            }
3511
3512            if (DEBUG_EPHEMERAL) {
3513                Slog.v(TAG, "Ephemeral resolver found;"
3514                        + " pkg: " + packageName + ", info:" + info);
3515            }
3516            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3517        }
3518        if (DEBUG_EPHEMERAL) {
3519            Slog.v(TAG, "Ephemeral resolver NOT found");
3520        }
3521        return null;
3522    }
3523
3524    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3525        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3526        intent.addCategory(Intent.CATEGORY_DEFAULT);
3527        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3528
3529        final int resolveFlags =
3530                MATCH_DIRECT_BOOT_AWARE
3531                | MATCH_DIRECT_BOOT_UNAWARE
3532                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3533        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3534                resolveFlags, UserHandle.USER_SYSTEM);
3535        // temporarily look for the old action
3536        if (matches.isEmpty()) {
3537            if (DEBUG_EPHEMERAL) {
3538                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3539            }
3540            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3541            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3542                    resolveFlags, UserHandle.USER_SYSTEM);
3543        }
3544        Iterator<ResolveInfo> iter = matches.iterator();
3545        while (iter.hasNext()) {
3546            final ResolveInfo rInfo = iter.next();
3547            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3548            if (ps != null) {
3549                final PermissionsState permissionsState = ps.getPermissionsState();
3550                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3551                    continue;
3552                }
3553            }
3554            iter.remove();
3555        }
3556        if (matches.size() == 0) {
3557            return null;
3558        } else if (matches.size() == 1) {
3559            return (ActivityInfo) matches.get(0).getComponentInfo();
3560        } else {
3561            throw new RuntimeException(
3562                    "There must be at most one ephemeral installer; found " + matches);
3563        }
3564    }
3565
3566    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3567            @NonNull ComponentName resolver) {
3568        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3569                .addCategory(Intent.CATEGORY_DEFAULT)
3570                .setPackage(resolver.getPackageName());
3571        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3572        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3573                UserHandle.USER_SYSTEM);
3574        // temporarily look for the old action
3575        if (matches.isEmpty()) {
3576            if (DEBUG_EPHEMERAL) {
3577                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3578            }
3579            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3580            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3581                    UserHandle.USER_SYSTEM);
3582        }
3583        if (matches.isEmpty()) {
3584            return null;
3585        }
3586        return matches.get(0).getComponentInfo().getComponentName();
3587    }
3588
3589    private void primeDomainVerificationsLPw(int userId) {
3590        if (DEBUG_DOMAIN_VERIFICATION) {
3591            Slog.d(TAG, "Priming domain verifications in user " + userId);
3592        }
3593
3594        SystemConfig systemConfig = SystemConfig.getInstance();
3595        ArraySet<String> packages = systemConfig.getLinkedApps();
3596
3597        for (String packageName : packages) {
3598            PackageParser.Package pkg = mPackages.get(packageName);
3599            if (pkg != null) {
3600                if (!pkg.isSystemApp()) {
3601                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3602                    continue;
3603                }
3604
3605                ArraySet<String> domains = null;
3606                for (PackageParser.Activity a : pkg.activities) {
3607                    for (ActivityIntentInfo filter : a.intents) {
3608                        if (hasValidDomains(filter)) {
3609                            if (domains == null) {
3610                                domains = new ArraySet<String>();
3611                            }
3612                            domains.addAll(filter.getHostsList());
3613                        }
3614                    }
3615                }
3616
3617                if (domains != null && domains.size() > 0) {
3618                    if (DEBUG_DOMAIN_VERIFICATION) {
3619                        Slog.v(TAG, "      + " + packageName);
3620                    }
3621                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3622                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3623                    // and then 'always' in the per-user state actually used for intent resolution.
3624                    final IntentFilterVerificationInfo ivi;
3625                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3626                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3627                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3628                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3629                } else {
3630                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3631                            + "' does not handle web links");
3632                }
3633            } else {
3634                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3635            }
3636        }
3637
3638        scheduleWritePackageRestrictionsLocked(userId);
3639        scheduleWriteSettingsLocked();
3640    }
3641
3642    private void applyFactoryDefaultBrowserLPw(int userId) {
3643        // The default browser app's package name is stored in a string resource,
3644        // with a product-specific overlay used for vendor customization.
3645        String browserPkg = mContext.getResources().getString(
3646                com.android.internal.R.string.default_browser);
3647        if (!TextUtils.isEmpty(browserPkg)) {
3648            // non-empty string => required to be a known package
3649            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3650            if (ps == null) {
3651                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3652                browserPkg = null;
3653            } else {
3654                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3655            }
3656        }
3657
3658        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3659        // default.  If there's more than one, just leave everything alone.
3660        if (browserPkg == null) {
3661            calculateDefaultBrowserLPw(userId);
3662        }
3663    }
3664
3665    private void calculateDefaultBrowserLPw(int userId) {
3666        List<String> allBrowsers = resolveAllBrowserApps(userId);
3667        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3668        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3669    }
3670
3671    private List<String> resolveAllBrowserApps(int userId) {
3672        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3673        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3674                PackageManager.MATCH_ALL, userId);
3675
3676        final int count = list.size();
3677        List<String> result = new ArrayList<String>(count);
3678        for (int i=0; i<count; i++) {
3679            ResolveInfo info = list.get(i);
3680            if (info.activityInfo == null
3681                    || !info.handleAllWebDataURI
3682                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3683                    || result.contains(info.activityInfo.packageName)) {
3684                continue;
3685            }
3686            result.add(info.activityInfo.packageName);
3687        }
3688
3689        return result;
3690    }
3691
3692    private boolean packageIsBrowser(String packageName, int userId) {
3693        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3694                PackageManager.MATCH_ALL, userId);
3695        final int N = list.size();
3696        for (int i = 0; i < N; i++) {
3697            ResolveInfo info = list.get(i);
3698            if (packageName.equals(info.activityInfo.packageName)) {
3699                return true;
3700            }
3701        }
3702        return false;
3703    }
3704
3705    private void checkDefaultBrowser() {
3706        final int myUserId = UserHandle.myUserId();
3707        final String packageName = getDefaultBrowserPackageName(myUserId);
3708        if (packageName != null) {
3709            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3710            if (info == null) {
3711                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3712                synchronized (mPackages) {
3713                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3714                }
3715            }
3716        }
3717    }
3718
3719    @Override
3720    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3721            throws RemoteException {
3722        try {
3723            return super.onTransact(code, data, reply, flags);
3724        } catch (RuntimeException e) {
3725            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3726                Slog.wtf(TAG, "Package Manager Crash", e);
3727            }
3728            throw e;
3729        }
3730    }
3731
3732    static int[] appendInts(int[] cur, int[] add) {
3733        if (add == null) return cur;
3734        if (cur == null) return add;
3735        final int N = add.length;
3736        for (int i=0; i<N; i++) {
3737            cur = appendInt(cur, add[i]);
3738        }
3739        return cur;
3740    }
3741
3742    /**
3743     * Returns whether or not a full application can see an instant application.
3744     * <p>
3745     * Currently, there are three cases in which this can occur:
3746     * <ol>
3747     * <li>The calling application is a "special" process. The special
3748     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3749     *     and {@code 0}</li>
3750     * <li>The calling application has the permission
3751     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3752     * <li>The calling application is the default launcher on the
3753     *     system partition.</li>
3754     * </ol>
3755     */
3756    private boolean canViewInstantApps(int callingUid, int userId) {
3757        if (callingUid == Process.SYSTEM_UID
3758                || callingUid == Process.SHELL_UID
3759                || callingUid == Process.ROOT_UID) {
3760            return true;
3761        }
3762        if (mContext.checkCallingOrSelfPermission(
3763                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3764            return true;
3765        }
3766        if (mContext.checkCallingOrSelfPermission(
3767                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3768            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3769            if (homeComponent != null
3770                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3771                return true;
3772            }
3773        }
3774        return false;
3775    }
3776
3777    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3778        if (!sUserManager.exists(userId)) return null;
3779        if (ps == null) {
3780            return null;
3781        }
3782        PackageParser.Package p = ps.pkg;
3783        if (p == null) {
3784            return null;
3785        }
3786        final int callingUid = Binder.getCallingUid();
3787        // Filter out ephemeral app metadata:
3788        //   * The system/shell/root can see metadata for any app
3789        //   * An installed app can see metadata for 1) other installed apps
3790        //     and 2) ephemeral apps that have explicitly interacted with it
3791        //   * Ephemeral apps can only see their own data and exposed installed apps
3792        //   * Holding a signature permission allows seeing instant apps
3793        if (filterAppAccessLPr(ps, callingUid, userId)) {
3794            return null;
3795        }
3796
3797        final PermissionsState permissionsState = ps.getPermissionsState();
3798
3799        // Compute GIDs only if requested
3800        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3801                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3802        // Compute granted permissions only if package has requested permissions
3803        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3804                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3805        final PackageUserState state = ps.readUserState(userId);
3806
3807        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3808                && ps.isSystem()) {
3809            flags |= MATCH_ANY_USER;
3810        }
3811
3812        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3813                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3814
3815        if (packageInfo == null) {
3816            return null;
3817        }
3818
3819        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3820                resolveExternalPackageNameLPr(p);
3821
3822        return packageInfo;
3823    }
3824
3825    @Override
3826    public void checkPackageStartable(String packageName, int userId) {
3827        final int callingUid = Binder.getCallingUid();
3828        if (getInstantAppPackageName(callingUid) != null) {
3829            throw new SecurityException("Instant applications don't have access to this method");
3830        }
3831        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3832        synchronized (mPackages) {
3833            final PackageSetting ps = mSettings.mPackages.get(packageName);
3834            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3835                throw new SecurityException("Package " + packageName + " was not found!");
3836            }
3837
3838            if (!ps.getInstalled(userId)) {
3839                throw new SecurityException(
3840                        "Package " + packageName + " was not installed for user " + userId + "!");
3841            }
3842
3843            if (mSafeMode && !ps.isSystem()) {
3844                throw new SecurityException("Package " + packageName + " not a system app!");
3845            }
3846
3847            if (mFrozenPackages.contains(packageName)) {
3848                throw new SecurityException("Package " + packageName + " is currently frozen!");
3849            }
3850
3851            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3852                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3853            }
3854        }
3855    }
3856
3857    @Override
3858    public boolean isPackageAvailable(String packageName, int userId) {
3859        if (!sUserManager.exists(userId)) return false;
3860        final int callingUid = Binder.getCallingUid();
3861        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3862                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3863        synchronized (mPackages) {
3864            PackageParser.Package p = mPackages.get(packageName);
3865            if (p != null) {
3866                final PackageSetting ps = (PackageSetting) p.mExtras;
3867                if (filterAppAccessLPr(ps, callingUid, userId)) {
3868                    return false;
3869                }
3870                if (ps != null) {
3871                    final PackageUserState state = ps.readUserState(userId);
3872                    if (state != null) {
3873                        return PackageParser.isAvailable(state);
3874                    }
3875                }
3876            }
3877        }
3878        return false;
3879    }
3880
3881    @Override
3882    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3883        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3884                flags, Binder.getCallingUid(), userId);
3885    }
3886
3887    @Override
3888    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3889            int flags, int userId) {
3890        return getPackageInfoInternal(versionedPackage.getPackageName(),
3891                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3892    }
3893
3894    /**
3895     * Important: The provided filterCallingUid is used exclusively to filter out packages
3896     * that can be seen based on user state. It's typically the original caller uid prior
3897     * to clearing. Because it can only be provided by trusted code, it's value can be
3898     * trusted and will be used as-is; unlike userId which will be validated by this method.
3899     */
3900    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3901            int flags, int filterCallingUid, int userId) {
3902        if (!sUserManager.exists(userId)) return null;
3903        flags = updateFlagsForPackage(flags, userId, packageName);
3904        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3905                false /* requireFullPermission */, false /* checkShell */, "get package info");
3906
3907        // reader
3908        synchronized (mPackages) {
3909            // Normalize package name to handle renamed packages and static libs
3910            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3911
3912            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3913            if (matchFactoryOnly) {
3914                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3915                if (ps != null) {
3916                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3917                        return null;
3918                    }
3919                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3920                        return null;
3921                    }
3922                    return generatePackageInfo(ps, flags, userId);
3923                }
3924            }
3925
3926            PackageParser.Package p = mPackages.get(packageName);
3927            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3928                return null;
3929            }
3930            if (DEBUG_PACKAGE_INFO)
3931                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3932            if (p != null) {
3933                final PackageSetting ps = (PackageSetting) p.mExtras;
3934                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3935                    return null;
3936                }
3937                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3938                    return null;
3939                }
3940                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3941            }
3942            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3943                final PackageSetting ps = mSettings.mPackages.get(packageName);
3944                if (ps == null) return null;
3945                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3946                    return null;
3947                }
3948                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3949                    return null;
3950                }
3951                return generatePackageInfo(ps, flags, userId);
3952            }
3953        }
3954        return null;
3955    }
3956
3957    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3958        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3959            return true;
3960        }
3961        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3962            return true;
3963        }
3964        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3965            return true;
3966        }
3967        return false;
3968    }
3969
3970    private boolean isComponentVisibleToInstantApp(
3971            @Nullable ComponentName component, @ComponentType int type) {
3972        if (type == TYPE_ACTIVITY) {
3973            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3974            return activity != null
3975                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3976                    : false;
3977        } else if (type == TYPE_RECEIVER) {
3978            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3979            return activity != null
3980                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3981                    : false;
3982        } else if (type == TYPE_SERVICE) {
3983            final PackageParser.Service service = mServices.mServices.get(component);
3984            return service != null
3985                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3986                    : false;
3987        } else if (type == TYPE_PROVIDER) {
3988            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3989            return provider != null
3990                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3991                    : false;
3992        } else if (type == TYPE_UNKNOWN) {
3993            return isComponentVisibleToInstantApp(component);
3994        }
3995        return false;
3996    }
3997
3998    /**
3999     * Returns whether or not access to the application should be filtered.
4000     * <p>
4001     * Access may be limited based upon whether the calling or target applications
4002     * are instant applications.
4003     *
4004     * @see #canAccessInstantApps(int)
4005     */
4006    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4007            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4008        // if we're in an isolated process, get the real calling UID
4009        if (Process.isIsolated(callingUid)) {
4010            callingUid = mIsolatedOwners.get(callingUid);
4011        }
4012        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4013        final boolean callerIsInstantApp = instantAppPkgName != null;
4014        if (ps == null) {
4015            if (callerIsInstantApp) {
4016                // pretend the application exists, but, needs to be filtered
4017                return true;
4018            }
4019            return false;
4020        }
4021        // if the target and caller are the same application, don't filter
4022        if (isCallerSameApp(ps.name, callingUid)) {
4023            return false;
4024        }
4025        if (callerIsInstantApp) {
4026            // request for a specific component; if it hasn't been explicitly exposed, filter
4027            if (component != null) {
4028                return !isComponentVisibleToInstantApp(component, componentType);
4029            }
4030            // request for application; if no components have been explicitly exposed, filter
4031            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4032        }
4033        if (ps.getInstantApp(userId)) {
4034            // caller can see all components of all instant applications, don't filter
4035            if (canViewInstantApps(callingUid, userId)) {
4036                return false;
4037            }
4038            // request for a specific instant application component, filter
4039            if (component != null) {
4040                return true;
4041            }
4042            // request for an instant application; if the caller hasn't been granted access, filter
4043            return !mInstantAppRegistry.isInstantAccessGranted(
4044                    userId, UserHandle.getAppId(callingUid), ps.appId);
4045        }
4046        return false;
4047    }
4048
4049    /**
4050     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4051     */
4052    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4053        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4054    }
4055
4056    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4057            int flags) {
4058        // Callers can access only the libs they depend on, otherwise they need to explicitly
4059        // ask for the shared libraries given the caller is allowed to access all static libs.
4060        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4061            // System/shell/root get to see all static libs
4062            final int appId = UserHandle.getAppId(uid);
4063            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4064                    || appId == Process.ROOT_UID) {
4065                return false;
4066            }
4067        }
4068
4069        // No package means no static lib as it is always on internal storage
4070        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4071            return false;
4072        }
4073
4074        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4075                ps.pkg.staticSharedLibVersion);
4076        if (libEntry == null) {
4077            return false;
4078        }
4079
4080        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4081        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4082        if (uidPackageNames == null) {
4083            return true;
4084        }
4085
4086        for (String uidPackageName : uidPackageNames) {
4087            if (ps.name.equals(uidPackageName)) {
4088                return false;
4089            }
4090            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4091            if (uidPs != null) {
4092                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4093                        libEntry.info.getName());
4094                if (index < 0) {
4095                    continue;
4096                }
4097                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4098                    return false;
4099                }
4100            }
4101        }
4102        return true;
4103    }
4104
4105    @Override
4106    public String[] currentToCanonicalPackageNames(String[] names) {
4107        final int callingUid = Binder.getCallingUid();
4108        if (getInstantAppPackageName(callingUid) != null) {
4109            return names;
4110        }
4111        final String[] out = new String[names.length];
4112        // reader
4113        synchronized (mPackages) {
4114            final int callingUserId = UserHandle.getUserId(callingUid);
4115            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4116            for (int i=names.length-1; i>=0; i--) {
4117                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4118                boolean translateName = false;
4119                if (ps != null && ps.realName != null) {
4120                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4121                    translateName = !targetIsInstantApp
4122                            || canViewInstantApps
4123                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4124                                    UserHandle.getAppId(callingUid), ps.appId);
4125                }
4126                out[i] = translateName ? ps.realName : names[i];
4127            }
4128        }
4129        return out;
4130    }
4131
4132    @Override
4133    public String[] canonicalToCurrentPackageNames(String[] names) {
4134        final int callingUid = Binder.getCallingUid();
4135        if (getInstantAppPackageName(callingUid) != null) {
4136            return names;
4137        }
4138        final String[] out = new String[names.length];
4139        // reader
4140        synchronized (mPackages) {
4141            final int callingUserId = UserHandle.getUserId(callingUid);
4142            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4143            for (int i=names.length-1; i>=0; i--) {
4144                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4145                boolean translateName = false;
4146                if (cur != null) {
4147                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4148                    final boolean targetIsInstantApp =
4149                            ps != null && ps.getInstantApp(callingUserId);
4150                    translateName = !targetIsInstantApp
4151                            || canViewInstantApps
4152                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4153                                    UserHandle.getAppId(callingUid), ps.appId);
4154                }
4155                out[i] = translateName ? cur : names[i];
4156            }
4157        }
4158        return out;
4159    }
4160
4161    @Override
4162    public int getPackageUid(String packageName, int flags, int userId) {
4163        if (!sUserManager.exists(userId)) return -1;
4164        final int callingUid = Binder.getCallingUid();
4165        flags = updateFlagsForPackage(flags, userId, packageName);
4166        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4167                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4168
4169        // reader
4170        synchronized (mPackages) {
4171            final PackageParser.Package p = mPackages.get(packageName);
4172            if (p != null && p.isMatch(flags)) {
4173                PackageSetting ps = (PackageSetting) p.mExtras;
4174                if (filterAppAccessLPr(ps, callingUid, userId)) {
4175                    return -1;
4176                }
4177                return UserHandle.getUid(userId, p.applicationInfo.uid);
4178            }
4179            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4180                final PackageSetting ps = mSettings.mPackages.get(packageName);
4181                if (ps != null && ps.isMatch(flags)
4182                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4183                    return UserHandle.getUid(userId, ps.appId);
4184                }
4185            }
4186        }
4187
4188        return -1;
4189    }
4190
4191    @Override
4192    public int[] getPackageGids(String packageName, int flags, int userId) {
4193        if (!sUserManager.exists(userId)) return null;
4194        final int callingUid = Binder.getCallingUid();
4195        flags = updateFlagsForPackage(flags, userId, packageName);
4196        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4197                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4198
4199        // reader
4200        synchronized (mPackages) {
4201            final PackageParser.Package p = mPackages.get(packageName);
4202            if (p != null && p.isMatch(flags)) {
4203                PackageSetting ps = (PackageSetting) p.mExtras;
4204                if (filterAppAccessLPr(ps, callingUid, userId)) {
4205                    return null;
4206                }
4207                // TODO: Shouldn't this be checking for package installed state for userId and
4208                // return null?
4209                return ps.getPermissionsState().computeGids(userId);
4210            }
4211            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4212                final PackageSetting ps = mSettings.mPackages.get(packageName);
4213                if (ps != null && ps.isMatch(flags)
4214                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4215                    return ps.getPermissionsState().computeGids(userId);
4216                }
4217            }
4218        }
4219
4220        return null;
4221    }
4222
4223    @Override
4224    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4225        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4226    }
4227
4228    @Override
4229    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4230            int flags) {
4231        // TODO Move this to PermissionManager when mPermissionGroups is moved there
4232        synchronized (mPackages) {
4233            if (groupName != null && !mPermissionGroups.containsKey(groupName)) {
4234                // This is thrown as NameNotFoundException
4235                return null;
4236            }
4237        }
4238        return new ParceledListSlice<>(
4239                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()));
4240    }
4241
4242    @Override
4243    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4244        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4245            return null;
4246        }
4247        // reader
4248        synchronized (mPackages) {
4249            return PackageParser.generatePermissionGroupInfo(
4250                    mPermissionGroups.get(name), flags);
4251        }
4252    }
4253
4254    @Override
4255    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4256        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4257            return ParceledListSlice.emptyList();
4258        }
4259        // reader
4260        synchronized (mPackages) {
4261            final int N = mPermissionGroups.size();
4262            ArrayList<PermissionGroupInfo> out
4263                    = new ArrayList<PermissionGroupInfo>(N);
4264            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4265                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4266            }
4267            return new ParceledListSlice<>(out);
4268        }
4269    }
4270
4271    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4272            int filterCallingUid, int userId) {
4273        if (!sUserManager.exists(userId)) return null;
4274        PackageSetting ps = mSettings.mPackages.get(packageName);
4275        if (ps != null) {
4276            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4277                return null;
4278            }
4279            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4280                return null;
4281            }
4282            if (ps.pkg == null) {
4283                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4284                if (pInfo != null) {
4285                    return pInfo.applicationInfo;
4286                }
4287                return null;
4288            }
4289            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4290                    ps.readUserState(userId), userId);
4291            if (ai != null) {
4292                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4293            }
4294            return ai;
4295        }
4296        return null;
4297    }
4298
4299    @Override
4300    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4301        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4302    }
4303
4304    /**
4305     * Important: The provided filterCallingUid is used exclusively to filter out applications
4306     * that can be seen based on user state. It's typically the original caller uid prior
4307     * to clearing. Because it can only be provided by trusted code, it's value can be
4308     * trusted and will be used as-is; unlike userId which will be validated by this method.
4309     */
4310    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4311            int filterCallingUid, int userId) {
4312        if (!sUserManager.exists(userId)) return null;
4313        flags = updateFlagsForApplication(flags, userId, packageName);
4314        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4315                false /* requireFullPermission */, false /* checkShell */, "get application info");
4316
4317        // writer
4318        synchronized (mPackages) {
4319            // Normalize package name to handle renamed packages and static libs
4320            packageName = resolveInternalPackageNameLPr(packageName,
4321                    PackageManager.VERSION_CODE_HIGHEST);
4322
4323            PackageParser.Package p = mPackages.get(packageName);
4324            if (DEBUG_PACKAGE_INFO) Log.v(
4325                    TAG, "getApplicationInfo " + packageName
4326                    + ": " + p);
4327            if (p != null) {
4328                PackageSetting ps = mSettings.mPackages.get(packageName);
4329                if (ps == null) return null;
4330                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4331                    return null;
4332                }
4333                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4334                    return null;
4335                }
4336                // Note: isEnabledLP() does not apply here - always return info
4337                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4338                        p, flags, ps.readUserState(userId), userId);
4339                if (ai != null) {
4340                    ai.packageName = resolveExternalPackageNameLPr(p);
4341                }
4342                return ai;
4343            }
4344            if ("android".equals(packageName)||"system".equals(packageName)) {
4345                return mAndroidApplication;
4346            }
4347            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4348                // Already generates the external package name
4349                return generateApplicationInfoFromSettingsLPw(packageName,
4350                        flags, filterCallingUid, userId);
4351            }
4352        }
4353        return null;
4354    }
4355
4356    private String normalizePackageNameLPr(String packageName) {
4357        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4358        return normalizedPackageName != null ? normalizedPackageName : packageName;
4359    }
4360
4361    @Override
4362    public void deletePreloadsFileCache() {
4363        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4364            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4365        }
4366        File dir = Environment.getDataPreloadsFileCacheDirectory();
4367        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4368        FileUtils.deleteContents(dir);
4369    }
4370
4371    @Override
4372    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4373            final int storageFlags, final IPackageDataObserver observer) {
4374        mContext.enforceCallingOrSelfPermission(
4375                android.Manifest.permission.CLEAR_APP_CACHE, null);
4376        mHandler.post(() -> {
4377            boolean success = false;
4378            try {
4379                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4380                success = true;
4381            } catch (IOException e) {
4382                Slog.w(TAG, e);
4383            }
4384            if (observer != null) {
4385                try {
4386                    observer.onRemoveCompleted(null, success);
4387                } catch (RemoteException e) {
4388                    Slog.w(TAG, e);
4389                }
4390            }
4391        });
4392    }
4393
4394    @Override
4395    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4396            final int storageFlags, final IntentSender pi) {
4397        mContext.enforceCallingOrSelfPermission(
4398                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4399        mHandler.post(() -> {
4400            boolean success = false;
4401            try {
4402                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4403                success = true;
4404            } catch (IOException e) {
4405                Slog.w(TAG, e);
4406            }
4407            if (pi != null) {
4408                try {
4409                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4410                } catch (SendIntentException e) {
4411                    Slog.w(TAG, e);
4412                }
4413            }
4414        });
4415    }
4416
4417    /**
4418     * Blocking call to clear various types of cached data across the system
4419     * until the requested bytes are available.
4420     */
4421    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4422        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4423        final File file = storage.findPathForUuid(volumeUuid);
4424        if (file.getUsableSpace() >= bytes) return;
4425
4426        if (ENABLE_FREE_CACHE_V2) {
4427            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4428                    volumeUuid);
4429            final boolean aggressive = (storageFlags
4430                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4431            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4432
4433            // 1. Pre-flight to determine if we have any chance to succeed
4434            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4435            if (internalVolume && (aggressive || SystemProperties
4436                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4437                deletePreloadsFileCache();
4438                if (file.getUsableSpace() >= bytes) return;
4439            }
4440
4441            // 3. Consider parsed APK data (aggressive only)
4442            if (internalVolume && aggressive) {
4443                FileUtils.deleteContents(mCacheDir);
4444                if (file.getUsableSpace() >= bytes) return;
4445            }
4446
4447            // 4. Consider cached app data (above quotas)
4448            try {
4449                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4450                        Installer.FLAG_FREE_CACHE_V2);
4451            } catch (InstallerException ignored) {
4452            }
4453            if (file.getUsableSpace() >= bytes) return;
4454
4455            // 5. Consider shared libraries with refcount=0 and age>min cache period
4456            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4457                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4458                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4459                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4460                return;
4461            }
4462
4463            // 6. Consider dexopt output (aggressive only)
4464            // TODO: Implement
4465
4466            // 7. Consider installed instant apps unused longer than min cache period
4467            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4468                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4469                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4470                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4471                return;
4472            }
4473
4474            // 8. Consider cached app data (below quotas)
4475            try {
4476                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4477                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4478            } catch (InstallerException ignored) {
4479            }
4480            if (file.getUsableSpace() >= bytes) return;
4481
4482            // 9. Consider DropBox entries
4483            // TODO: Implement
4484
4485            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4486            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4487                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4488                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4489                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4490                return;
4491            }
4492        } else {
4493            try {
4494                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4495            } catch (InstallerException ignored) {
4496            }
4497            if (file.getUsableSpace() >= bytes) return;
4498        }
4499
4500        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4501    }
4502
4503    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4504            throws IOException {
4505        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4506        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4507
4508        List<VersionedPackage> packagesToDelete = null;
4509        final long now = System.currentTimeMillis();
4510
4511        synchronized (mPackages) {
4512            final int[] allUsers = sUserManager.getUserIds();
4513            final int libCount = mSharedLibraries.size();
4514            for (int i = 0; i < libCount; i++) {
4515                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4516                if (versionedLib == null) {
4517                    continue;
4518                }
4519                final int versionCount = versionedLib.size();
4520                for (int j = 0; j < versionCount; j++) {
4521                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4522                    // Skip packages that are not static shared libs.
4523                    if (!libInfo.isStatic()) {
4524                        break;
4525                    }
4526                    // Important: We skip static shared libs used for some user since
4527                    // in such a case we need to keep the APK on the device. The check for
4528                    // a lib being used for any user is performed by the uninstall call.
4529                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4530                    // Resolve the package name - we use synthetic package names internally
4531                    final String internalPackageName = resolveInternalPackageNameLPr(
4532                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4533                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4534                    // Skip unused static shared libs cached less than the min period
4535                    // to prevent pruning a lib needed by a subsequently installed package.
4536                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4537                        continue;
4538                    }
4539                    if (packagesToDelete == null) {
4540                        packagesToDelete = new ArrayList<>();
4541                    }
4542                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4543                            declaringPackage.getVersionCode()));
4544                }
4545            }
4546        }
4547
4548        if (packagesToDelete != null) {
4549            final int packageCount = packagesToDelete.size();
4550            for (int i = 0; i < packageCount; i++) {
4551                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4552                // Delete the package synchronously (will fail of the lib used for any user).
4553                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4554                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4555                                == PackageManager.DELETE_SUCCEEDED) {
4556                    if (volume.getUsableSpace() >= neededSpace) {
4557                        return true;
4558                    }
4559                }
4560            }
4561        }
4562
4563        return false;
4564    }
4565
4566    /**
4567     * Update given flags based on encryption status of current user.
4568     */
4569    private int updateFlags(int flags, int userId) {
4570        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4571                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4572            // Caller expressed an explicit opinion about what encryption
4573            // aware/unaware components they want to see, so fall through and
4574            // give them what they want
4575        } else {
4576            // Caller expressed no opinion, so match based on user state
4577            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4578                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4579            } else {
4580                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4581            }
4582        }
4583        return flags;
4584    }
4585
4586    private UserManagerInternal getUserManagerInternal() {
4587        if (mUserManagerInternal == null) {
4588            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4589        }
4590        return mUserManagerInternal;
4591    }
4592
4593    private DeviceIdleController.LocalService getDeviceIdleController() {
4594        if (mDeviceIdleController == null) {
4595            mDeviceIdleController =
4596                    LocalServices.getService(DeviceIdleController.LocalService.class);
4597        }
4598        return mDeviceIdleController;
4599    }
4600
4601    /**
4602     * Update given flags when being used to request {@link PackageInfo}.
4603     */
4604    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4605        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4606        boolean triaged = true;
4607        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4608                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4609            // Caller is asking for component details, so they'd better be
4610            // asking for specific encryption matching behavior, or be triaged
4611            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4612                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4613                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4614                triaged = false;
4615            }
4616        }
4617        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4618                | PackageManager.MATCH_SYSTEM_ONLY
4619                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4620            triaged = false;
4621        }
4622        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4623            mPermissionManager.enforceCrossUserPermission(
4624                    Binder.getCallingUid(), userId, false, false,
4625                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4626                    + Debug.getCallers(5));
4627        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4628                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4629            // If the caller wants all packages and has a restricted profile associated with it,
4630            // then match all users. This is to make sure that launchers that need to access work
4631            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4632            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4633            flags |= PackageManager.MATCH_ANY_USER;
4634        }
4635        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4636            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4637                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4638        }
4639        return updateFlags(flags, userId);
4640    }
4641
4642    /**
4643     * Update given flags when being used to request {@link ApplicationInfo}.
4644     */
4645    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4646        return updateFlagsForPackage(flags, userId, cookie);
4647    }
4648
4649    /**
4650     * Update given flags when being used to request {@link ComponentInfo}.
4651     */
4652    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4653        if (cookie instanceof Intent) {
4654            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4655                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4656            }
4657        }
4658
4659        boolean triaged = true;
4660        // Caller is asking for component details, so they'd better be
4661        // asking for specific encryption matching behavior, or be triaged
4662        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4663                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4664                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4665            triaged = false;
4666        }
4667        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4668            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4669                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4670        }
4671
4672        return updateFlags(flags, userId);
4673    }
4674
4675    /**
4676     * Update given intent when being used to request {@link ResolveInfo}.
4677     */
4678    private Intent updateIntentForResolve(Intent intent) {
4679        if (intent.getSelector() != null) {
4680            intent = intent.getSelector();
4681        }
4682        if (DEBUG_PREFERRED) {
4683            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4684        }
4685        return intent;
4686    }
4687
4688    /**
4689     * Update given flags when being used to request {@link ResolveInfo}.
4690     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4691     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4692     * flag set. However, this flag is only honoured in three circumstances:
4693     * <ul>
4694     * <li>when called from a system process</li>
4695     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4696     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4697     * action and a {@code android.intent.category.BROWSABLE} category</li>
4698     * </ul>
4699     */
4700    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4701        return updateFlagsForResolve(flags, userId, intent, callingUid,
4702                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4703    }
4704    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4705            boolean wantInstantApps) {
4706        return updateFlagsForResolve(flags, userId, intent, callingUid,
4707                wantInstantApps, false /*onlyExposedExplicitly*/);
4708    }
4709    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4710            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4711        // Safe mode means we shouldn't match any third-party components
4712        if (mSafeMode) {
4713            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4714        }
4715        if (getInstantAppPackageName(callingUid) != null) {
4716            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4717            if (onlyExposedExplicitly) {
4718                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4719            }
4720            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4721            flags |= PackageManager.MATCH_INSTANT;
4722        } else {
4723            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4724            final boolean allowMatchInstant =
4725                    (wantInstantApps
4726                            && Intent.ACTION_VIEW.equals(intent.getAction())
4727                            && hasWebURI(intent))
4728                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4729            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4730                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4731            if (!allowMatchInstant) {
4732                flags &= ~PackageManager.MATCH_INSTANT;
4733            }
4734        }
4735        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4736    }
4737
4738    @Override
4739    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4740        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4741    }
4742
4743    /**
4744     * Important: The provided filterCallingUid is used exclusively to filter out activities
4745     * that can be seen based on user state. It's typically the original caller uid prior
4746     * to clearing. Because it can only be provided by trusted code, it's value can be
4747     * trusted and will be used as-is; unlike userId which will be validated by this method.
4748     */
4749    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4750            int filterCallingUid, int userId) {
4751        if (!sUserManager.exists(userId)) return null;
4752        flags = updateFlagsForComponent(flags, userId, component);
4753        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4754                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4755        synchronized (mPackages) {
4756            PackageParser.Activity a = mActivities.mActivities.get(component);
4757
4758            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4759            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4760                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4761                if (ps == null) return null;
4762                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4763                    return null;
4764                }
4765                return PackageParser.generateActivityInfo(
4766                        a, flags, ps.readUserState(userId), userId);
4767            }
4768            if (mResolveComponentName.equals(component)) {
4769                return PackageParser.generateActivityInfo(
4770                        mResolveActivity, flags, new PackageUserState(), userId);
4771            }
4772        }
4773        return null;
4774    }
4775
4776    @Override
4777    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4778            String resolvedType) {
4779        synchronized (mPackages) {
4780            if (component.equals(mResolveComponentName)) {
4781                // The resolver supports EVERYTHING!
4782                return true;
4783            }
4784            final int callingUid = Binder.getCallingUid();
4785            final int callingUserId = UserHandle.getUserId(callingUid);
4786            PackageParser.Activity a = mActivities.mActivities.get(component);
4787            if (a == null) {
4788                return false;
4789            }
4790            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4791            if (ps == null) {
4792                return false;
4793            }
4794            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4795                return false;
4796            }
4797            for (int i=0; i<a.intents.size(); i++) {
4798                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4799                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4800                    return true;
4801                }
4802            }
4803            return false;
4804        }
4805    }
4806
4807    @Override
4808    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4809        if (!sUserManager.exists(userId)) return null;
4810        final int callingUid = Binder.getCallingUid();
4811        flags = updateFlagsForComponent(flags, userId, component);
4812        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4813                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4814        synchronized (mPackages) {
4815            PackageParser.Activity a = mReceivers.mActivities.get(component);
4816            if (DEBUG_PACKAGE_INFO) Log.v(
4817                TAG, "getReceiverInfo " + component + ": " + a);
4818            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4819                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4820                if (ps == null) return null;
4821                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4822                    return null;
4823                }
4824                return PackageParser.generateActivityInfo(
4825                        a, flags, ps.readUserState(userId), userId);
4826            }
4827        }
4828        return null;
4829    }
4830
4831    @Override
4832    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4833            int flags, int userId) {
4834        if (!sUserManager.exists(userId)) return null;
4835        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4836        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4837            return null;
4838        }
4839
4840        flags = updateFlagsForPackage(flags, userId, null);
4841
4842        final boolean canSeeStaticLibraries =
4843                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4844                        == PERMISSION_GRANTED
4845                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4846                        == PERMISSION_GRANTED
4847                || canRequestPackageInstallsInternal(packageName,
4848                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4849                        false  /* throwIfPermNotDeclared*/)
4850                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4851                        == PERMISSION_GRANTED;
4852
4853        synchronized (mPackages) {
4854            List<SharedLibraryInfo> result = null;
4855
4856            final int libCount = mSharedLibraries.size();
4857            for (int i = 0; i < libCount; i++) {
4858                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4859                if (versionedLib == null) {
4860                    continue;
4861                }
4862
4863                final int versionCount = versionedLib.size();
4864                for (int j = 0; j < versionCount; j++) {
4865                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4866                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4867                        break;
4868                    }
4869                    final long identity = Binder.clearCallingIdentity();
4870                    try {
4871                        PackageInfo packageInfo = getPackageInfoVersioned(
4872                                libInfo.getDeclaringPackage(), flags
4873                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4874                        if (packageInfo == null) {
4875                            continue;
4876                        }
4877                    } finally {
4878                        Binder.restoreCallingIdentity(identity);
4879                    }
4880
4881                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4882                            libInfo.getVersion(), libInfo.getType(),
4883                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4884                            flags, userId));
4885
4886                    if (result == null) {
4887                        result = new ArrayList<>();
4888                    }
4889                    result.add(resLibInfo);
4890                }
4891            }
4892
4893            return result != null ? new ParceledListSlice<>(result) : null;
4894        }
4895    }
4896
4897    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4898            SharedLibraryInfo libInfo, int flags, int userId) {
4899        List<VersionedPackage> versionedPackages = null;
4900        final int packageCount = mSettings.mPackages.size();
4901        for (int i = 0; i < packageCount; i++) {
4902            PackageSetting ps = mSettings.mPackages.valueAt(i);
4903
4904            if (ps == null) {
4905                continue;
4906            }
4907
4908            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4909                continue;
4910            }
4911
4912            final String libName = libInfo.getName();
4913            if (libInfo.isStatic()) {
4914                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4915                if (libIdx < 0) {
4916                    continue;
4917                }
4918                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4919                    continue;
4920                }
4921                if (versionedPackages == null) {
4922                    versionedPackages = new ArrayList<>();
4923                }
4924                // If the dependent is a static shared lib, use the public package name
4925                String dependentPackageName = ps.name;
4926                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4927                    dependentPackageName = ps.pkg.manifestPackageName;
4928                }
4929                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4930            } else if (ps.pkg != null) {
4931                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4932                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4933                    if (versionedPackages == null) {
4934                        versionedPackages = new ArrayList<>();
4935                    }
4936                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4937                }
4938            }
4939        }
4940
4941        return versionedPackages;
4942    }
4943
4944    @Override
4945    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4946        if (!sUserManager.exists(userId)) return null;
4947        final int callingUid = Binder.getCallingUid();
4948        flags = updateFlagsForComponent(flags, userId, component);
4949        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4950                false /* requireFullPermission */, false /* checkShell */, "get service info");
4951        synchronized (mPackages) {
4952            PackageParser.Service s = mServices.mServices.get(component);
4953            if (DEBUG_PACKAGE_INFO) Log.v(
4954                TAG, "getServiceInfo " + component + ": " + s);
4955            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4956                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4957                if (ps == null) return null;
4958                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4959                    return null;
4960                }
4961                return PackageParser.generateServiceInfo(
4962                        s, flags, ps.readUserState(userId), userId);
4963            }
4964        }
4965        return null;
4966    }
4967
4968    @Override
4969    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4970        if (!sUserManager.exists(userId)) return null;
4971        final int callingUid = Binder.getCallingUid();
4972        flags = updateFlagsForComponent(flags, userId, component);
4973        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4974                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4975        synchronized (mPackages) {
4976            PackageParser.Provider p = mProviders.mProviders.get(component);
4977            if (DEBUG_PACKAGE_INFO) Log.v(
4978                TAG, "getProviderInfo " + component + ": " + p);
4979            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4980                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4981                if (ps == null) return null;
4982                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4983                    return null;
4984                }
4985                return PackageParser.generateProviderInfo(
4986                        p, flags, ps.readUserState(userId), userId);
4987            }
4988        }
4989        return null;
4990    }
4991
4992    @Override
4993    public String[] getSystemSharedLibraryNames() {
4994        // allow instant applications
4995        synchronized (mPackages) {
4996            Set<String> libs = null;
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                final int versionCount = versionedLib.size();
5004                for (int j = 0; j < versionCount; j++) {
5005                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5006                    if (!libEntry.info.isStatic()) {
5007                        if (libs == null) {
5008                            libs = new ArraySet<>();
5009                        }
5010                        libs.add(libEntry.info.getName());
5011                        break;
5012                    }
5013                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5014                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5015                            UserHandle.getUserId(Binder.getCallingUid()),
5016                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5017                        if (libs == null) {
5018                            libs = new ArraySet<>();
5019                        }
5020                        libs.add(libEntry.info.getName());
5021                        break;
5022                    }
5023                }
5024            }
5025
5026            if (libs != null) {
5027                String[] libsArray = new String[libs.size()];
5028                libs.toArray(libsArray);
5029                return libsArray;
5030            }
5031
5032            return null;
5033        }
5034    }
5035
5036    @Override
5037    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5038        // allow instant applications
5039        synchronized (mPackages) {
5040            return mServicesSystemSharedLibraryPackageName;
5041        }
5042    }
5043
5044    @Override
5045    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5046        // allow instant applications
5047        synchronized (mPackages) {
5048            return mSharedSystemSharedLibraryPackageName;
5049        }
5050    }
5051
5052    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5053        for (int i = userList.length - 1; i >= 0; --i) {
5054            final int userId = userList[i];
5055            // don't add instant app to the list of updates
5056            if (pkgSetting.getInstantApp(userId)) {
5057                continue;
5058            }
5059            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5060            if (changedPackages == null) {
5061                changedPackages = new SparseArray<>();
5062                mChangedPackages.put(userId, changedPackages);
5063            }
5064            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5065            if (sequenceNumbers == null) {
5066                sequenceNumbers = new HashMap<>();
5067                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5068            }
5069            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5070            if (sequenceNumber != null) {
5071                changedPackages.remove(sequenceNumber);
5072            }
5073            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5074            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5075        }
5076        mChangedPackagesSequenceNumber++;
5077    }
5078
5079    @Override
5080    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5081        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5082            return null;
5083        }
5084        synchronized (mPackages) {
5085            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5086                return null;
5087            }
5088            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5089            if (changedPackages == null) {
5090                return null;
5091            }
5092            final List<String> packageNames =
5093                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5094            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5095                final String packageName = changedPackages.get(i);
5096                if (packageName != null) {
5097                    packageNames.add(packageName);
5098                }
5099            }
5100            return packageNames.isEmpty()
5101                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5102        }
5103    }
5104
5105    @Override
5106    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5107        // allow instant applications
5108        ArrayList<FeatureInfo> res;
5109        synchronized (mAvailableFeatures) {
5110            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5111            res.addAll(mAvailableFeatures.values());
5112        }
5113        final FeatureInfo fi = new FeatureInfo();
5114        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5115                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5116        res.add(fi);
5117
5118        return new ParceledListSlice<>(res);
5119    }
5120
5121    @Override
5122    public boolean hasSystemFeature(String name, int version) {
5123        // allow instant applications
5124        synchronized (mAvailableFeatures) {
5125            final FeatureInfo feat = mAvailableFeatures.get(name);
5126            if (feat == null) {
5127                return false;
5128            } else {
5129                return feat.version >= version;
5130            }
5131        }
5132    }
5133
5134    @Override
5135    public int checkPermission(String permName, String pkgName, int userId) {
5136        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5137    }
5138
5139    @Override
5140    public int checkUidPermission(String permName, int uid) {
5141        final int callingUid = Binder.getCallingUid();
5142        final int callingUserId = UserHandle.getUserId(callingUid);
5143        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5144        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5145        final int userId = UserHandle.getUserId(uid);
5146        if (!sUserManager.exists(userId)) {
5147            return PackageManager.PERMISSION_DENIED;
5148        }
5149
5150        synchronized (mPackages) {
5151            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5152            if (obj != null) {
5153                if (obj instanceof SharedUserSetting) {
5154                    if (isCallerInstantApp) {
5155                        return PackageManager.PERMISSION_DENIED;
5156                    }
5157                } else if (obj instanceof PackageSetting) {
5158                    final PackageSetting ps = (PackageSetting) obj;
5159                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5160                        return PackageManager.PERMISSION_DENIED;
5161                    }
5162                }
5163                final SettingBase settingBase = (SettingBase) obj;
5164                final PermissionsState permissionsState = settingBase.getPermissionsState();
5165                if (permissionsState.hasPermission(permName, userId)) {
5166                    if (isUidInstantApp) {
5167                        if (mSettings.mPermissions.isPermissionInstant(permName)) {
5168                            return PackageManager.PERMISSION_GRANTED;
5169                        }
5170                    } else {
5171                        return PackageManager.PERMISSION_GRANTED;
5172                    }
5173                }
5174                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5175                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5176                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5177                    return PackageManager.PERMISSION_GRANTED;
5178                }
5179            } else {
5180                ArraySet<String> perms = mSystemPermissions.get(uid);
5181                if (perms != null) {
5182                    if (perms.contains(permName)) {
5183                        return PackageManager.PERMISSION_GRANTED;
5184                    }
5185                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5186                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5187                        return PackageManager.PERMISSION_GRANTED;
5188                    }
5189                }
5190            }
5191        }
5192
5193        return PackageManager.PERMISSION_DENIED;
5194    }
5195
5196    @Override
5197    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5198        if (UserHandle.getCallingUserId() != userId) {
5199            mContext.enforceCallingPermission(
5200                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5201                    "isPermissionRevokedByPolicy for user " + userId);
5202        }
5203
5204        if (checkPermission(permission, packageName, userId)
5205                == PackageManager.PERMISSION_GRANTED) {
5206            return false;
5207        }
5208
5209        final int callingUid = Binder.getCallingUid();
5210        if (getInstantAppPackageName(callingUid) != null) {
5211            if (!isCallerSameApp(packageName, callingUid)) {
5212                return false;
5213            }
5214        } else {
5215            if (isInstantApp(packageName, userId)) {
5216                return false;
5217            }
5218        }
5219
5220        final long identity = Binder.clearCallingIdentity();
5221        try {
5222            final int flags = getPermissionFlags(permission, packageName, userId);
5223            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5224        } finally {
5225            Binder.restoreCallingIdentity(identity);
5226        }
5227    }
5228
5229    @Override
5230    public String getPermissionControllerPackageName() {
5231        synchronized (mPackages) {
5232            return mRequiredInstallerPackage;
5233        }
5234    }
5235
5236    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5237        return mPermissionManager.addDynamicPermission(
5238                info, async, getCallingUid(), new PermissionCallback() {
5239                    @Override
5240                    public void onPermissionChanged() {
5241                        if (!async) {
5242                            mSettings.writeLPr();
5243                        } else {
5244                            scheduleWriteSettingsLocked();
5245                        }
5246                    }
5247                });
5248    }
5249
5250    @Override
5251    public boolean addPermission(PermissionInfo info) {
5252        synchronized (mPackages) {
5253            return addDynamicPermission(info, false);
5254        }
5255    }
5256
5257    @Override
5258    public boolean addPermissionAsync(PermissionInfo info) {
5259        synchronized (mPackages) {
5260            return addDynamicPermission(info, true);
5261        }
5262    }
5263
5264    @Override
5265    public void removePermission(String permName) {
5266        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5267    }
5268
5269    @Override
5270    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5271        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5272                getCallingUid(), userId, mPermissionCallback);
5273    }
5274
5275    @Override
5276    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5277        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5278                getCallingUid(), userId, mPermissionCallback);
5279    }
5280
5281    /**
5282     * Get the first event id for the permission.
5283     *
5284     * <p>There are four events for each permission: <ul>
5285     *     <li>Request permission: first id + 0</li>
5286     *     <li>Grant permission: first id + 1</li>
5287     *     <li>Request for permission denied: first id + 2</li>
5288     *     <li>Revoke permission: first id + 3</li>
5289     * </ul></p>
5290     *
5291     * @param name name of the permission
5292     *
5293     * @return The first event id for the permission
5294     */
5295    private static int getBaseEventId(@NonNull String name) {
5296        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5297
5298        if (eventIdIndex == -1) {
5299            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5300                    || Build.IS_USER) {
5301                Log.i(TAG, "Unknown permission " + name);
5302
5303                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5304            } else {
5305                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5306                //
5307                // Also update
5308                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5309                // - metrics_constants.proto
5310                throw new IllegalStateException("Unknown permission " + name);
5311            }
5312        }
5313
5314        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5315    }
5316
5317    /**
5318     * Log that a permission was revoked.
5319     *
5320     * @param context Context of the caller
5321     * @param name name of the permission
5322     * @param packageName package permission if for
5323     */
5324    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5325            @NonNull String packageName) {
5326        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5327    }
5328
5329    /**
5330     * Log that a permission request was granted.
5331     *
5332     * @param context Context of the caller
5333     * @param name name of the permission
5334     * @param packageName package permission if for
5335     */
5336    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5337            @NonNull String packageName) {
5338        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5339    }
5340
5341    @Override
5342    public void resetRuntimePermissions() {
5343        mContext.enforceCallingOrSelfPermission(
5344                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5345                "revokeRuntimePermission");
5346
5347        int callingUid = Binder.getCallingUid();
5348        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5349            mContext.enforceCallingOrSelfPermission(
5350                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5351                    "resetRuntimePermissions");
5352        }
5353
5354        synchronized (mPackages) {
5355            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5356            for (int userId : UserManagerService.getInstance().getUserIds()) {
5357                final int packageCount = mPackages.size();
5358                for (int i = 0; i < packageCount; i++) {
5359                    PackageParser.Package pkg = mPackages.valueAt(i);
5360                    if (!(pkg.mExtras instanceof PackageSetting)) {
5361                        continue;
5362                    }
5363                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5364                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5365                }
5366            }
5367        }
5368    }
5369
5370    @Override
5371    public int getPermissionFlags(String permName, String packageName, int userId) {
5372        return mPermissionManager.getPermissionFlags(permName, packageName, getCallingUid(), userId);
5373    }
5374
5375    @Override
5376    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5377            int flagValues, int userId) {
5378        mPermissionManager.updatePermissionFlags(
5379                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5380                mPermissionCallback);
5381    }
5382
5383    /**
5384     * Update the permission flags for all packages and runtime permissions of a user in order
5385     * to allow device or profile owner to remove POLICY_FIXED.
5386     */
5387    @Override
5388    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5389        synchronized (mPackages) {
5390            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5391                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5392                    mPermissionCallback);
5393            if (changed) {
5394                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5395            }
5396        }
5397    }
5398
5399    @Override
5400    public boolean shouldShowRequestPermissionRationale(String permissionName,
5401            String packageName, int userId) {
5402        if (UserHandle.getCallingUserId() != userId) {
5403            mContext.enforceCallingPermission(
5404                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5405                    "canShowRequestPermissionRationale for user " + userId);
5406        }
5407
5408        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5409        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5410            return false;
5411        }
5412
5413        if (checkPermission(permissionName, packageName, userId)
5414                == PackageManager.PERMISSION_GRANTED) {
5415            return false;
5416        }
5417
5418        final int flags;
5419
5420        final long identity = Binder.clearCallingIdentity();
5421        try {
5422            flags = getPermissionFlags(permissionName,
5423                    packageName, userId);
5424        } finally {
5425            Binder.restoreCallingIdentity(identity);
5426        }
5427
5428        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5429                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5430                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5431
5432        if ((flags & fixedFlags) != 0) {
5433            return false;
5434        }
5435
5436        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5437    }
5438
5439    @Override
5440    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5441        mContext.enforceCallingOrSelfPermission(
5442                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5443                "addOnPermissionsChangeListener");
5444
5445        synchronized (mPackages) {
5446            mOnPermissionChangeListeners.addListenerLocked(listener);
5447        }
5448    }
5449
5450    @Override
5451    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5452        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5453            throw new SecurityException("Instant applications don't have access to this method");
5454        }
5455        synchronized (mPackages) {
5456            mOnPermissionChangeListeners.removeListenerLocked(listener);
5457        }
5458    }
5459
5460    @Override
5461    public boolean isProtectedBroadcast(String actionName) {
5462        // allow instant applications
5463        synchronized (mProtectedBroadcasts) {
5464            if (mProtectedBroadcasts.contains(actionName)) {
5465                return true;
5466            } else if (actionName != null) {
5467                // TODO: remove these terrible hacks
5468                if (actionName.startsWith("android.net.netmon.lingerExpired")
5469                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5470                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5471                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5472                    return true;
5473                }
5474            }
5475        }
5476        return false;
5477    }
5478
5479    @Override
5480    public int checkSignatures(String pkg1, String pkg2) {
5481        synchronized (mPackages) {
5482            final PackageParser.Package p1 = mPackages.get(pkg1);
5483            final PackageParser.Package p2 = mPackages.get(pkg2);
5484            if (p1 == null || p1.mExtras == null
5485                    || p2 == null || p2.mExtras == null) {
5486                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5487            }
5488            final int callingUid = Binder.getCallingUid();
5489            final int callingUserId = UserHandle.getUserId(callingUid);
5490            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5491            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5492            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5493                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5494                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5495            }
5496            return compareSignatures(p1.mSignatures, p2.mSignatures);
5497        }
5498    }
5499
5500    @Override
5501    public int checkUidSignatures(int uid1, int uid2) {
5502        final int callingUid = Binder.getCallingUid();
5503        final int callingUserId = UserHandle.getUserId(callingUid);
5504        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5505        // Map to base uids.
5506        uid1 = UserHandle.getAppId(uid1);
5507        uid2 = UserHandle.getAppId(uid2);
5508        // reader
5509        synchronized (mPackages) {
5510            Signature[] s1;
5511            Signature[] s2;
5512            Object obj = mSettings.getUserIdLPr(uid1);
5513            if (obj != null) {
5514                if (obj instanceof SharedUserSetting) {
5515                    if (isCallerInstantApp) {
5516                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5517                    }
5518                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5519                } else if (obj instanceof PackageSetting) {
5520                    final PackageSetting ps = (PackageSetting) obj;
5521                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5522                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5523                    }
5524                    s1 = ps.signatures.mSignatures;
5525                } else {
5526                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5527                }
5528            } else {
5529                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5530            }
5531            obj = mSettings.getUserIdLPr(uid2);
5532            if (obj != null) {
5533                if (obj instanceof SharedUserSetting) {
5534                    if (isCallerInstantApp) {
5535                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5536                    }
5537                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5538                } else if (obj instanceof PackageSetting) {
5539                    final PackageSetting ps = (PackageSetting) obj;
5540                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5541                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5542                    }
5543                    s2 = ps.signatures.mSignatures;
5544                } else {
5545                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5546                }
5547            } else {
5548                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5549            }
5550            return compareSignatures(s1, s2);
5551        }
5552    }
5553
5554    /**
5555     * This method should typically only be used when granting or revoking
5556     * permissions, since the app may immediately restart after this call.
5557     * <p>
5558     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5559     * guard your work against the app being relaunched.
5560     */
5561    private void killUid(int appId, int userId, String reason) {
5562        final long identity = Binder.clearCallingIdentity();
5563        try {
5564            IActivityManager am = ActivityManager.getService();
5565            if (am != null) {
5566                try {
5567                    am.killUid(appId, userId, reason);
5568                } catch (RemoteException e) {
5569                    /* ignore - same process */
5570                }
5571            }
5572        } finally {
5573            Binder.restoreCallingIdentity(identity);
5574        }
5575    }
5576
5577    /**
5578     * Compares two sets of signatures. Returns:
5579     * <br />
5580     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5581     * <br />
5582     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5583     * <br />
5584     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5585     * <br />
5586     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5587     * <br />
5588     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5589     */
5590    public static int compareSignatures(Signature[] s1, Signature[] s2) {
5591        if (s1 == null) {
5592            return s2 == null
5593                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5594                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5595        }
5596
5597        if (s2 == null) {
5598            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5599        }
5600
5601        if (s1.length != s2.length) {
5602            return PackageManager.SIGNATURE_NO_MATCH;
5603        }
5604
5605        // Since both signature sets are of size 1, we can compare without HashSets.
5606        if (s1.length == 1) {
5607            return s1[0].equals(s2[0]) ?
5608                    PackageManager.SIGNATURE_MATCH :
5609                    PackageManager.SIGNATURE_NO_MATCH;
5610        }
5611
5612        ArraySet<Signature> set1 = new ArraySet<Signature>();
5613        for (Signature sig : s1) {
5614            set1.add(sig);
5615        }
5616        ArraySet<Signature> set2 = new ArraySet<Signature>();
5617        for (Signature sig : s2) {
5618            set2.add(sig);
5619        }
5620        // Make sure s2 contains all signatures in s1.
5621        if (set1.equals(set2)) {
5622            return PackageManager.SIGNATURE_MATCH;
5623        }
5624        return PackageManager.SIGNATURE_NO_MATCH;
5625    }
5626
5627    /**
5628     * If the database version for this type of package (internal storage or
5629     * external storage) is less than the version where package signatures
5630     * were updated, return true.
5631     */
5632    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5633        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5634        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5635    }
5636
5637    /**
5638     * Used for backward compatibility to make sure any packages with
5639     * certificate chains get upgraded to the new style. {@code existingSigs}
5640     * will be in the old format (since they were stored on disk from before the
5641     * system upgrade) and {@code scannedSigs} will be in the newer format.
5642     */
5643    private int compareSignaturesCompat(PackageSignatures existingSigs,
5644            PackageParser.Package scannedPkg) {
5645        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5646            return PackageManager.SIGNATURE_NO_MATCH;
5647        }
5648
5649        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5650        for (Signature sig : existingSigs.mSignatures) {
5651            existingSet.add(sig);
5652        }
5653        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5654        for (Signature sig : scannedPkg.mSignatures) {
5655            try {
5656                Signature[] chainSignatures = sig.getChainSignatures();
5657                for (Signature chainSig : chainSignatures) {
5658                    scannedCompatSet.add(chainSig);
5659                }
5660            } catch (CertificateEncodingException e) {
5661                scannedCompatSet.add(sig);
5662            }
5663        }
5664        /*
5665         * Make sure the expanded scanned set contains all signatures in the
5666         * existing one.
5667         */
5668        if (scannedCompatSet.equals(existingSet)) {
5669            // Migrate the old signatures to the new scheme.
5670            existingSigs.assignSignatures(scannedPkg.mSignatures);
5671            // The new KeySets will be re-added later in the scanning process.
5672            synchronized (mPackages) {
5673                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5674            }
5675            return PackageManager.SIGNATURE_MATCH;
5676        }
5677        return PackageManager.SIGNATURE_NO_MATCH;
5678    }
5679
5680    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5681        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5682        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5683    }
5684
5685    private int compareSignaturesRecover(PackageSignatures existingSigs,
5686            PackageParser.Package scannedPkg) {
5687        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5688            return PackageManager.SIGNATURE_NO_MATCH;
5689        }
5690
5691        String msg = null;
5692        try {
5693            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5694                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5695                        + scannedPkg.packageName);
5696                return PackageManager.SIGNATURE_MATCH;
5697            }
5698        } catch (CertificateException e) {
5699            msg = e.getMessage();
5700        }
5701
5702        logCriticalInfo(Log.INFO,
5703                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5704        return PackageManager.SIGNATURE_NO_MATCH;
5705    }
5706
5707    @Override
5708    public List<String> getAllPackages() {
5709        final int callingUid = Binder.getCallingUid();
5710        final int callingUserId = UserHandle.getUserId(callingUid);
5711        synchronized (mPackages) {
5712            if (canViewInstantApps(callingUid, callingUserId)) {
5713                return new ArrayList<String>(mPackages.keySet());
5714            }
5715            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5716            final List<String> result = new ArrayList<>();
5717            if (instantAppPkgName != null) {
5718                // caller is an instant application; filter unexposed applications
5719                for (PackageParser.Package pkg : mPackages.values()) {
5720                    if (!pkg.visibleToInstantApps) {
5721                        continue;
5722                    }
5723                    result.add(pkg.packageName);
5724                }
5725            } else {
5726                // caller is a normal application; filter instant applications
5727                for (PackageParser.Package pkg : mPackages.values()) {
5728                    final PackageSetting ps =
5729                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5730                    if (ps != null
5731                            && ps.getInstantApp(callingUserId)
5732                            && !mInstantAppRegistry.isInstantAccessGranted(
5733                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5734                        continue;
5735                    }
5736                    result.add(pkg.packageName);
5737                }
5738            }
5739            return result;
5740        }
5741    }
5742
5743    @Override
5744    public String[] getPackagesForUid(int uid) {
5745        final int callingUid = Binder.getCallingUid();
5746        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5747        final int userId = UserHandle.getUserId(uid);
5748        uid = UserHandle.getAppId(uid);
5749        // reader
5750        synchronized (mPackages) {
5751            Object obj = mSettings.getUserIdLPr(uid);
5752            if (obj instanceof SharedUserSetting) {
5753                if (isCallerInstantApp) {
5754                    return null;
5755                }
5756                final SharedUserSetting sus = (SharedUserSetting) obj;
5757                final int N = sus.packages.size();
5758                String[] res = new String[N];
5759                final Iterator<PackageSetting> it = sus.packages.iterator();
5760                int i = 0;
5761                while (it.hasNext()) {
5762                    PackageSetting ps = it.next();
5763                    if (ps.getInstalled(userId)) {
5764                        res[i++] = ps.name;
5765                    } else {
5766                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5767                    }
5768                }
5769                return res;
5770            } else if (obj instanceof PackageSetting) {
5771                final PackageSetting ps = (PackageSetting) obj;
5772                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5773                    return new String[]{ps.name};
5774                }
5775            }
5776        }
5777        return null;
5778    }
5779
5780    @Override
5781    public String getNameForUid(int uid) {
5782        final int callingUid = Binder.getCallingUid();
5783        if (getInstantAppPackageName(callingUid) != null) {
5784            return null;
5785        }
5786        synchronized (mPackages) {
5787            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5788            if (obj instanceof SharedUserSetting) {
5789                final SharedUserSetting sus = (SharedUserSetting) obj;
5790                return sus.name + ":" + sus.userId;
5791            } else if (obj instanceof PackageSetting) {
5792                final PackageSetting ps = (PackageSetting) obj;
5793                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5794                    return null;
5795                }
5796                return ps.name;
5797            }
5798            return null;
5799        }
5800    }
5801
5802    @Override
5803    public String[] getNamesForUids(int[] uids) {
5804        if (uids == null || uids.length == 0) {
5805            return null;
5806        }
5807        final int callingUid = Binder.getCallingUid();
5808        if (getInstantAppPackageName(callingUid) != null) {
5809            return null;
5810        }
5811        final String[] names = new String[uids.length];
5812        synchronized (mPackages) {
5813            for (int i = uids.length - 1; i >= 0; i--) {
5814                final int uid = uids[i];
5815                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5816                if (obj instanceof SharedUserSetting) {
5817                    final SharedUserSetting sus = (SharedUserSetting) obj;
5818                    names[i] = "shared:" + sus.name;
5819                } else if (obj instanceof PackageSetting) {
5820                    final PackageSetting ps = (PackageSetting) obj;
5821                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5822                        names[i] = null;
5823                    } else {
5824                        names[i] = ps.name;
5825                    }
5826                } else {
5827                    names[i] = null;
5828                }
5829            }
5830        }
5831        return names;
5832    }
5833
5834    @Override
5835    public int getUidForSharedUser(String sharedUserName) {
5836        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5837            return -1;
5838        }
5839        if (sharedUserName == null) {
5840            return -1;
5841        }
5842        // reader
5843        synchronized (mPackages) {
5844            SharedUserSetting suid;
5845            try {
5846                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5847                if (suid != null) {
5848                    return suid.userId;
5849                }
5850            } catch (PackageManagerException ignore) {
5851                // can't happen, but, still need to catch it
5852            }
5853            return -1;
5854        }
5855    }
5856
5857    @Override
5858    public int getFlagsForUid(int uid) {
5859        final int callingUid = Binder.getCallingUid();
5860        if (getInstantAppPackageName(callingUid) != null) {
5861            return 0;
5862        }
5863        synchronized (mPackages) {
5864            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5865            if (obj instanceof SharedUserSetting) {
5866                final SharedUserSetting sus = (SharedUserSetting) obj;
5867                return sus.pkgFlags;
5868            } else if (obj instanceof PackageSetting) {
5869                final PackageSetting ps = (PackageSetting) obj;
5870                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5871                    return 0;
5872                }
5873                return ps.pkgFlags;
5874            }
5875        }
5876        return 0;
5877    }
5878
5879    @Override
5880    public int getPrivateFlagsForUid(int uid) {
5881        final int callingUid = Binder.getCallingUid();
5882        if (getInstantAppPackageName(callingUid) != null) {
5883            return 0;
5884        }
5885        synchronized (mPackages) {
5886            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5887            if (obj instanceof SharedUserSetting) {
5888                final SharedUserSetting sus = (SharedUserSetting) obj;
5889                return sus.pkgPrivateFlags;
5890            } else if (obj instanceof PackageSetting) {
5891                final PackageSetting ps = (PackageSetting) obj;
5892                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5893                    return 0;
5894                }
5895                return ps.pkgPrivateFlags;
5896            }
5897        }
5898        return 0;
5899    }
5900
5901    @Override
5902    public boolean isUidPrivileged(int uid) {
5903        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5904            return false;
5905        }
5906        uid = UserHandle.getAppId(uid);
5907        // reader
5908        synchronized (mPackages) {
5909            Object obj = mSettings.getUserIdLPr(uid);
5910            if (obj instanceof SharedUserSetting) {
5911                final SharedUserSetting sus = (SharedUserSetting) obj;
5912                final Iterator<PackageSetting> it = sus.packages.iterator();
5913                while (it.hasNext()) {
5914                    if (it.next().isPrivileged()) {
5915                        return true;
5916                    }
5917                }
5918            } else if (obj instanceof PackageSetting) {
5919                final PackageSetting ps = (PackageSetting) obj;
5920                return ps.isPrivileged();
5921            }
5922        }
5923        return false;
5924    }
5925
5926    @Override
5927    public String[] getAppOpPermissionPackages(String permName) {
5928        return mPermissionManager.getAppOpPermissionPackages(permName);
5929    }
5930
5931    @Override
5932    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5933            int flags, int userId) {
5934        return resolveIntentInternal(
5935                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5936    }
5937
5938    /**
5939     * Normally instant apps can only be resolved when they're visible to the caller.
5940     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5941     * since we need to allow the system to start any installed application.
5942     */
5943    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5944            int flags, int userId, boolean resolveForStart) {
5945        try {
5946            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5947
5948            if (!sUserManager.exists(userId)) return null;
5949            final int callingUid = Binder.getCallingUid();
5950            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5951            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5952                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5953
5954            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5955            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5956                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5957            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5958
5959            final ResolveInfo bestChoice =
5960                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5961            return bestChoice;
5962        } finally {
5963            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5964        }
5965    }
5966
5967    @Override
5968    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5969        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5970            throw new SecurityException(
5971                    "findPersistentPreferredActivity can only be run by the system");
5972        }
5973        if (!sUserManager.exists(userId)) {
5974            return null;
5975        }
5976        final int callingUid = Binder.getCallingUid();
5977        intent = updateIntentForResolve(intent);
5978        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5979        final int flags = updateFlagsForResolve(
5980                0, userId, intent, callingUid, false /*includeInstantApps*/);
5981        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5982                userId);
5983        synchronized (mPackages) {
5984            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5985                    userId);
5986        }
5987    }
5988
5989    @Override
5990    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5991            IntentFilter filter, int match, ComponentName activity) {
5992        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5993            return;
5994        }
5995        final int userId = UserHandle.getCallingUserId();
5996        if (DEBUG_PREFERRED) {
5997            Log.v(TAG, "setLastChosenActivity intent=" + intent
5998                + " resolvedType=" + resolvedType
5999                + " flags=" + flags
6000                + " filter=" + filter
6001                + " match=" + match
6002                + " activity=" + activity);
6003            filter.dump(new PrintStreamPrinter(System.out), "    ");
6004        }
6005        intent.setComponent(null);
6006        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6007                userId);
6008        // Find any earlier preferred or last chosen entries and nuke them
6009        findPreferredActivity(intent, resolvedType,
6010                flags, query, 0, false, true, false, userId);
6011        // Add the new activity as the last chosen for this filter
6012        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6013                "Setting last chosen");
6014    }
6015
6016    @Override
6017    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6018        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6019            return null;
6020        }
6021        final int userId = UserHandle.getCallingUserId();
6022        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6023        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6024                userId);
6025        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6026                false, false, false, userId);
6027    }
6028
6029    /**
6030     * Returns whether or not instant apps have been disabled remotely.
6031     */
6032    private boolean isEphemeralDisabled() {
6033        return mEphemeralAppsDisabled;
6034    }
6035
6036    private boolean isInstantAppAllowed(
6037            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6038            boolean skipPackageCheck) {
6039        if (mInstantAppResolverConnection == null) {
6040            return false;
6041        }
6042        if (mInstantAppInstallerActivity == null) {
6043            return false;
6044        }
6045        if (intent.getComponent() != null) {
6046            return false;
6047        }
6048        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6049            return false;
6050        }
6051        if (!skipPackageCheck && intent.getPackage() != null) {
6052            return false;
6053        }
6054        final boolean isWebUri = hasWebURI(intent);
6055        if (!isWebUri || intent.getData().getHost() == null) {
6056            return false;
6057        }
6058        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6059        // Or if there's already an ephemeral app installed that handles the action
6060        synchronized (mPackages) {
6061            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6062            for (int n = 0; n < count; n++) {
6063                final ResolveInfo info = resolvedActivities.get(n);
6064                final String packageName = info.activityInfo.packageName;
6065                final PackageSetting ps = mSettings.mPackages.get(packageName);
6066                if (ps != null) {
6067                    // only check domain verification status if the app is not a browser
6068                    if (!info.handleAllWebDataURI) {
6069                        // Try to get the status from User settings first
6070                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6071                        final int status = (int) (packedStatus >> 32);
6072                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6073                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6074                            if (DEBUG_EPHEMERAL) {
6075                                Slog.v(TAG, "DENY instant app;"
6076                                    + " pkg: " + packageName + ", status: " + status);
6077                            }
6078                            return false;
6079                        }
6080                    }
6081                    if (ps.getInstantApp(userId)) {
6082                        if (DEBUG_EPHEMERAL) {
6083                            Slog.v(TAG, "DENY instant app installed;"
6084                                    + " pkg: " + packageName);
6085                        }
6086                        return false;
6087                    }
6088                }
6089            }
6090        }
6091        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6092        return true;
6093    }
6094
6095    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6096            Intent origIntent, String resolvedType, String callingPackage,
6097            Bundle verificationBundle, int userId) {
6098        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6099                new InstantAppRequest(responseObj, origIntent, resolvedType,
6100                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6101        mHandler.sendMessage(msg);
6102    }
6103
6104    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6105            int flags, List<ResolveInfo> query, int userId) {
6106        if (query != null) {
6107            final int N = query.size();
6108            if (N == 1) {
6109                return query.get(0);
6110            } else if (N > 1) {
6111                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6112                // If there is more than one activity with the same priority,
6113                // then let the user decide between them.
6114                ResolveInfo r0 = query.get(0);
6115                ResolveInfo r1 = query.get(1);
6116                if (DEBUG_INTENT_MATCHING || debug) {
6117                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6118                            + r1.activityInfo.name + "=" + r1.priority);
6119                }
6120                // If the first activity has a higher priority, or a different
6121                // default, then it is always desirable to pick it.
6122                if (r0.priority != r1.priority
6123                        || r0.preferredOrder != r1.preferredOrder
6124                        || r0.isDefault != r1.isDefault) {
6125                    return query.get(0);
6126                }
6127                // If we have saved a preference for a preferred activity for
6128                // this Intent, use that.
6129                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6130                        flags, query, r0.priority, true, false, debug, userId);
6131                if (ri != null) {
6132                    return ri;
6133                }
6134                // If we have an ephemeral app, use it
6135                for (int i = 0; i < N; i++) {
6136                    ri = query.get(i);
6137                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6138                        final String packageName = ri.activityInfo.packageName;
6139                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6140                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6141                        final int status = (int)(packedStatus >> 32);
6142                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6143                            return ri;
6144                        }
6145                    }
6146                }
6147                ri = new ResolveInfo(mResolveInfo);
6148                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6149                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6150                // If all of the options come from the same package, show the application's
6151                // label and icon instead of the generic resolver's.
6152                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6153                // and then throw away the ResolveInfo itself, meaning that the caller loses
6154                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6155                // a fallback for this case; we only set the target package's resources on
6156                // the ResolveInfo, not the ActivityInfo.
6157                final String intentPackage = intent.getPackage();
6158                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6159                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6160                    ri.resolvePackageName = intentPackage;
6161                    if (userNeedsBadging(userId)) {
6162                        ri.noResourceId = true;
6163                    } else {
6164                        ri.icon = appi.icon;
6165                    }
6166                    ri.iconResourceId = appi.icon;
6167                    ri.labelRes = appi.labelRes;
6168                }
6169                ri.activityInfo.applicationInfo = new ApplicationInfo(
6170                        ri.activityInfo.applicationInfo);
6171                if (userId != 0) {
6172                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6173                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6174                }
6175                // Make sure that the resolver is displayable in car mode
6176                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6177                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6178                return ri;
6179            }
6180        }
6181        return null;
6182    }
6183
6184    /**
6185     * Return true if the given list is not empty and all of its contents have
6186     * an activityInfo with the given package name.
6187     */
6188    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6189        if (ArrayUtils.isEmpty(list)) {
6190            return false;
6191        }
6192        for (int i = 0, N = list.size(); i < N; i++) {
6193            final ResolveInfo ri = list.get(i);
6194            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6195            if (ai == null || !packageName.equals(ai.packageName)) {
6196                return false;
6197            }
6198        }
6199        return true;
6200    }
6201
6202    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6203            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6204        final int N = query.size();
6205        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6206                .get(userId);
6207        // Get the list of persistent preferred activities that handle the intent
6208        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6209        List<PersistentPreferredActivity> pprefs = ppir != null
6210                ? ppir.queryIntent(intent, resolvedType,
6211                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6212                        userId)
6213                : null;
6214        if (pprefs != null && pprefs.size() > 0) {
6215            final int M = pprefs.size();
6216            for (int i=0; i<M; i++) {
6217                final PersistentPreferredActivity ppa = pprefs.get(i);
6218                if (DEBUG_PREFERRED || debug) {
6219                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6220                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6221                            + "\n  component=" + ppa.mComponent);
6222                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6223                }
6224                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6225                        flags | MATCH_DISABLED_COMPONENTS, userId);
6226                if (DEBUG_PREFERRED || debug) {
6227                    Slog.v(TAG, "Found persistent preferred activity:");
6228                    if (ai != null) {
6229                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6230                    } else {
6231                        Slog.v(TAG, "  null");
6232                    }
6233                }
6234                if (ai == null) {
6235                    // This previously registered persistent preferred activity
6236                    // component is no longer known. Ignore it and do NOT remove it.
6237                    continue;
6238                }
6239                for (int j=0; j<N; j++) {
6240                    final ResolveInfo ri = query.get(j);
6241                    if (!ri.activityInfo.applicationInfo.packageName
6242                            .equals(ai.applicationInfo.packageName)) {
6243                        continue;
6244                    }
6245                    if (!ri.activityInfo.name.equals(ai.name)) {
6246                        continue;
6247                    }
6248                    //  Found a persistent preference that can handle the intent.
6249                    if (DEBUG_PREFERRED || debug) {
6250                        Slog.v(TAG, "Returning persistent preferred activity: " +
6251                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6252                    }
6253                    return ri;
6254                }
6255            }
6256        }
6257        return null;
6258    }
6259
6260    // TODO: handle preferred activities missing while user has amnesia
6261    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6262            List<ResolveInfo> query, int priority, boolean always,
6263            boolean removeMatches, boolean debug, int userId) {
6264        if (!sUserManager.exists(userId)) return null;
6265        final int callingUid = Binder.getCallingUid();
6266        flags = updateFlagsForResolve(
6267                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6268        intent = updateIntentForResolve(intent);
6269        // writer
6270        synchronized (mPackages) {
6271            // Try to find a matching persistent preferred activity.
6272            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6273                    debug, userId);
6274
6275            // If a persistent preferred activity matched, use it.
6276            if (pri != null) {
6277                return pri;
6278            }
6279
6280            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6281            // Get the list of preferred activities that handle the intent
6282            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6283            List<PreferredActivity> prefs = pir != null
6284                    ? pir.queryIntent(intent, resolvedType,
6285                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6286                            userId)
6287                    : null;
6288            if (prefs != null && prefs.size() > 0) {
6289                boolean changed = false;
6290                try {
6291                    // First figure out how good the original match set is.
6292                    // We will only allow preferred activities that came
6293                    // from the same match quality.
6294                    int match = 0;
6295
6296                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6297
6298                    final int N = query.size();
6299                    for (int j=0; j<N; j++) {
6300                        final ResolveInfo ri = query.get(j);
6301                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6302                                + ": 0x" + Integer.toHexString(match));
6303                        if (ri.match > match) {
6304                            match = ri.match;
6305                        }
6306                    }
6307
6308                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6309                            + Integer.toHexString(match));
6310
6311                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6312                    final int M = prefs.size();
6313                    for (int i=0; i<M; i++) {
6314                        final PreferredActivity pa = prefs.get(i);
6315                        if (DEBUG_PREFERRED || debug) {
6316                            Slog.v(TAG, "Checking PreferredActivity ds="
6317                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6318                                    + "\n  component=" + pa.mPref.mComponent);
6319                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6320                        }
6321                        if (pa.mPref.mMatch != match) {
6322                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6323                                    + Integer.toHexString(pa.mPref.mMatch));
6324                            continue;
6325                        }
6326                        // If it's not an "always" type preferred activity and that's what we're
6327                        // looking for, skip it.
6328                        if (always && !pa.mPref.mAlways) {
6329                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6330                            continue;
6331                        }
6332                        final ActivityInfo ai = getActivityInfo(
6333                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6334                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6335                                userId);
6336                        if (DEBUG_PREFERRED || debug) {
6337                            Slog.v(TAG, "Found preferred activity:");
6338                            if (ai != null) {
6339                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6340                            } else {
6341                                Slog.v(TAG, "  null");
6342                            }
6343                        }
6344                        if (ai == null) {
6345                            // This previously registered preferred activity
6346                            // component is no longer known.  Most likely an update
6347                            // to the app was installed and in the new version this
6348                            // component no longer exists.  Clean it up by removing
6349                            // it from the preferred activities list, and skip it.
6350                            Slog.w(TAG, "Removing dangling preferred activity: "
6351                                    + pa.mPref.mComponent);
6352                            pir.removeFilter(pa);
6353                            changed = true;
6354                            continue;
6355                        }
6356                        for (int j=0; j<N; j++) {
6357                            final ResolveInfo ri = query.get(j);
6358                            if (!ri.activityInfo.applicationInfo.packageName
6359                                    .equals(ai.applicationInfo.packageName)) {
6360                                continue;
6361                            }
6362                            if (!ri.activityInfo.name.equals(ai.name)) {
6363                                continue;
6364                            }
6365
6366                            if (removeMatches) {
6367                                pir.removeFilter(pa);
6368                                changed = true;
6369                                if (DEBUG_PREFERRED) {
6370                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6371                                }
6372                                break;
6373                            }
6374
6375                            // Okay we found a previously set preferred or last chosen app.
6376                            // If the result set is different from when this
6377                            // was created, and is not a subset of the preferred set, we need to
6378                            // clear it and re-ask the user their preference, if we're looking for
6379                            // an "always" type entry.
6380                            if (always && !pa.mPref.sameSet(query)) {
6381                                if (pa.mPref.isSuperset(query)) {
6382                                    // some components of the set are no longer present in
6383                                    // the query, but the preferred activity can still be reused
6384                                    if (DEBUG_PREFERRED) {
6385                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6386                                                + " still valid as only non-preferred components"
6387                                                + " were removed for " + intent + " type "
6388                                                + resolvedType);
6389                                    }
6390                                    // remove obsolete components and re-add the up-to-date filter
6391                                    PreferredActivity freshPa = new PreferredActivity(pa,
6392                                            pa.mPref.mMatch,
6393                                            pa.mPref.discardObsoleteComponents(query),
6394                                            pa.mPref.mComponent,
6395                                            pa.mPref.mAlways);
6396                                    pir.removeFilter(pa);
6397                                    pir.addFilter(freshPa);
6398                                    changed = true;
6399                                } else {
6400                                    Slog.i(TAG,
6401                                            "Result set changed, dropping preferred activity for "
6402                                                    + intent + " type " + resolvedType);
6403                                    if (DEBUG_PREFERRED) {
6404                                        Slog.v(TAG, "Removing preferred activity since set changed "
6405                                                + pa.mPref.mComponent);
6406                                    }
6407                                    pir.removeFilter(pa);
6408                                    // Re-add the filter as a "last chosen" entry (!always)
6409                                    PreferredActivity lastChosen = new PreferredActivity(
6410                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6411                                    pir.addFilter(lastChosen);
6412                                    changed = true;
6413                                    return null;
6414                                }
6415                            }
6416
6417                            // Yay! Either the set matched or we're looking for the last chosen
6418                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6419                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6420                            return ri;
6421                        }
6422                    }
6423                } finally {
6424                    if (changed) {
6425                        if (DEBUG_PREFERRED) {
6426                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6427                        }
6428                        scheduleWritePackageRestrictionsLocked(userId);
6429                    }
6430                }
6431            }
6432        }
6433        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6434        return null;
6435    }
6436
6437    /*
6438     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6439     */
6440    @Override
6441    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6442            int targetUserId) {
6443        mContext.enforceCallingOrSelfPermission(
6444                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6445        List<CrossProfileIntentFilter> matches =
6446                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6447        if (matches != null) {
6448            int size = matches.size();
6449            for (int i = 0; i < size; i++) {
6450                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6451            }
6452        }
6453        if (hasWebURI(intent)) {
6454            // cross-profile app linking works only towards the parent.
6455            final int callingUid = Binder.getCallingUid();
6456            final UserInfo parent = getProfileParent(sourceUserId);
6457            synchronized(mPackages) {
6458                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6459                        false /*includeInstantApps*/);
6460                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6461                        intent, resolvedType, flags, sourceUserId, parent.id);
6462                return xpDomainInfo != null;
6463            }
6464        }
6465        return false;
6466    }
6467
6468    private UserInfo getProfileParent(int userId) {
6469        final long identity = Binder.clearCallingIdentity();
6470        try {
6471            return sUserManager.getProfileParent(userId);
6472        } finally {
6473            Binder.restoreCallingIdentity(identity);
6474        }
6475    }
6476
6477    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6478            String resolvedType, int userId) {
6479        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6480        if (resolver != null) {
6481            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6482        }
6483        return null;
6484    }
6485
6486    @Override
6487    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6488            String resolvedType, int flags, int userId) {
6489        try {
6490            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6491
6492            return new ParceledListSlice<>(
6493                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6494        } finally {
6495            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6496        }
6497    }
6498
6499    /**
6500     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6501     * instant, returns {@code null}.
6502     */
6503    private String getInstantAppPackageName(int callingUid) {
6504        synchronized (mPackages) {
6505            // If the caller is an isolated app use the owner's uid for the lookup.
6506            if (Process.isIsolated(callingUid)) {
6507                callingUid = mIsolatedOwners.get(callingUid);
6508            }
6509            final int appId = UserHandle.getAppId(callingUid);
6510            final Object obj = mSettings.getUserIdLPr(appId);
6511            if (obj instanceof PackageSetting) {
6512                final PackageSetting ps = (PackageSetting) obj;
6513                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6514                return isInstantApp ? ps.pkg.packageName : null;
6515            }
6516        }
6517        return null;
6518    }
6519
6520    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6521            String resolvedType, int flags, int userId) {
6522        return queryIntentActivitiesInternal(
6523                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6524                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6525    }
6526
6527    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6528            String resolvedType, int flags, int filterCallingUid, int userId,
6529            boolean resolveForStart, boolean allowDynamicSplits) {
6530        if (!sUserManager.exists(userId)) return Collections.emptyList();
6531        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6532        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6533                false /* requireFullPermission */, false /* checkShell */,
6534                "query intent activities");
6535        final String pkgName = intent.getPackage();
6536        ComponentName comp = intent.getComponent();
6537        if (comp == null) {
6538            if (intent.getSelector() != null) {
6539                intent = intent.getSelector();
6540                comp = intent.getComponent();
6541            }
6542        }
6543
6544        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6545                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6546        if (comp != null) {
6547            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6548            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6549            if (ai != null) {
6550                // When specifying an explicit component, we prevent the activity from being
6551                // used when either 1) the calling package is normal and the activity is within
6552                // an ephemeral application or 2) the calling package is ephemeral and the
6553                // activity is not visible to ephemeral applications.
6554                final boolean matchInstantApp =
6555                        (flags & PackageManager.MATCH_INSTANT) != 0;
6556                final boolean matchVisibleToInstantAppOnly =
6557                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6558                final boolean matchExplicitlyVisibleOnly =
6559                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6560                final boolean isCallerInstantApp =
6561                        instantAppPkgName != null;
6562                final boolean isTargetSameInstantApp =
6563                        comp.getPackageName().equals(instantAppPkgName);
6564                final boolean isTargetInstantApp =
6565                        (ai.applicationInfo.privateFlags
6566                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6567                final boolean isTargetVisibleToInstantApp =
6568                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6569                final boolean isTargetExplicitlyVisibleToInstantApp =
6570                        isTargetVisibleToInstantApp
6571                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6572                final boolean isTargetHiddenFromInstantApp =
6573                        !isTargetVisibleToInstantApp
6574                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6575                final boolean blockResolution =
6576                        !isTargetSameInstantApp
6577                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6578                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6579                                        && isTargetHiddenFromInstantApp));
6580                if (!blockResolution) {
6581                    final ResolveInfo ri = new ResolveInfo();
6582                    ri.activityInfo = ai;
6583                    list.add(ri);
6584                }
6585            }
6586            return applyPostResolutionFilter(
6587                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6588        }
6589
6590        // reader
6591        boolean sortResult = false;
6592        boolean addEphemeral = false;
6593        List<ResolveInfo> result;
6594        final boolean ephemeralDisabled = isEphemeralDisabled();
6595        synchronized (mPackages) {
6596            if (pkgName == null) {
6597                List<CrossProfileIntentFilter> matchingFilters =
6598                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6599                // Check for results that need to skip the current profile.
6600                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6601                        resolvedType, flags, userId);
6602                if (xpResolveInfo != null) {
6603                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6604                    xpResult.add(xpResolveInfo);
6605                    return applyPostResolutionFilter(
6606                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6607                            allowDynamicSplits, filterCallingUid, userId);
6608                }
6609
6610                // Check for results in the current profile.
6611                result = filterIfNotSystemUser(mActivities.queryIntent(
6612                        intent, resolvedType, flags, userId), userId);
6613                addEphemeral = !ephemeralDisabled
6614                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6615                // Check for cross profile results.
6616                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6617                xpResolveInfo = queryCrossProfileIntents(
6618                        matchingFilters, intent, resolvedType, flags, userId,
6619                        hasNonNegativePriorityResult);
6620                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6621                    boolean isVisibleToUser = filterIfNotSystemUser(
6622                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6623                    if (isVisibleToUser) {
6624                        result.add(xpResolveInfo);
6625                        sortResult = true;
6626                    }
6627                }
6628                if (hasWebURI(intent)) {
6629                    CrossProfileDomainInfo xpDomainInfo = null;
6630                    final UserInfo parent = getProfileParent(userId);
6631                    if (parent != null) {
6632                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6633                                flags, userId, parent.id);
6634                    }
6635                    if (xpDomainInfo != null) {
6636                        if (xpResolveInfo != null) {
6637                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6638                            // in the result.
6639                            result.remove(xpResolveInfo);
6640                        }
6641                        if (result.size() == 0 && !addEphemeral) {
6642                            // No result in current profile, but found candidate in parent user.
6643                            // And we are not going to add emphemeral app, so we can return the
6644                            // result straight away.
6645                            result.add(xpDomainInfo.resolveInfo);
6646                            return applyPostResolutionFilter(result, instantAppPkgName,
6647                                    allowDynamicSplits, filterCallingUid, userId);
6648                        }
6649                    } else if (result.size() <= 1 && !addEphemeral) {
6650                        // No result in parent user and <= 1 result in current profile, and we
6651                        // are not going to add emphemeral app, so we can return the result without
6652                        // further processing.
6653                        return applyPostResolutionFilter(result, instantAppPkgName,
6654                                allowDynamicSplits, filterCallingUid, userId);
6655                    }
6656                    // We have more than one candidate (combining results from current and parent
6657                    // profile), so we need filtering and sorting.
6658                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6659                            intent, flags, result, xpDomainInfo, userId);
6660                    sortResult = true;
6661                }
6662            } else {
6663                final PackageParser.Package pkg = mPackages.get(pkgName);
6664                result = null;
6665                if (pkg != null) {
6666                    result = filterIfNotSystemUser(
6667                            mActivities.queryIntentForPackage(
6668                                    intent, resolvedType, flags, pkg.activities, userId),
6669                            userId);
6670                }
6671                if (result == null || result.size() == 0) {
6672                    // the caller wants to resolve for a particular package; however, there
6673                    // were no installed results, so, try to find an ephemeral result
6674                    addEphemeral = !ephemeralDisabled
6675                            && isInstantAppAllowed(
6676                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6677                    if (result == null) {
6678                        result = new ArrayList<>();
6679                    }
6680                }
6681            }
6682        }
6683        if (addEphemeral) {
6684            result = maybeAddInstantAppInstaller(
6685                    result, intent, resolvedType, flags, userId, resolveForStart);
6686        }
6687        if (sortResult) {
6688            Collections.sort(result, mResolvePrioritySorter);
6689        }
6690        return applyPostResolutionFilter(
6691                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6692    }
6693
6694    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6695            String resolvedType, int flags, int userId, boolean resolveForStart) {
6696        // first, check to see if we've got an instant app already installed
6697        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6698        ResolveInfo localInstantApp = null;
6699        boolean blockResolution = false;
6700        if (!alreadyResolvedLocally) {
6701            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6702                    flags
6703                        | PackageManager.GET_RESOLVED_FILTER
6704                        | PackageManager.MATCH_INSTANT
6705                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6706                    userId);
6707            for (int i = instantApps.size() - 1; i >= 0; --i) {
6708                final ResolveInfo info = instantApps.get(i);
6709                final String packageName = info.activityInfo.packageName;
6710                final PackageSetting ps = mSettings.mPackages.get(packageName);
6711                if (ps.getInstantApp(userId)) {
6712                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6713                    final int status = (int)(packedStatus >> 32);
6714                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6715                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6716                        // there's a local instant application installed, but, the user has
6717                        // chosen to never use it; skip resolution and don't acknowledge
6718                        // an instant application is even available
6719                        if (DEBUG_EPHEMERAL) {
6720                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6721                        }
6722                        blockResolution = true;
6723                        break;
6724                    } else {
6725                        // we have a locally installed instant application; skip resolution
6726                        // but acknowledge there's an instant application available
6727                        if (DEBUG_EPHEMERAL) {
6728                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6729                        }
6730                        localInstantApp = info;
6731                        break;
6732                    }
6733                }
6734            }
6735        }
6736        // no app installed, let's see if one's available
6737        AuxiliaryResolveInfo auxiliaryResponse = null;
6738        if (!blockResolution) {
6739            if (localInstantApp == null) {
6740                // we don't have an instant app locally, resolve externally
6741                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6742                final InstantAppRequest requestObject = new InstantAppRequest(
6743                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6744                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6745                        resolveForStart);
6746                auxiliaryResponse =
6747                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6748                                mContext, mInstantAppResolverConnection, requestObject);
6749                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6750            } else {
6751                // we have an instant application locally, but, we can't admit that since
6752                // callers shouldn't be able to determine prior browsing. create a dummy
6753                // auxiliary response so the downstream code behaves as if there's an
6754                // instant application available externally. when it comes time to start
6755                // the instant application, we'll do the right thing.
6756                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6757                auxiliaryResponse = new AuxiliaryResolveInfo(
6758                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6759                        ai.versionCode, null /*failureIntent*/);
6760            }
6761        }
6762        if (auxiliaryResponse != null) {
6763            if (DEBUG_EPHEMERAL) {
6764                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6765            }
6766            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6767            final PackageSetting ps =
6768                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6769            if (ps != null) {
6770                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6771                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6772                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6773                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6774                // make sure this resolver is the default
6775                ephemeralInstaller.isDefault = true;
6776                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6777                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6778                // add a non-generic filter
6779                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6780                ephemeralInstaller.filter.addDataPath(
6781                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6782                ephemeralInstaller.isInstantAppAvailable = true;
6783                result.add(ephemeralInstaller);
6784            }
6785        }
6786        return result;
6787    }
6788
6789    private static class CrossProfileDomainInfo {
6790        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6791        ResolveInfo resolveInfo;
6792        /* Best domain verification status of the activities found in the other profile */
6793        int bestDomainVerificationStatus;
6794    }
6795
6796    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6797            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6798        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6799                sourceUserId)) {
6800            return null;
6801        }
6802        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6803                resolvedType, flags, parentUserId);
6804
6805        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6806            return null;
6807        }
6808        CrossProfileDomainInfo result = null;
6809        int size = resultTargetUser.size();
6810        for (int i = 0; i < size; i++) {
6811            ResolveInfo riTargetUser = resultTargetUser.get(i);
6812            // Intent filter verification is only for filters that specify a host. So don't return
6813            // those that handle all web uris.
6814            if (riTargetUser.handleAllWebDataURI) {
6815                continue;
6816            }
6817            String packageName = riTargetUser.activityInfo.packageName;
6818            PackageSetting ps = mSettings.mPackages.get(packageName);
6819            if (ps == null) {
6820                continue;
6821            }
6822            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6823            int status = (int)(verificationState >> 32);
6824            if (result == null) {
6825                result = new CrossProfileDomainInfo();
6826                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6827                        sourceUserId, parentUserId);
6828                result.bestDomainVerificationStatus = status;
6829            } else {
6830                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6831                        result.bestDomainVerificationStatus);
6832            }
6833        }
6834        // Don't consider matches with status NEVER across profiles.
6835        if (result != null && result.bestDomainVerificationStatus
6836                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6837            return null;
6838        }
6839        return result;
6840    }
6841
6842    /**
6843     * Verification statuses are ordered from the worse to the best, except for
6844     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6845     */
6846    private int bestDomainVerificationStatus(int status1, int status2) {
6847        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6848            return status2;
6849        }
6850        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6851            return status1;
6852        }
6853        return (int) MathUtils.max(status1, status2);
6854    }
6855
6856    private boolean isUserEnabled(int userId) {
6857        long callingId = Binder.clearCallingIdentity();
6858        try {
6859            UserInfo userInfo = sUserManager.getUserInfo(userId);
6860            return userInfo != null && userInfo.isEnabled();
6861        } finally {
6862            Binder.restoreCallingIdentity(callingId);
6863        }
6864    }
6865
6866    /**
6867     * Filter out activities with systemUserOnly flag set, when current user is not System.
6868     *
6869     * @return filtered list
6870     */
6871    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6872        if (userId == UserHandle.USER_SYSTEM) {
6873            return resolveInfos;
6874        }
6875        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6876            ResolveInfo info = resolveInfos.get(i);
6877            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6878                resolveInfos.remove(i);
6879            }
6880        }
6881        return resolveInfos;
6882    }
6883
6884    /**
6885     * Filters out ephemeral activities.
6886     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6887     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6888     *
6889     * @param resolveInfos The pre-filtered list of resolved activities
6890     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6891     *          is performed.
6892     * @return A filtered list of resolved activities.
6893     */
6894    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6895            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6896        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6897            final ResolveInfo info = resolveInfos.get(i);
6898            // allow activities that are defined in the provided package
6899            if (allowDynamicSplits
6900                    && info.activityInfo.splitName != null
6901                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6902                            info.activityInfo.splitName)) {
6903                // requested activity is defined in a split that hasn't been installed yet.
6904                // add the installer to the resolve list
6905                if (DEBUG_INSTALL) {
6906                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6907                }
6908                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6909                final ComponentName installFailureActivity = findInstallFailureActivity(
6910                        info.activityInfo.packageName,  filterCallingUid, userId);
6911                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6912                        info.activityInfo.packageName, info.activityInfo.splitName,
6913                        installFailureActivity,
6914                        info.activityInfo.applicationInfo.versionCode,
6915                        null /*failureIntent*/);
6916                // make sure this resolver is the default
6917                installerInfo.isDefault = true;
6918                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6919                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6920                // add a non-generic filter
6921                installerInfo.filter = new IntentFilter();
6922                // load resources from the correct package
6923                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6924                resolveInfos.set(i, installerInfo);
6925                continue;
6926            }
6927            // caller is a full app, don't need to apply any other filtering
6928            if (ephemeralPkgName == null) {
6929                continue;
6930            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6931                // caller is same app; don't need to apply any other filtering
6932                continue;
6933            }
6934            // allow activities that have been explicitly exposed to ephemeral apps
6935            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6936            if (!isEphemeralApp
6937                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6938                continue;
6939            }
6940            resolveInfos.remove(i);
6941        }
6942        return resolveInfos;
6943    }
6944
6945    /**
6946     * Returns the activity component that can handle install failures.
6947     * <p>By default, the instant application installer handles failures. However, an
6948     * application may want to handle failures on its own. Applications do this by
6949     * creating an activity with an intent filter that handles the action
6950     * {@link Intent#ACTION_INSTALL_FAILURE}.
6951     */
6952    private @Nullable ComponentName findInstallFailureActivity(
6953            String packageName, int filterCallingUid, int userId) {
6954        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6955        failureActivityIntent.setPackage(packageName);
6956        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6957        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6958                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6959                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6960        final int NR = result.size();
6961        if (NR > 0) {
6962            for (int i = 0; i < NR; i++) {
6963                final ResolveInfo info = result.get(i);
6964                if (info.activityInfo.splitName != null) {
6965                    continue;
6966                }
6967                return new ComponentName(packageName, info.activityInfo.name);
6968            }
6969        }
6970        return null;
6971    }
6972
6973    /**
6974     * @param resolveInfos list of resolve infos in descending priority order
6975     * @return if the list contains a resolve info with non-negative priority
6976     */
6977    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6978        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6979    }
6980
6981    private static boolean hasWebURI(Intent intent) {
6982        if (intent.getData() == null) {
6983            return false;
6984        }
6985        final String scheme = intent.getScheme();
6986        if (TextUtils.isEmpty(scheme)) {
6987            return false;
6988        }
6989        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6990    }
6991
6992    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6993            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6994            int userId) {
6995        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6996
6997        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6998            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6999                    candidates.size());
7000        }
7001
7002        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7003        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7004        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7005        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7006        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7007        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7008
7009        synchronized (mPackages) {
7010            final int count = candidates.size();
7011            // First, try to use linked apps. Partition the candidates into four lists:
7012            // one for the final results, one for the "do not use ever", one for "undefined status"
7013            // and finally one for "browser app type".
7014            for (int n=0; n<count; n++) {
7015                ResolveInfo info = candidates.get(n);
7016                String packageName = info.activityInfo.packageName;
7017                PackageSetting ps = mSettings.mPackages.get(packageName);
7018                if (ps != null) {
7019                    // Add to the special match all list (Browser use case)
7020                    if (info.handleAllWebDataURI) {
7021                        matchAllList.add(info);
7022                        continue;
7023                    }
7024                    // Try to get the status from User settings first
7025                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7026                    int status = (int)(packedStatus >> 32);
7027                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7028                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7029                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7030                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7031                                    + " : linkgen=" + linkGeneration);
7032                        }
7033                        // Use link-enabled generation as preferredOrder, i.e.
7034                        // prefer newly-enabled over earlier-enabled.
7035                        info.preferredOrder = linkGeneration;
7036                        alwaysList.add(info);
7037                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7038                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7039                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7040                        }
7041                        neverList.add(info);
7042                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7043                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7044                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7045                        }
7046                        alwaysAskList.add(info);
7047                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7048                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7049                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7050                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7051                        }
7052                        undefinedList.add(info);
7053                    }
7054                }
7055            }
7056
7057            // We'll want to include browser possibilities in a few cases
7058            boolean includeBrowser = false;
7059
7060            // First try to add the "always" resolution(s) for the current user, if any
7061            if (alwaysList.size() > 0) {
7062                result.addAll(alwaysList);
7063            } else {
7064                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7065                result.addAll(undefinedList);
7066                // Maybe add one for the other profile.
7067                if (xpDomainInfo != null && (
7068                        xpDomainInfo.bestDomainVerificationStatus
7069                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7070                    result.add(xpDomainInfo.resolveInfo);
7071                }
7072                includeBrowser = true;
7073            }
7074
7075            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7076            // If there were 'always' entries their preferred order has been set, so we also
7077            // back that off to make the alternatives equivalent
7078            if (alwaysAskList.size() > 0) {
7079                for (ResolveInfo i : result) {
7080                    i.preferredOrder = 0;
7081                }
7082                result.addAll(alwaysAskList);
7083                includeBrowser = true;
7084            }
7085
7086            if (includeBrowser) {
7087                // Also add browsers (all of them or only the default one)
7088                if (DEBUG_DOMAIN_VERIFICATION) {
7089                    Slog.v(TAG, "   ...including browsers in candidate set");
7090                }
7091                if ((matchFlags & MATCH_ALL) != 0) {
7092                    result.addAll(matchAllList);
7093                } else {
7094                    // Browser/generic handling case.  If there's a default browser, go straight
7095                    // to that (but only if there is no other higher-priority match).
7096                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7097                    int maxMatchPrio = 0;
7098                    ResolveInfo defaultBrowserMatch = null;
7099                    final int numCandidates = matchAllList.size();
7100                    for (int n = 0; n < numCandidates; n++) {
7101                        ResolveInfo info = matchAllList.get(n);
7102                        // track the highest overall match priority...
7103                        if (info.priority > maxMatchPrio) {
7104                            maxMatchPrio = info.priority;
7105                        }
7106                        // ...and the highest-priority default browser match
7107                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7108                            if (defaultBrowserMatch == null
7109                                    || (defaultBrowserMatch.priority < info.priority)) {
7110                                if (debug) {
7111                                    Slog.v(TAG, "Considering default browser match " + info);
7112                                }
7113                                defaultBrowserMatch = info;
7114                            }
7115                        }
7116                    }
7117                    if (defaultBrowserMatch != null
7118                            && defaultBrowserMatch.priority >= maxMatchPrio
7119                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7120                    {
7121                        if (debug) {
7122                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7123                        }
7124                        result.add(defaultBrowserMatch);
7125                    } else {
7126                        result.addAll(matchAllList);
7127                    }
7128                }
7129
7130                // If there is nothing selected, add all candidates and remove the ones that the user
7131                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7132                if (result.size() == 0) {
7133                    result.addAll(candidates);
7134                    result.removeAll(neverList);
7135                }
7136            }
7137        }
7138        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7139            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7140                    result.size());
7141            for (ResolveInfo info : result) {
7142                Slog.v(TAG, "  + " + info.activityInfo);
7143            }
7144        }
7145        return result;
7146    }
7147
7148    // Returns a packed value as a long:
7149    //
7150    // high 'int'-sized word: link status: undefined/ask/never/always.
7151    // low 'int'-sized word: relative priority among 'always' results.
7152    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7153        long result = ps.getDomainVerificationStatusForUser(userId);
7154        // if none available, get the master status
7155        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7156            if (ps.getIntentFilterVerificationInfo() != null) {
7157                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7158            }
7159        }
7160        return result;
7161    }
7162
7163    private ResolveInfo querySkipCurrentProfileIntents(
7164            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7165            int flags, int sourceUserId) {
7166        if (matchingFilters != null) {
7167            int size = matchingFilters.size();
7168            for (int i = 0; i < size; i ++) {
7169                CrossProfileIntentFilter filter = matchingFilters.get(i);
7170                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7171                    // Checking if there are activities in the target user that can handle the
7172                    // intent.
7173                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7174                            resolvedType, flags, sourceUserId);
7175                    if (resolveInfo != null) {
7176                        return resolveInfo;
7177                    }
7178                }
7179            }
7180        }
7181        return null;
7182    }
7183
7184    // Return matching ResolveInfo in target user if any.
7185    private ResolveInfo queryCrossProfileIntents(
7186            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7187            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7188        if (matchingFilters != null) {
7189            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7190            // match the same intent. For performance reasons, it is better not to
7191            // run queryIntent twice for the same userId
7192            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7193            int size = matchingFilters.size();
7194            for (int i = 0; i < size; i++) {
7195                CrossProfileIntentFilter filter = matchingFilters.get(i);
7196                int targetUserId = filter.getTargetUserId();
7197                boolean skipCurrentProfile =
7198                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7199                boolean skipCurrentProfileIfNoMatchFound =
7200                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7201                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7202                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7203                    // Checking if there are activities in the target user that can handle the
7204                    // intent.
7205                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7206                            resolvedType, flags, sourceUserId);
7207                    if (resolveInfo != null) return resolveInfo;
7208                    alreadyTriedUserIds.put(targetUserId, true);
7209                }
7210            }
7211        }
7212        return null;
7213    }
7214
7215    /**
7216     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7217     * will forward the intent to the filter's target user.
7218     * Otherwise, returns null.
7219     */
7220    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7221            String resolvedType, int flags, int sourceUserId) {
7222        int targetUserId = filter.getTargetUserId();
7223        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7224                resolvedType, flags, targetUserId);
7225        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7226            // If all the matches in the target profile are suspended, return null.
7227            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7228                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7229                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7230                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7231                            targetUserId);
7232                }
7233            }
7234        }
7235        return null;
7236    }
7237
7238    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7239            int sourceUserId, int targetUserId) {
7240        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7241        long ident = Binder.clearCallingIdentity();
7242        boolean targetIsProfile;
7243        try {
7244            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7245        } finally {
7246            Binder.restoreCallingIdentity(ident);
7247        }
7248        String className;
7249        if (targetIsProfile) {
7250            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7251        } else {
7252            className = FORWARD_INTENT_TO_PARENT;
7253        }
7254        ComponentName forwardingActivityComponentName = new ComponentName(
7255                mAndroidApplication.packageName, className);
7256        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7257                sourceUserId);
7258        if (!targetIsProfile) {
7259            forwardingActivityInfo.showUserIcon = targetUserId;
7260            forwardingResolveInfo.noResourceId = true;
7261        }
7262        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7263        forwardingResolveInfo.priority = 0;
7264        forwardingResolveInfo.preferredOrder = 0;
7265        forwardingResolveInfo.match = 0;
7266        forwardingResolveInfo.isDefault = true;
7267        forwardingResolveInfo.filter = filter;
7268        forwardingResolveInfo.targetUserId = targetUserId;
7269        return forwardingResolveInfo;
7270    }
7271
7272    @Override
7273    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7274            Intent[] specifics, String[] specificTypes, Intent intent,
7275            String resolvedType, int flags, int userId) {
7276        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7277                specificTypes, intent, resolvedType, flags, userId));
7278    }
7279
7280    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7281            Intent[] specifics, String[] specificTypes, Intent intent,
7282            String resolvedType, int flags, int userId) {
7283        if (!sUserManager.exists(userId)) return Collections.emptyList();
7284        final int callingUid = Binder.getCallingUid();
7285        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7286                false /*includeInstantApps*/);
7287        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7288                false /*requireFullPermission*/, false /*checkShell*/,
7289                "query intent activity options");
7290        final String resultsAction = intent.getAction();
7291
7292        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7293                | PackageManager.GET_RESOLVED_FILTER, userId);
7294
7295        if (DEBUG_INTENT_MATCHING) {
7296            Log.v(TAG, "Query " + intent + ": " + results);
7297        }
7298
7299        int specificsPos = 0;
7300        int N;
7301
7302        // todo: note that the algorithm used here is O(N^2).  This
7303        // isn't a problem in our current environment, but if we start running
7304        // into situations where we have more than 5 or 10 matches then this
7305        // should probably be changed to something smarter...
7306
7307        // First we go through and resolve each of the specific items
7308        // that were supplied, taking care of removing any corresponding
7309        // duplicate items in the generic resolve list.
7310        if (specifics != null) {
7311            for (int i=0; i<specifics.length; i++) {
7312                final Intent sintent = specifics[i];
7313                if (sintent == null) {
7314                    continue;
7315                }
7316
7317                if (DEBUG_INTENT_MATCHING) {
7318                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7319                }
7320
7321                String action = sintent.getAction();
7322                if (resultsAction != null && resultsAction.equals(action)) {
7323                    // If this action was explicitly requested, then don't
7324                    // remove things that have it.
7325                    action = null;
7326                }
7327
7328                ResolveInfo ri = null;
7329                ActivityInfo ai = null;
7330
7331                ComponentName comp = sintent.getComponent();
7332                if (comp == null) {
7333                    ri = resolveIntent(
7334                        sintent,
7335                        specificTypes != null ? specificTypes[i] : null,
7336                            flags, userId);
7337                    if (ri == null) {
7338                        continue;
7339                    }
7340                    if (ri == mResolveInfo) {
7341                        // ACK!  Must do something better with this.
7342                    }
7343                    ai = ri.activityInfo;
7344                    comp = new ComponentName(ai.applicationInfo.packageName,
7345                            ai.name);
7346                } else {
7347                    ai = getActivityInfo(comp, flags, userId);
7348                    if (ai == null) {
7349                        continue;
7350                    }
7351                }
7352
7353                // Look for any generic query activities that are duplicates
7354                // of this specific one, and remove them from the results.
7355                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7356                N = results.size();
7357                int j;
7358                for (j=specificsPos; j<N; j++) {
7359                    ResolveInfo sri = results.get(j);
7360                    if ((sri.activityInfo.name.equals(comp.getClassName())
7361                            && sri.activityInfo.applicationInfo.packageName.equals(
7362                                    comp.getPackageName()))
7363                        || (action != null && sri.filter.matchAction(action))) {
7364                        results.remove(j);
7365                        if (DEBUG_INTENT_MATCHING) Log.v(
7366                            TAG, "Removing duplicate item from " + j
7367                            + " due to specific " + specificsPos);
7368                        if (ri == null) {
7369                            ri = sri;
7370                        }
7371                        j--;
7372                        N--;
7373                    }
7374                }
7375
7376                // Add this specific item to its proper place.
7377                if (ri == null) {
7378                    ri = new ResolveInfo();
7379                    ri.activityInfo = ai;
7380                }
7381                results.add(specificsPos, ri);
7382                ri.specificIndex = i;
7383                specificsPos++;
7384            }
7385        }
7386
7387        // Now we go through the remaining generic results and remove any
7388        // duplicate actions that are found here.
7389        N = results.size();
7390        for (int i=specificsPos; i<N-1; i++) {
7391            final ResolveInfo rii = results.get(i);
7392            if (rii.filter == null) {
7393                continue;
7394            }
7395
7396            // Iterate over all of the actions of this result's intent
7397            // filter...  typically this should be just one.
7398            final Iterator<String> it = rii.filter.actionsIterator();
7399            if (it == null) {
7400                continue;
7401            }
7402            while (it.hasNext()) {
7403                final String action = it.next();
7404                if (resultsAction != null && resultsAction.equals(action)) {
7405                    // If this action was explicitly requested, then don't
7406                    // remove things that have it.
7407                    continue;
7408                }
7409                for (int j=i+1; j<N; j++) {
7410                    final ResolveInfo rij = results.get(j);
7411                    if (rij.filter != null && rij.filter.hasAction(action)) {
7412                        results.remove(j);
7413                        if (DEBUG_INTENT_MATCHING) Log.v(
7414                            TAG, "Removing duplicate item from " + j
7415                            + " due to action " + action + " at " + i);
7416                        j--;
7417                        N--;
7418                    }
7419                }
7420            }
7421
7422            // If the caller didn't request filter information, drop it now
7423            // so we don't have to marshall/unmarshall it.
7424            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7425                rii.filter = null;
7426            }
7427        }
7428
7429        // Filter out the caller activity if so requested.
7430        if (caller != null) {
7431            N = results.size();
7432            for (int i=0; i<N; i++) {
7433                ActivityInfo ainfo = results.get(i).activityInfo;
7434                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7435                        && caller.getClassName().equals(ainfo.name)) {
7436                    results.remove(i);
7437                    break;
7438                }
7439            }
7440        }
7441
7442        // If the caller didn't request filter information,
7443        // drop them now so we don't have to
7444        // marshall/unmarshall it.
7445        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7446            N = results.size();
7447            for (int i=0; i<N; i++) {
7448                results.get(i).filter = null;
7449            }
7450        }
7451
7452        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7453        return results;
7454    }
7455
7456    @Override
7457    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7458            String resolvedType, int flags, int userId) {
7459        return new ParceledListSlice<>(
7460                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7461                        false /*allowDynamicSplits*/));
7462    }
7463
7464    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7465            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7466        if (!sUserManager.exists(userId)) return Collections.emptyList();
7467        final int callingUid = Binder.getCallingUid();
7468        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7469                false /*requireFullPermission*/, false /*checkShell*/,
7470                "query intent receivers");
7471        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7472        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7473                false /*includeInstantApps*/);
7474        ComponentName comp = intent.getComponent();
7475        if (comp == null) {
7476            if (intent.getSelector() != null) {
7477                intent = intent.getSelector();
7478                comp = intent.getComponent();
7479            }
7480        }
7481        if (comp != null) {
7482            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7483            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7484            if (ai != null) {
7485                // When specifying an explicit component, we prevent the activity from being
7486                // used when either 1) the calling package is normal and the activity is within
7487                // an instant application or 2) the calling package is ephemeral and the
7488                // activity is not visible to instant applications.
7489                final boolean matchInstantApp =
7490                        (flags & PackageManager.MATCH_INSTANT) != 0;
7491                final boolean matchVisibleToInstantAppOnly =
7492                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7493                final boolean matchExplicitlyVisibleOnly =
7494                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7495                final boolean isCallerInstantApp =
7496                        instantAppPkgName != null;
7497                final boolean isTargetSameInstantApp =
7498                        comp.getPackageName().equals(instantAppPkgName);
7499                final boolean isTargetInstantApp =
7500                        (ai.applicationInfo.privateFlags
7501                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7502                final boolean isTargetVisibleToInstantApp =
7503                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7504                final boolean isTargetExplicitlyVisibleToInstantApp =
7505                        isTargetVisibleToInstantApp
7506                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7507                final boolean isTargetHiddenFromInstantApp =
7508                        !isTargetVisibleToInstantApp
7509                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7510                final boolean blockResolution =
7511                        !isTargetSameInstantApp
7512                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7513                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7514                                        && isTargetHiddenFromInstantApp));
7515                if (!blockResolution) {
7516                    ResolveInfo ri = new ResolveInfo();
7517                    ri.activityInfo = ai;
7518                    list.add(ri);
7519                }
7520            }
7521            return applyPostResolutionFilter(
7522                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7523        }
7524
7525        // reader
7526        synchronized (mPackages) {
7527            String pkgName = intent.getPackage();
7528            if (pkgName == null) {
7529                final List<ResolveInfo> result =
7530                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7531                return applyPostResolutionFilter(
7532                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7533            }
7534            final PackageParser.Package pkg = mPackages.get(pkgName);
7535            if (pkg != null) {
7536                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7537                        intent, resolvedType, flags, pkg.receivers, userId);
7538                return applyPostResolutionFilter(
7539                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7540            }
7541            return Collections.emptyList();
7542        }
7543    }
7544
7545    @Override
7546    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7547        final int callingUid = Binder.getCallingUid();
7548        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7549    }
7550
7551    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7552            int userId, int callingUid) {
7553        if (!sUserManager.exists(userId)) return null;
7554        flags = updateFlagsForResolve(
7555                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7556        List<ResolveInfo> query = queryIntentServicesInternal(
7557                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7558        if (query != null) {
7559            if (query.size() >= 1) {
7560                // If there is more than one service with the same priority,
7561                // just arbitrarily pick the first one.
7562                return query.get(0);
7563            }
7564        }
7565        return null;
7566    }
7567
7568    @Override
7569    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7570            String resolvedType, int flags, int userId) {
7571        final int callingUid = Binder.getCallingUid();
7572        return new ParceledListSlice<>(queryIntentServicesInternal(
7573                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7574    }
7575
7576    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7577            String resolvedType, int flags, int userId, int callingUid,
7578            boolean includeInstantApps) {
7579        if (!sUserManager.exists(userId)) return Collections.emptyList();
7580        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7581                false /*requireFullPermission*/, false /*checkShell*/,
7582                "query intent receivers");
7583        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7584        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7585        ComponentName comp = intent.getComponent();
7586        if (comp == null) {
7587            if (intent.getSelector() != null) {
7588                intent = intent.getSelector();
7589                comp = intent.getComponent();
7590            }
7591        }
7592        if (comp != null) {
7593            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7594            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7595            if (si != null) {
7596                // When specifying an explicit component, we prevent the service from being
7597                // used when either 1) the service is in an instant application and the
7598                // caller is not the same instant application or 2) the calling package is
7599                // ephemeral and the activity is not visible to ephemeral applications.
7600                final boolean matchInstantApp =
7601                        (flags & PackageManager.MATCH_INSTANT) != 0;
7602                final boolean matchVisibleToInstantAppOnly =
7603                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7604                final boolean isCallerInstantApp =
7605                        instantAppPkgName != null;
7606                final boolean isTargetSameInstantApp =
7607                        comp.getPackageName().equals(instantAppPkgName);
7608                final boolean isTargetInstantApp =
7609                        (si.applicationInfo.privateFlags
7610                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7611                final boolean isTargetHiddenFromInstantApp =
7612                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7613                final boolean blockResolution =
7614                        !isTargetSameInstantApp
7615                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7616                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7617                                        && isTargetHiddenFromInstantApp));
7618                if (!blockResolution) {
7619                    final ResolveInfo ri = new ResolveInfo();
7620                    ri.serviceInfo = si;
7621                    list.add(ri);
7622                }
7623            }
7624            return list;
7625        }
7626
7627        // reader
7628        synchronized (mPackages) {
7629            String pkgName = intent.getPackage();
7630            if (pkgName == null) {
7631                return applyPostServiceResolutionFilter(
7632                        mServices.queryIntent(intent, resolvedType, flags, userId),
7633                        instantAppPkgName);
7634            }
7635            final PackageParser.Package pkg = mPackages.get(pkgName);
7636            if (pkg != null) {
7637                return applyPostServiceResolutionFilter(
7638                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7639                                userId),
7640                        instantAppPkgName);
7641            }
7642            return Collections.emptyList();
7643        }
7644    }
7645
7646    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7647            String instantAppPkgName) {
7648        if (instantAppPkgName == null) {
7649            return resolveInfos;
7650        }
7651        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7652            final ResolveInfo info = resolveInfos.get(i);
7653            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7654            // allow services that are defined in the provided package
7655            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7656                if (info.serviceInfo.splitName != null
7657                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7658                                info.serviceInfo.splitName)) {
7659                    // requested service is defined in a split that hasn't been installed yet.
7660                    // add the installer to the resolve list
7661                    if (DEBUG_EPHEMERAL) {
7662                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7663                    }
7664                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7665                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7666                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7667                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7668                            null /*failureIntent*/);
7669                    // make sure this resolver is the default
7670                    installerInfo.isDefault = true;
7671                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7672                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7673                    // add a non-generic filter
7674                    installerInfo.filter = new IntentFilter();
7675                    // load resources from the correct package
7676                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7677                    resolveInfos.set(i, installerInfo);
7678                }
7679                continue;
7680            }
7681            // allow services that have been explicitly exposed to ephemeral apps
7682            if (!isEphemeralApp
7683                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7684                continue;
7685            }
7686            resolveInfos.remove(i);
7687        }
7688        return resolveInfos;
7689    }
7690
7691    @Override
7692    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7693            String resolvedType, int flags, int userId) {
7694        return new ParceledListSlice<>(
7695                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7696    }
7697
7698    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7699            Intent intent, String resolvedType, int flags, int userId) {
7700        if (!sUserManager.exists(userId)) return Collections.emptyList();
7701        final int callingUid = Binder.getCallingUid();
7702        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7703        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7704                false /*includeInstantApps*/);
7705        ComponentName comp = intent.getComponent();
7706        if (comp == null) {
7707            if (intent.getSelector() != null) {
7708                intent = intent.getSelector();
7709                comp = intent.getComponent();
7710            }
7711        }
7712        if (comp != null) {
7713            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7714            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7715            if (pi != null) {
7716                // When specifying an explicit component, we prevent the provider from being
7717                // used when either 1) the provider is in an instant application and the
7718                // caller is not the same instant application or 2) the calling package is an
7719                // instant application and the provider is not visible to instant applications.
7720                final boolean matchInstantApp =
7721                        (flags & PackageManager.MATCH_INSTANT) != 0;
7722                final boolean matchVisibleToInstantAppOnly =
7723                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7724                final boolean isCallerInstantApp =
7725                        instantAppPkgName != null;
7726                final boolean isTargetSameInstantApp =
7727                        comp.getPackageName().equals(instantAppPkgName);
7728                final boolean isTargetInstantApp =
7729                        (pi.applicationInfo.privateFlags
7730                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7731                final boolean isTargetHiddenFromInstantApp =
7732                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7733                final boolean blockResolution =
7734                        !isTargetSameInstantApp
7735                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7736                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7737                                        && isTargetHiddenFromInstantApp));
7738                if (!blockResolution) {
7739                    final ResolveInfo ri = new ResolveInfo();
7740                    ri.providerInfo = pi;
7741                    list.add(ri);
7742                }
7743            }
7744            return list;
7745        }
7746
7747        // reader
7748        synchronized (mPackages) {
7749            String pkgName = intent.getPackage();
7750            if (pkgName == null) {
7751                return applyPostContentProviderResolutionFilter(
7752                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7753                        instantAppPkgName);
7754            }
7755            final PackageParser.Package pkg = mPackages.get(pkgName);
7756            if (pkg != null) {
7757                return applyPostContentProviderResolutionFilter(
7758                        mProviders.queryIntentForPackage(
7759                        intent, resolvedType, flags, pkg.providers, userId),
7760                        instantAppPkgName);
7761            }
7762            return Collections.emptyList();
7763        }
7764    }
7765
7766    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7767            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7768        if (instantAppPkgName == null) {
7769            return resolveInfos;
7770        }
7771        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7772            final ResolveInfo info = resolveInfos.get(i);
7773            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7774            // allow providers that are defined in the provided package
7775            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7776                if (info.providerInfo.splitName != null
7777                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7778                                info.providerInfo.splitName)) {
7779                    // requested provider is defined in a split that hasn't been installed yet.
7780                    // add the installer to the resolve list
7781                    if (DEBUG_EPHEMERAL) {
7782                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7783                    }
7784                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7785                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7786                            info.providerInfo.packageName, info.providerInfo.splitName,
7787                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7788                            null /*failureIntent*/);
7789                    // make sure this resolver is the default
7790                    installerInfo.isDefault = true;
7791                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7792                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7793                    // add a non-generic filter
7794                    installerInfo.filter = new IntentFilter();
7795                    // load resources from the correct package
7796                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7797                    resolveInfos.set(i, installerInfo);
7798                }
7799                continue;
7800            }
7801            // allow providers that have been explicitly exposed to instant applications
7802            if (!isEphemeralApp
7803                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7804                continue;
7805            }
7806            resolveInfos.remove(i);
7807        }
7808        return resolveInfos;
7809    }
7810
7811    @Override
7812    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7813        final int callingUid = Binder.getCallingUid();
7814        if (getInstantAppPackageName(callingUid) != null) {
7815            return ParceledListSlice.emptyList();
7816        }
7817        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7818        flags = updateFlagsForPackage(flags, userId, null);
7819        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7820        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7821                true /* requireFullPermission */, false /* checkShell */,
7822                "get installed packages");
7823
7824        // writer
7825        synchronized (mPackages) {
7826            ArrayList<PackageInfo> list;
7827            if (listUninstalled) {
7828                list = new ArrayList<>(mSettings.mPackages.size());
7829                for (PackageSetting ps : mSettings.mPackages.values()) {
7830                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7831                        continue;
7832                    }
7833                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7834                        continue;
7835                    }
7836                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7837                    if (pi != null) {
7838                        list.add(pi);
7839                    }
7840                }
7841            } else {
7842                list = new ArrayList<>(mPackages.size());
7843                for (PackageParser.Package p : mPackages.values()) {
7844                    final PackageSetting ps = (PackageSetting) p.mExtras;
7845                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7846                        continue;
7847                    }
7848                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7849                        continue;
7850                    }
7851                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7852                            p.mExtras, flags, userId);
7853                    if (pi != null) {
7854                        list.add(pi);
7855                    }
7856                }
7857            }
7858
7859            return new ParceledListSlice<>(list);
7860        }
7861    }
7862
7863    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7864            String[] permissions, boolean[] tmp, int flags, int userId) {
7865        int numMatch = 0;
7866        final PermissionsState permissionsState = ps.getPermissionsState();
7867        for (int i=0; i<permissions.length; i++) {
7868            final String permission = permissions[i];
7869            if (permissionsState.hasPermission(permission, userId)) {
7870                tmp[i] = true;
7871                numMatch++;
7872            } else {
7873                tmp[i] = false;
7874            }
7875        }
7876        if (numMatch == 0) {
7877            return;
7878        }
7879        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7880
7881        // The above might return null in cases of uninstalled apps or install-state
7882        // skew across users/profiles.
7883        if (pi != null) {
7884            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7885                if (numMatch == permissions.length) {
7886                    pi.requestedPermissions = permissions;
7887                } else {
7888                    pi.requestedPermissions = new String[numMatch];
7889                    numMatch = 0;
7890                    for (int i=0; i<permissions.length; i++) {
7891                        if (tmp[i]) {
7892                            pi.requestedPermissions[numMatch] = permissions[i];
7893                            numMatch++;
7894                        }
7895                    }
7896                }
7897            }
7898            list.add(pi);
7899        }
7900    }
7901
7902    @Override
7903    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7904            String[] permissions, int flags, int userId) {
7905        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7906        flags = updateFlagsForPackage(flags, userId, permissions);
7907        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7908                true /* requireFullPermission */, false /* checkShell */,
7909                "get packages holding permissions");
7910        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7911
7912        // writer
7913        synchronized (mPackages) {
7914            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7915            boolean[] tmpBools = new boolean[permissions.length];
7916            if (listUninstalled) {
7917                for (PackageSetting ps : mSettings.mPackages.values()) {
7918                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7919                            userId);
7920                }
7921            } else {
7922                for (PackageParser.Package pkg : mPackages.values()) {
7923                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7924                    if (ps != null) {
7925                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7926                                userId);
7927                    }
7928                }
7929            }
7930
7931            return new ParceledListSlice<PackageInfo>(list);
7932        }
7933    }
7934
7935    @Override
7936    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7937        final int callingUid = Binder.getCallingUid();
7938        if (getInstantAppPackageName(callingUid) != null) {
7939            return ParceledListSlice.emptyList();
7940        }
7941        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7942        flags = updateFlagsForApplication(flags, userId, null);
7943        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7944
7945        // writer
7946        synchronized (mPackages) {
7947            ArrayList<ApplicationInfo> list;
7948            if (listUninstalled) {
7949                list = new ArrayList<>(mSettings.mPackages.size());
7950                for (PackageSetting ps : mSettings.mPackages.values()) {
7951                    ApplicationInfo ai;
7952                    int effectiveFlags = flags;
7953                    if (ps.isSystem()) {
7954                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7955                    }
7956                    if (ps.pkg != null) {
7957                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7958                            continue;
7959                        }
7960                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7961                            continue;
7962                        }
7963                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7964                                ps.readUserState(userId), userId);
7965                        if (ai != null) {
7966                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7967                        }
7968                    } else {
7969                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7970                        // and already converts to externally visible package name
7971                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7972                                callingUid, effectiveFlags, userId);
7973                    }
7974                    if (ai != null) {
7975                        list.add(ai);
7976                    }
7977                }
7978            } else {
7979                list = new ArrayList<>(mPackages.size());
7980                for (PackageParser.Package p : mPackages.values()) {
7981                    if (p.mExtras != null) {
7982                        PackageSetting ps = (PackageSetting) p.mExtras;
7983                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7984                            continue;
7985                        }
7986                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7987                            continue;
7988                        }
7989                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7990                                ps.readUserState(userId), userId);
7991                        if (ai != null) {
7992                            ai.packageName = resolveExternalPackageNameLPr(p);
7993                            list.add(ai);
7994                        }
7995                    }
7996                }
7997            }
7998
7999            return new ParceledListSlice<>(list);
8000        }
8001    }
8002
8003    @Override
8004    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8005        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8006            return null;
8007        }
8008        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8009            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8010                    "getEphemeralApplications");
8011        }
8012        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8013                true /* requireFullPermission */, false /* checkShell */,
8014                "getEphemeralApplications");
8015        synchronized (mPackages) {
8016            List<InstantAppInfo> instantApps = mInstantAppRegistry
8017                    .getInstantAppsLPr(userId);
8018            if (instantApps != null) {
8019                return new ParceledListSlice<>(instantApps);
8020            }
8021        }
8022        return null;
8023    }
8024
8025    @Override
8026    public boolean isInstantApp(String packageName, int userId) {
8027        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8028                true /* requireFullPermission */, false /* checkShell */,
8029                "isInstantApp");
8030        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8031            return false;
8032        }
8033
8034        synchronized (mPackages) {
8035            int callingUid = Binder.getCallingUid();
8036            if (Process.isIsolated(callingUid)) {
8037                callingUid = mIsolatedOwners.get(callingUid);
8038            }
8039            final PackageSetting ps = mSettings.mPackages.get(packageName);
8040            PackageParser.Package pkg = mPackages.get(packageName);
8041            final boolean returnAllowed =
8042                    ps != null
8043                    && (isCallerSameApp(packageName, callingUid)
8044                            || canViewInstantApps(callingUid, userId)
8045                            || mInstantAppRegistry.isInstantAccessGranted(
8046                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8047            if (returnAllowed) {
8048                return ps.getInstantApp(userId);
8049            }
8050        }
8051        return false;
8052    }
8053
8054    @Override
8055    public byte[] getInstantAppCookie(String packageName, int userId) {
8056        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8057            return null;
8058        }
8059
8060        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8061                true /* requireFullPermission */, false /* checkShell */,
8062                "getInstantAppCookie");
8063        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8064            return null;
8065        }
8066        synchronized (mPackages) {
8067            return mInstantAppRegistry.getInstantAppCookieLPw(
8068                    packageName, userId);
8069        }
8070    }
8071
8072    @Override
8073    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8074        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8075            return true;
8076        }
8077
8078        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8079                true /* requireFullPermission */, true /* checkShell */,
8080                "setInstantAppCookie");
8081        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8082            return false;
8083        }
8084        synchronized (mPackages) {
8085            return mInstantAppRegistry.setInstantAppCookieLPw(
8086                    packageName, cookie, userId);
8087        }
8088    }
8089
8090    @Override
8091    public Bitmap getInstantAppIcon(String packageName, int userId) {
8092        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8093            return null;
8094        }
8095
8096        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8097            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8098                    "getInstantAppIcon");
8099        }
8100        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8101                true /* requireFullPermission */, false /* checkShell */,
8102                "getInstantAppIcon");
8103
8104        synchronized (mPackages) {
8105            return mInstantAppRegistry.getInstantAppIconLPw(
8106                    packageName, userId);
8107        }
8108    }
8109
8110    private boolean isCallerSameApp(String packageName, int uid) {
8111        PackageParser.Package pkg = mPackages.get(packageName);
8112        return pkg != null
8113                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8114    }
8115
8116    @Override
8117    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8118        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8119            return ParceledListSlice.emptyList();
8120        }
8121        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8122    }
8123
8124    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8125        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8126
8127        // reader
8128        synchronized (mPackages) {
8129            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8130            final int userId = UserHandle.getCallingUserId();
8131            while (i.hasNext()) {
8132                final PackageParser.Package p = i.next();
8133                if (p.applicationInfo == null) continue;
8134
8135                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8136                        && !p.applicationInfo.isDirectBootAware();
8137                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8138                        && p.applicationInfo.isDirectBootAware();
8139
8140                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8141                        && (!mSafeMode || isSystemApp(p))
8142                        && (matchesUnaware || matchesAware)) {
8143                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8144                    if (ps != null) {
8145                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8146                                ps.readUserState(userId), userId);
8147                        if (ai != null) {
8148                            finalList.add(ai);
8149                        }
8150                    }
8151                }
8152            }
8153        }
8154
8155        return finalList;
8156    }
8157
8158    @Override
8159    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8160        return resolveContentProviderInternal(name, flags, userId);
8161    }
8162
8163    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8164        if (!sUserManager.exists(userId)) return null;
8165        flags = updateFlagsForComponent(flags, userId, name);
8166        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8167        // reader
8168        synchronized (mPackages) {
8169            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8170            PackageSetting ps = provider != null
8171                    ? mSettings.mPackages.get(provider.owner.packageName)
8172                    : null;
8173            if (ps != null) {
8174                final boolean isInstantApp = ps.getInstantApp(userId);
8175                // normal application; filter out instant application provider
8176                if (instantAppPkgName == null && isInstantApp) {
8177                    return null;
8178                }
8179                // instant application; filter out other instant applications
8180                if (instantAppPkgName != null
8181                        && isInstantApp
8182                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8183                    return null;
8184                }
8185                // instant application; filter out non-exposed provider
8186                if (instantAppPkgName != null
8187                        && !isInstantApp
8188                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8189                    return null;
8190                }
8191                // provider not enabled
8192                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8193                    return null;
8194                }
8195                return PackageParser.generateProviderInfo(
8196                        provider, flags, ps.readUserState(userId), userId);
8197            }
8198            return null;
8199        }
8200    }
8201
8202    /**
8203     * @deprecated
8204     */
8205    @Deprecated
8206    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8207        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8208            return;
8209        }
8210        // reader
8211        synchronized (mPackages) {
8212            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8213                    .entrySet().iterator();
8214            final int userId = UserHandle.getCallingUserId();
8215            while (i.hasNext()) {
8216                Map.Entry<String, PackageParser.Provider> entry = i.next();
8217                PackageParser.Provider p = entry.getValue();
8218                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8219
8220                if (ps != null && p.syncable
8221                        && (!mSafeMode || (p.info.applicationInfo.flags
8222                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8223                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8224                            ps.readUserState(userId), userId);
8225                    if (info != null) {
8226                        outNames.add(entry.getKey());
8227                        outInfo.add(info);
8228                    }
8229                }
8230            }
8231        }
8232    }
8233
8234    @Override
8235    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8236            int uid, int flags, String metaDataKey) {
8237        final int callingUid = Binder.getCallingUid();
8238        final int userId = processName != null ? UserHandle.getUserId(uid)
8239                : UserHandle.getCallingUserId();
8240        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8241        flags = updateFlagsForComponent(flags, userId, processName);
8242        ArrayList<ProviderInfo> finalList = null;
8243        // reader
8244        synchronized (mPackages) {
8245            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8246            while (i.hasNext()) {
8247                final PackageParser.Provider p = i.next();
8248                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8249                if (ps != null && p.info.authority != null
8250                        && (processName == null
8251                                || (p.info.processName.equals(processName)
8252                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8253                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8254
8255                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8256                    // parameter.
8257                    if (metaDataKey != null
8258                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8259                        continue;
8260                    }
8261                    final ComponentName component =
8262                            new ComponentName(p.info.packageName, p.info.name);
8263                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8264                        continue;
8265                    }
8266                    if (finalList == null) {
8267                        finalList = new ArrayList<ProviderInfo>(3);
8268                    }
8269                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8270                            ps.readUserState(userId), userId);
8271                    if (info != null) {
8272                        finalList.add(info);
8273                    }
8274                }
8275            }
8276        }
8277
8278        if (finalList != null) {
8279            Collections.sort(finalList, mProviderInitOrderSorter);
8280            return new ParceledListSlice<ProviderInfo>(finalList);
8281        }
8282
8283        return ParceledListSlice.emptyList();
8284    }
8285
8286    @Override
8287    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8288        // reader
8289        synchronized (mPackages) {
8290            final int callingUid = Binder.getCallingUid();
8291            final int callingUserId = UserHandle.getUserId(callingUid);
8292            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8293            if (ps == null) return null;
8294            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8295                return null;
8296            }
8297            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8298            return PackageParser.generateInstrumentationInfo(i, flags);
8299        }
8300    }
8301
8302    @Override
8303    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8304            String targetPackage, int flags) {
8305        final int callingUid = Binder.getCallingUid();
8306        final int callingUserId = UserHandle.getUserId(callingUid);
8307        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8308        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8309            return ParceledListSlice.emptyList();
8310        }
8311        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8312    }
8313
8314    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8315            int flags) {
8316        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8317
8318        // reader
8319        synchronized (mPackages) {
8320            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8321            while (i.hasNext()) {
8322                final PackageParser.Instrumentation p = i.next();
8323                if (targetPackage == null
8324                        || targetPackage.equals(p.info.targetPackage)) {
8325                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8326                            flags);
8327                    if (ii != null) {
8328                        finalList.add(ii);
8329                    }
8330                }
8331            }
8332        }
8333
8334        return finalList;
8335    }
8336
8337    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8338        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8339        try {
8340            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8341        } finally {
8342            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8343        }
8344    }
8345
8346    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8347        final File[] files = dir.listFiles();
8348        if (ArrayUtils.isEmpty(files)) {
8349            Log.d(TAG, "No files in app dir " + dir);
8350            return;
8351        }
8352
8353        if (DEBUG_PACKAGE_SCANNING) {
8354            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8355                    + " flags=0x" + Integer.toHexString(parseFlags));
8356        }
8357        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8358                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8359                mParallelPackageParserCallback);
8360
8361        // Submit files for parsing in parallel
8362        int fileCount = 0;
8363        for (File file : files) {
8364            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8365                    && !PackageInstallerService.isStageName(file.getName());
8366            if (!isPackage) {
8367                // Ignore entries which are not packages
8368                continue;
8369            }
8370            parallelPackageParser.submit(file, parseFlags);
8371            fileCount++;
8372        }
8373
8374        // Process results one by one
8375        for (; fileCount > 0; fileCount--) {
8376            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8377            Throwable throwable = parseResult.throwable;
8378            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8379
8380            if (throwable == null) {
8381                // Static shared libraries have synthetic package names
8382                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8383                    renameStaticSharedLibraryPackage(parseResult.pkg);
8384                }
8385                try {
8386                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8387                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8388                                currentTime, null);
8389                    }
8390                } catch (PackageManagerException e) {
8391                    errorCode = e.error;
8392                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8393                }
8394            } else if (throwable instanceof PackageParser.PackageParserException) {
8395                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8396                        throwable;
8397                errorCode = e.error;
8398                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8399            } else {
8400                throw new IllegalStateException("Unexpected exception occurred while parsing "
8401                        + parseResult.scanFile, throwable);
8402            }
8403
8404            // Delete invalid userdata apps
8405            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8406                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8407                logCriticalInfo(Log.WARN,
8408                        "Deleting invalid package at " + parseResult.scanFile);
8409                removeCodePathLI(parseResult.scanFile);
8410            }
8411        }
8412        parallelPackageParser.close();
8413    }
8414
8415    private static File getSettingsProblemFile() {
8416        File dataDir = Environment.getDataDirectory();
8417        File systemDir = new File(dataDir, "system");
8418        File fname = new File(systemDir, "uiderrors.txt");
8419        return fname;
8420    }
8421
8422    public static void reportSettingsProblem(int priority, String msg) {
8423        logCriticalInfo(priority, msg);
8424    }
8425
8426    public static void logCriticalInfo(int priority, String msg) {
8427        Slog.println(priority, TAG, msg);
8428        EventLogTags.writePmCriticalInfo(msg);
8429        try {
8430            File fname = getSettingsProblemFile();
8431            FileOutputStream out = new FileOutputStream(fname, true);
8432            PrintWriter pw = new FastPrintWriter(out);
8433            SimpleDateFormat formatter = new SimpleDateFormat();
8434            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8435            pw.println(dateString + ": " + msg);
8436            pw.close();
8437            FileUtils.setPermissions(
8438                    fname.toString(),
8439                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8440                    -1, -1);
8441        } catch (java.io.IOException e) {
8442        }
8443    }
8444
8445    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8446        if (srcFile.isDirectory()) {
8447            final File baseFile = new File(pkg.baseCodePath);
8448            long maxModifiedTime = baseFile.lastModified();
8449            if (pkg.splitCodePaths != null) {
8450                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8451                    final File splitFile = new File(pkg.splitCodePaths[i]);
8452                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8453                }
8454            }
8455            return maxModifiedTime;
8456        }
8457        return srcFile.lastModified();
8458    }
8459
8460    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8461            final int policyFlags) throws PackageManagerException {
8462        // When upgrading from pre-N MR1, verify the package time stamp using the package
8463        // directory and not the APK file.
8464        final long lastModifiedTime = mIsPreNMR1Upgrade
8465                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8466        if (ps != null
8467                && ps.codePath.equals(srcFile)
8468                && ps.timeStamp == lastModifiedTime
8469                && !isCompatSignatureUpdateNeeded(pkg)
8470                && !isRecoverSignatureUpdateNeeded(pkg)) {
8471            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8472            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8473            ArraySet<PublicKey> signingKs;
8474            synchronized (mPackages) {
8475                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8476            }
8477            if (ps.signatures.mSignatures != null
8478                    && ps.signatures.mSignatures.length != 0
8479                    && signingKs != null) {
8480                // Optimization: reuse the existing cached certificates
8481                // if the package appears to be unchanged.
8482                pkg.mSignatures = ps.signatures.mSignatures;
8483                pkg.mSigningKeys = signingKs;
8484                return;
8485            }
8486
8487            Slog.w(TAG, "PackageSetting for " + ps.name
8488                    + " is missing signatures.  Collecting certs again to recover them.");
8489        } else {
8490            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8491        }
8492
8493        try {
8494            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8495            PackageParser.collectCertificates(pkg, policyFlags);
8496        } catch (PackageParserException e) {
8497            throw PackageManagerException.from(e);
8498        } finally {
8499            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8500        }
8501    }
8502
8503    /**
8504     *  Traces a package scan.
8505     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8506     */
8507    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8508            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8509        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8510        try {
8511            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8512        } finally {
8513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8514        }
8515    }
8516
8517    /**
8518     *  Scans a package and returns the newly parsed package.
8519     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8520     */
8521    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8522            long currentTime, UserHandle user) throws PackageManagerException {
8523        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8524        PackageParser pp = new PackageParser();
8525        pp.setSeparateProcesses(mSeparateProcesses);
8526        pp.setOnlyCoreApps(mOnlyCore);
8527        pp.setDisplayMetrics(mMetrics);
8528        pp.setCallback(mPackageParserCallback);
8529
8530        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8531            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8532        }
8533
8534        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8535        final PackageParser.Package pkg;
8536        try {
8537            pkg = pp.parsePackage(scanFile, parseFlags);
8538        } catch (PackageParserException e) {
8539            throw PackageManagerException.from(e);
8540        } finally {
8541            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8542        }
8543
8544        // Static shared libraries have synthetic package names
8545        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8546            renameStaticSharedLibraryPackage(pkg);
8547        }
8548
8549        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8550    }
8551
8552    /**
8553     *  Scans a package and returns the newly parsed package.
8554     *  @throws PackageManagerException on a parse error.
8555     */
8556    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8557            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8558            throws PackageManagerException {
8559        // If the package has children and this is the first dive in the function
8560        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8561        // packages (parent and children) would be successfully scanned before the
8562        // actual scan since scanning mutates internal state and we want to atomically
8563        // install the package and its children.
8564        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8565            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8566                scanFlags |= SCAN_CHECK_ONLY;
8567            }
8568        } else {
8569            scanFlags &= ~SCAN_CHECK_ONLY;
8570        }
8571
8572        // Scan the parent
8573        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8574                scanFlags, currentTime, user);
8575
8576        // Scan the children
8577        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8578        for (int i = 0; i < childCount; i++) {
8579            PackageParser.Package childPackage = pkg.childPackages.get(i);
8580            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8581                    currentTime, user);
8582        }
8583
8584
8585        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8586            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8587        }
8588
8589        return scannedPkg;
8590    }
8591
8592    /**
8593     *  Scans a package and returns the newly parsed package.
8594     *  @throws PackageManagerException on a parse error.
8595     */
8596    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8597            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8598            throws PackageManagerException {
8599        PackageSetting ps = null;
8600        PackageSetting updatedPkg;
8601        // reader
8602        synchronized (mPackages) {
8603            // Look to see if we already know about this package.
8604            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8605            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8606                // This package has been renamed to its original name.  Let's
8607                // use that.
8608                ps = mSettings.getPackageLPr(oldName);
8609            }
8610            // If there was no original package, see one for the real package name.
8611            if (ps == null) {
8612                ps = mSettings.getPackageLPr(pkg.packageName);
8613            }
8614            // Check to see if this package could be hiding/updating a system
8615            // package.  Must look for it either under the original or real
8616            // package name depending on our state.
8617            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8618            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8619
8620            // If this is a package we don't know about on the system partition, we
8621            // may need to remove disabled child packages on the system partition
8622            // or may need to not add child packages if the parent apk is updated
8623            // on the data partition and no longer defines this child package.
8624            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8625                // If this is a parent package for an updated system app and this system
8626                // app got an OTA update which no longer defines some of the child packages
8627                // we have to prune them from the disabled system packages.
8628                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8629                if (disabledPs != null) {
8630                    final int scannedChildCount = (pkg.childPackages != null)
8631                            ? pkg.childPackages.size() : 0;
8632                    final int disabledChildCount = disabledPs.childPackageNames != null
8633                            ? disabledPs.childPackageNames.size() : 0;
8634                    for (int i = 0; i < disabledChildCount; i++) {
8635                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8636                        boolean disabledPackageAvailable = false;
8637                        for (int j = 0; j < scannedChildCount; j++) {
8638                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8639                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8640                                disabledPackageAvailable = true;
8641                                break;
8642                            }
8643                         }
8644                         if (!disabledPackageAvailable) {
8645                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8646                         }
8647                    }
8648                }
8649            }
8650        }
8651
8652        final boolean isUpdatedPkg = updatedPkg != null;
8653        final boolean isUpdatedSystemPkg = isUpdatedPkg
8654                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8655        boolean isUpdatedPkgBetter = false;
8656        // First check if this is a system package that may involve an update
8657        if (isUpdatedSystemPkg) {
8658            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8659            // it needs to drop FLAG_PRIVILEGED.
8660            if (locationIsPrivileged(scanFile)) {
8661                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8662            } else {
8663                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8664            }
8665            // If new package is not located in "/oem" (e.g. due to an OTA),
8666            // it needs to drop FLAG_OEM.
8667            if (locationIsOem(scanFile)) {
8668                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8669            } else {
8670                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8671            }
8672
8673            if (ps != null && !ps.codePath.equals(scanFile)) {
8674                // The path has changed from what was last scanned...  check the
8675                // version of the new path against what we have stored to determine
8676                // what to do.
8677                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8678                if (pkg.mVersionCode <= ps.versionCode) {
8679                    // The system package has been updated and the code path does not match
8680                    // Ignore entry. Skip it.
8681                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8682                            + " ignored: updated version " + ps.versionCode
8683                            + " better than this " + pkg.mVersionCode);
8684                    if (!updatedPkg.codePath.equals(scanFile)) {
8685                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8686                                + ps.name + " changing from " + updatedPkg.codePathString
8687                                + " to " + scanFile);
8688                        updatedPkg.codePath = scanFile;
8689                        updatedPkg.codePathString = scanFile.toString();
8690                        updatedPkg.resourcePath = scanFile;
8691                        updatedPkg.resourcePathString = scanFile.toString();
8692                    }
8693                    updatedPkg.pkg = pkg;
8694                    updatedPkg.versionCode = pkg.mVersionCode;
8695
8696                    // Update the disabled system child packages to point to the package too.
8697                    final int childCount = updatedPkg.childPackageNames != null
8698                            ? updatedPkg.childPackageNames.size() : 0;
8699                    for (int i = 0; i < childCount; i++) {
8700                        String childPackageName = updatedPkg.childPackageNames.get(i);
8701                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8702                                childPackageName);
8703                        if (updatedChildPkg != null) {
8704                            updatedChildPkg.pkg = pkg;
8705                            updatedChildPkg.versionCode = pkg.mVersionCode;
8706                        }
8707                    }
8708                } else {
8709                    // The current app on the system partition is better than
8710                    // what we have updated to on the data partition; switch
8711                    // back to the system partition version.
8712                    // At this point, its safely assumed that package installation for
8713                    // apps in system partition will go through. If not there won't be a working
8714                    // version of the app
8715                    // writer
8716                    synchronized (mPackages) {
8717                        // Just remove the loaded entries from package lists.
8718                        mPackages.remove(ps.name);
8719                    }
8720
8721                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8722                            + " reverting from " + ps.codePathString
8723                            + ": new version " + pkg.mVersionCode
8724                            + " better than installed " + ps.versionCode);
8725
8726                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8727                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8728                    synchronized (mInstallLock) {
8729                        args.cleanUpResourcesLI();
8730                    }
8731                    synchronized (mPackages) {
8732                        mSettings.enableSystemPackageLPw(ps.name);
8733                    }
8734                    isUpdatedPkgBetter = true;
8735                }
8736            }
8737        }
8738
8739        String resourcePath = null;
8740        String baseResourcePath = null;
8741        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8742            if (ps != null && ps.resourcePathString != null) {
8743                resourcePath = ps.resourcePathString;
8744                baseResourcePath = ps.resourcePathString;
8745            } else {
8746                // Should not happen at all. Just log an error.
8747                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8748            }
8749        } else {
8750            resourcePath = pkg.codePath;
8751            baseResourcePath = pkg.baseCodePath;
8752        }
8753
8754        // Set application objects path explicitly.
8755        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8756        pkg.setApplicationInfoCodePath(pkg.codePath);
8757        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8758        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8759        pkg.setApplicationInfoResourcePath(resourcePath);
8760        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8761        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8762
8763        // throw an exception if we have an update to a system application, but, it's not more
8764        // recent than the package we've already scanned
8765        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8766            // Set CPU Abis to application info.
8767            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8768                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
8769                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
8770            } else {
8771                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
8772                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
8773            }
8774
8775            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8776                    + scanFile + " ignored: updated version " + ps.versionCode
8777                    + " better than this " + pkg.mVersionCode);
8778        }
8779
8780        if (isUpdatedPkg) {
8781            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8782            // initially
8783            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8784
8785            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8786            // flag set initially
8787            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8788                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8789            }
8790
8791            // An updated OEM app will not have the PARSE_IS_OEM
8792            // flag set initially
8793            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8794                policyFlags |= PackageParser.PARSE_IS_OEM;
8795            }
8796        }
8797
8798        // Verify certificates against what was last scanned
8799        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8800
8801        /*
8802         * A new system app appeared, but we already had a non-system one of the
8803         * same name installed earlier.
8804         */
8805        boolean shouldHideSystemApp = false;
8806        if (!isUpdatedPkg && ps != null
8807                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8808            /*
8809             * Check to make sure the signatures match first. If they don't,
8810             * wipe the installed application and its data.
8811             */
8812            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8813                    != PackageManager.SIGNATURE_MATCH) {
8814                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8815                        + " signatures don't match existing userdata copy; removing");
8816                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8817                        "scanPackageInternalLI")) {
8818                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8819                }
8820                ps = null;
8821            } else {
8822                /*
8823                 * If the newly-added system app is an older version than the
8824                 * already installed version, hide it. It will be scanned later
8825                 * and re-added like an update.
8826                 */
8827                if (pkg.mVersionCode <= ps.versionCode) {
8828                    shouldHideSystemApp = true;
8829                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8830                            + " but new version " + pkg.mVersionCode + " better than installed "
8831                            + ps.versionCode + "; hiding system");
8832                } else {
8833                    /*
8834                     * The newly found system app is a newer version that the
8835                     * one previously installed. Simply remove the
8836                     * already-installed application and replace it with our own
8837                     * while keeping the application data.
8838                     */
8839                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8840                            + " reverting from " + ps.codePathString + ": new version "
8841                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8842                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8843                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8844                    synchronized (mInstallLock) {
8845                        args.cleanUpResourcesLI();
8846                    }
8847                }
8848            }
8849        }
8850
8851        // The apk is forward locked (not public) if its code and resources
8852        // are kept in different files. (except for app in either system or
8853        // vendor path).
8854        // TODO grab this value from PackageSettings
8855        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8856            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8857                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8858            }
8859        }
8860
8861        final int userId = ((user == null) ? 0 : user.getIdentifier());
8862        if (ps != null && ps.getInstantApp(userId)) {
8863            scanFlags |= SCAN_AS_INSTANT_APP;
8864        }
8865        if (ps != null && ps.getVirtulalPreload(userId)) {
8866            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8867        }
8868
8869        // Note that we invoke the following method only if we are about to unpack an application
8870        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8871                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8872
8873        /*
8874         * If the system app should be overridden by a previously installed
8875         * data, hide the system app now and let the /data/app scan pick it up
8876         * again.
8877         */
8878        if (shouldHideSystemApp) {
8879            synchronized (mPackages) {
8880                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8881            }
8882        }
8883
8884        return scannedPkg;
8885    }
8886
8887    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8888        // Derive the new package synthetic package name
8889        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8890                + pkg.staticSharedLibVersion);
8891    }
8892
8893    private static String fixProcessName(String defProcessName,
8894            String processName) {
8895        if (processName == null) {
8896            return defProcessName;
8897        }
8898        return processName;
8899    }
8900
8901    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8902            throws PackageManagerException {
8903        if (pkgSetting.signatures.mSignatures != null) {
8904            // Already existing package. Make sure signatures match
8905            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8906                    == PackageManager.SIGNATURE_MATCH;
8907            if (!match) {
8908                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8909                        == PackageManager.SIGNATURE_MATCH;
8910            }
8911            if (!match) {
8912                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8913                        == PackageManager.SIGNATURE_MATCH;
8914            }
8915            if (!match) {
8916                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8917                        + pkg.packageName + " signatures do not match the "
8918                        + "previously installed version; ignoring!");
8919            }
8920        }
8921
8922        // Check for shared user signatures
8923        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8924            // Already existing package. Make sure signatures match
8925            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8926                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8927            if (!match) {
8928                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8929                        == PackageManager.SIGNATURE_MATCH;
8930            }
8931            if (!match) {
8932                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8933                        == PackageManager.SIGNATURE_MATCH;
8934            }
8935            if (!match) {
8936                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8937                        "Package " + pkg.packageName
8938                        + " has no signatures that match those in shared user "
8939                        + pkgSetting.sharedUser.name + "; ignoring!");
8940            }
8941        }
8942    }
8943
8944    /**
8945     * Enforces that only the system UID or root's UID can call a method exposed
8946     * via Binder.
8947     *
8948     * @param message used as message if SecurityException is thrown
8949     * @throws SecurityException if the caller is not system or root
8950     */
8951    private static final void enforceSystemOrRoot(String message) {
8952        final int uid = Binder.getCallingUid();
8953        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8954            throw new SecurityException(message);
8955        }
8956    }
8957
8958    @Override
8959    public void performFstrimIfNeeded() {
8960        enforceSystemOrRoot("Only the system can request fstrim");
8961
8962        // Before everything else, see whether we need to fstrim.
8963        try {
8964            IStorageManager sm = PackageHelper.getStorageManager();
8965            if (sm != null) {
8966                boolean doTrim = false;
8967                final long interval = android.provider.Settings.Global.getLong(
8968                        mContext.getContentResolver(),
8969                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8970                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8971                if (interval > 0) {
8972                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8973                    if (timeSinceLast > interval) {
8974                        doTrim = true;
8975                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8976                                + "; running immediately");
8977                    }
8978                }
8979                if (doTrim) {
8980                    final boolean dexOptDialogShown;
8981                    synchronized (mPackages) {
8982                        dexOptDialogShown = mDexOptDialogShown;
8983                    }
8984                    if (!isFirstBoot() && dexOptDialogShown) {
8985                        try {
8986                            ActivityManager.getService().showBootMessage(
8987                                    mContext.getResources().getString(
8988                                            R.string.android_upgrading_fstrim), true);
8989                        } catch (RemoteException e) {
8990                        }
8991                    }
8992                    sm.runMaintenance();
8993                }
8994            } else {
8995                Slog.e(TAG, "storageManager service unavailable!");
8996            }
8997        } catch (RemoteException e) {
8998            // Can't happen; StorageManagerService is local
8999        }
9000    }
9001
9002    @Override
9003    public void updatePackagesIfNeeded() {
9004        enforceSystemOrRoot("Only the system can request package update");
9005
9006        // We need to re-extract after an OTA.
9007        boolean causeUpgrade = isUpgrade();
9008
9009        // First boot or factory reset.
9010        // Note: we also handle devices that are upgrading to N right now as if it is their
9011        //       first boot, as they do not have profile data.
9012        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9013
9014        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9015        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9016
9017        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9018            return;
9019        }
9020
9021        List<PackageParser.Package> pkgs;
9022        synchronized (mPackages) {
9023            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9024        }
9025
9026        final long startTime = System.nanoTime();
9027        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9028                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9029                    false /* bootComplete */);
9030
9031        final int elapsedTimeSeconds =
9032                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9033
9034        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9035        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9036        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9037        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9038        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9039    }
9040
9041    /*
9042     * Return the prebuilt profile path given a package base code path.
9043     */
9044    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9045        return pkg.baseCodePath + ".prof";
9046    }
9047
9048    /**
9049     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9050     * containing statistics about the invocation. The array consists of three elements,
9051     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9052     * and {@code numberOfPackagesFailed}.
9053     */
9054    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9055            final String compilerFilter, boolean bootComplete) {
9056
9057        int numberOfPackagesVisited = 0;
9058        int numberOfPackagesOptimized = 0;
9059        int numberOfPackagesSkipped = 0;
9060        int numberOfPackagesFailed = 0;
9061        final int numberOfPackagesToDexopt = pkgs.size();
9062
9063        for (PackageParser.Package pkg : pkgs) {
9064            numberOfPackagesVisited++;
9065
9066            boolean useProfileForDexopt = false;
9067
9068            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9069                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9070                // that are already compiled.
9071                File profileFile = new File(getPrebuildProfilePath(pkg));
9072                // Copy profile if it exists.
9073                if (profileFile.exists()) {
9074                    try {
9075                        // We could also do this lazily before calling dexopt in
9076                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9077                        // is that we don't have a good way to say "do this only once".
9078                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9079                                pkg.applicationInfo.uid, pkg.packageName)) {
9080                            Log.e(TAG, "Installer failed to copy system profile!");
9081                        } else {
9082                            // Disabled as this causes speed-profile compilation during first boot
9083                            // even if things are already compiled.
9084                            // useProfileForDexopt = true;
9085                        }
9086                    } catch (Exception e) {
9087                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9088                                e);
9089                    }
9090                } else {
9091                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9092                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9093                    // minimize the number off apps being speed-profile compiled during first boot.
9094                    // The other paths will not change the filter.
9095                    if (disabledPs != null && disabledPs.pkg.isStub) {
9096                        // The package is the stub one, remove the stub suffix to get the normal
9097                        // package and APK names.
9098                        String systemProfilePath =
9099                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9100                        profileFile = new File(systemProfilePath);
9101                        // If we have a profile for a compressed APK, copy it to the reference
9102                        // location.
9103                        // Note that copying the profile here will cause it to override the
9104                        // reference profile every OTA even though the existing reference profile
9105                        // may have more data. We can't copy during decompression since the
9106                        // directories are not set up at that point.
9107                        if (profileFile.exists()) {
9108                            try {
9109                                // We could also do this lazily before calling dexopt in
9110                                // PackageDexOptimizer to prevent this happening on first boot. The
9111                                // issue is that we don't have a good way to say "do this only
9112                                // once".
9113                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9114                                        pkg.applicationInfo.uid, pkg.packageName)) {
9115                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9116                                } else {
9117                                    useProfileForDexopt = true;
9118                                }
9119                            } catch (Exception e) {
9120                                Log.e(TAG, "Failed to copy profile " +
9121                                        profileFile.getAbsolutePath() + " ", e);
9122                            }
9123                        }
9124                    }
9125                }
9126            }
9127
9128            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9129                if (DEBUG_DEXOPT) {
9130                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9131                }
9132                numberOfPackagesSkipped++;
9133                continue;
9134            }
9135
9136            if (DEBUG_DEXOPT) {
9137                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9138                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9139            }
9140
9141            if (showDialog) {
9142                try {
9143                    ActivityManager.getService().showBootMessage(
9144                            mContext.getResources().getString(R.string.android_upgrading_apk,
9145                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9146                } catch (RemoteException e) {
9147                }
9148                synchronized (mPackages) {
9149                    mDexOptDialogShown = true;
9150                }
9151            }
9152
9153            String pkgCompilerFilter = compilerFilter;
9154            if (useProfileForDexopt) {
9155                // Use background dexopt mode to try and use the profile. Note that this does not
9156                // guarantee usage of the profile.
9157                pkgCompilerFilter =
9158                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9159                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9160            }
9161
9162            // checkProfiles is false to avoid merging profiles during boot which
9163            // might interfere with background compilation (b/28612421).
9164            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9165            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9166            // trade-off worth doing to save boot time work.
9167            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9168            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9169                    pkg.packageName,
9170                    pkgCompilerFilter,
9171                    dexoptFlags));
9172
9173            switch (primaryDexOptStaus) {
9174                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9175                    numberOfPackagesOptimized++;
9176                    break;
9177                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9178                    numberOfPackagesSkipped++;
9179                    break;
9180                case PackageDexOptimizer.DEX_OPT_FAILED:
9181                    numberOfPackagesFailed++;
9182                    break;
9183                default:
9184                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9185                    break;
9186            }
9187        }
9188
9189        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9190                numberOfPackagesFailed };
9191    }
9192
9193    @Override
9194    public void notifyPackageUse(String packageName, int reason) {
9195        synchronized (mPackages) {
9196            final int callingUid = Binder.getCallingUid();
9197            final int callingUserId = UserHandle.getUserId(callingUid);
9198            if (getInstantAppPackageName(callingUid) != null) {
9199                if (!isCallerSameApp(packageName, callingUid)) {
9200                    return;
9201                }
9202            } else {
9203                if (isInstantApp(packageName, callingUserId)) {
9204                    return;
9205                }
9206            }
9207            notifyPackageUseLocked(packageName, reason);
9208        }
9209    }
9210
9211    private void notifyPackageUseLocked(String packageName, int reason) {
9212        final PackageParser.Package p = mPackages.get(packageName);
9213        if (p == null) {
9214            return;
9215        }
9216        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9217    }
9218
9219    @Override
9220    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9221            List<String> classPaths, String loaderIsa) {
9222        int userId = UserHandle.getCallingUserId();
9223        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9224        if (ai == null) {
9225            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9226                + loadingPackageName + ", user=" + userId);
9227            return;
9228        }
9229        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9230    }
9231
9232    @Override
9233    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9234            IDexModuleRegisterCallback callback) {
9235        int userId = UserHandle.getCallingUserId();
9236        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9237        DexManager.RegisterDexModuleResult result;
9238        if (ai == null) {
9239            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9240                     " calling user. package=" + packageName + ", user=" + userId);
9241            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9242        } else {
9243            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9244        }
9245
9246        if (callback != null) {
9247            mHandler.post(() -> {
9248                try {
9249                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9250                } catch (RemoteException e) {
9251                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9252                }
9253            });
9254        }
9255    }
9256
9257    /**
9258     * Ask the package manager to perform a dex-opt with the given compiler filter.
9259     *
9260     * Note: exposed only for the shell command to allow moving packages explicitly to a
9261     *       definite state.
9262     */
9263    @Override
9264    public boolean performDexOptMode(String packageName,
9265            boolean checkProfiles, String targetCompilerFilter, boolean force,
9266            boolean bootComplete, String splitName) {
9267        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9268                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9269                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9270        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9271                splitName, flags));
9272    }
9273
9274    /**
9275     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9276     * secondary dex files belonging to the given package.
9277     *
9278     * Note: exposed only for the shell command to allow moving packages explicitly to a
9279     *       definite state.
9280     */
9281    @Override
9282    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9283            boolean force) {
9284        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9285                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9286                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9287                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9288        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9289    }
9290
9291    /*package*/ boolean performDexOpt(DexoptOptions options) {
9292        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9293            return false;
9294        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9295            return false;
9296        }
9297
9298        if (options.isDexoptOnlySecondaryDex()) {
9299            return mDexManager.dexoptSecondaryDex(options);
9300        } else {
9301            int dexoptStatus = performDexOptWithStatus(options);
9302            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9303        }
9304    }
9305
9306    /**
9307     * Perform dexopt on the given package and return one of following result:
9308     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9309     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9310     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9311     */
9312    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9313        return performDexOptTraced(options);
9314    }
9315
9316    private int performDexOptTraced(DexoptOptions options) {
9317        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9318        try {
9319            return performDexOptInternal(options);
9320        } finally {
9321            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9322        }
9323    }
9324
9325    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9326    // if the package can now be considered up to date for the given filter.
9327    private int performDexOptInternal(DexoptOptions options) {
9328        PackageParser.Package p;
9329        synchronized (mPackages) {
9330            p = mPackages.get(options.getPackageName());
9331            if (p == null) {
9332                // Package could not be found. Report failure.
9333                return PackageDexOptimizer.DEX_OPT_FAILED;
9334            }
9335            mPackageUsage.maybeWriteAsync(mPackages);
9336            mCompilerStats.maybeWriteAsync();
9337        }
9338        long callingId = Binder.clearCallingIdentity();
9339        try {
9340            synchronized (mInstallLock) {
9341                return performDexOptInternalWithDependenciesLI(p, options);
9342            }
9343        } finally {
9344            Binder.restoreCallingIdentity(callingId);
9345        }
9346    }
9347
9348    public ArraySet<String> getOptimizablePackages() {
9349        ArraySet<String> pkgs = new ArraySet<String>();
9350        synchronized (mPackages) {
9351            for (PackageParser.Package p : mPackages.values()) {
9352                if (PackageDexOptimizer.canOptimizePackage(p)) {
9353                    pkgs.add(p.packageName);
9354                }
9355            }
9356        }
9357        return pkgs;
9358    }
9359
9360    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9361            DexoptOptions options) {
9362        // Select the dex optimizer based on the force parameter.
9363        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9364        //       allocate an object here.
9365        PackageDexOptimizer pdo = options.isForce()
9366                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9367                : mPackageDexOptimizer;
9368
9369        // Dexopt all dependencies first. Note: we ignore the return value and march on
9370        // on errors.
9371        // Note that we are going to call performDexOpt on those libraries as many times as
9372        // they are referenced in packages. When we do a batch of performDexOpt (for example
9373        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9374        // and the first package that uses the library will dexopt it. The
9375        // others will see that the compiled code for the library is up to date.
9376        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9377        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9378        if (!deps.isEmpty()) {
9379            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9380                    options.getCompilerFilter(), options.getSplitName(),
9381                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9382            for (PackageParser.Package depPackage : deps) {
9383                // TODO: Analyze and investigate if we (should) profile libraries.
9384                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9385                        getOrCreateCompilerPackageStats(depPackage),
9386                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9387            }
9388        }
9389        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9390                getOrCreateCompilerPackageStats(p),
9391                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9392    }
9393
9394    /**
9395     * Reconcile the information we have about the secondary dex files belonging to
9396     * {@code packagName} and the actual dex files. For all dex files that were
9397     * deleted, update the internal records and delete the generated oat files.
9398     */
9399    @Override
9400    public void reconcileSecondaryDexFiles(String packageName) {
9401        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9402            return;
9403        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9404            return;
9405        }
9406        mDexManager.reconcileSecondaryDexFiles(packageName);
9407    }
9408
9409    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9410    // a reference there.
9411    /*package*/ DexManager getDexManager() {
9412        return mDexManager;
9413    }
9414
9415    /**
9416     * Execute the background dexopt job immediately.
9417     */
9418    @Override
9419    public boolean runBackgroundDexoptJob() {
9420        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9421            return false;
9422        }
9423        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9424    }
9425
9426    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9427        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9428                || p.usesStaticLibraries != null) {
9429            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9430            Set<String> collectedNames = new HashSet<>();
9431            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9432
9433            retValue.remove(p);
9434
9435            return retValue;
9436        } else {
9437            return Collections.emptyList();
9438        }
9439    }
9440
9441    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9442            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9443        if (!collectedNames.contains(p.packageName)) {
9444            collectedNames.add(p.packageName);
9445            collected.add(p);
9446
9447            if (p.usesLibraries != null) {
9448                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9449                        null, collected, collectedNames);
9450            }
9451            if (p.usesOptionalLibraries != null) {
9452                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9453                        null, collected, collectedNames);
9454            }
9455            if (p.usesStaticLibraries != null) {
9456                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9457                        p.usesStaticLibrariesVersions, collected, collectedNames);
9458            }
9459        }
9460    }
9461
9462    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9463            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9464        final int libNameCount = libs.size();
9465        for (int i = 0; i < libNameCount; i++) {
9466            String libName = libs.get(i);
9467            int version = (versions != null && versions.length == libNameCount)
9468                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9469            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9470            if (libPkg != null) {
9471                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9472            }
9473        }
9474    }
9475
9476    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9477        synchronized (mPackages) {
9478            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9479            if (libEntry != null) {
9480                return mPackages.get(libEntry.apk);
9481            }
9482            return null;
9483        }
9484    }
9485
9486    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9487        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9488        if (versionedLib == null) {
9489            return null;
9490        }
9491        return versionedLib.get(version);
9492    }
9493
9494    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9495        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9496                pkg.staticSharedLibName);
9497        if (versionedLib == null) {
9498            return null;
9499        }
9500        int previousLibVersion = -1;
9501        final int versionCount = versionedLib.size();
9502        for (int i = 0; i < versionCount; i++) {
9503            final int libVersion = versionedLib.keyAt(i);
9504            if (libVersion < pkg.staticSharedLibVersion) {
9505                previousLibVersion = Math.max(previousLibVersion, libVersion);
9506            }
9507        }
9508        if (previousLibVersion >= 0) {
9509            return versionedLib.get(previousLibVersion);
9510        }
9511        return null;
9512    }
9513
9514    public void shutdown() {
9515        mPackageUsage.writeNow(mPackages);
9516        mCompilerStats.writeNow();
9517        mDexManager.writePackageDexUsageNow();
9518    }
9519
9520    @Override
9521    public void dumpProfiles(String packageName) {
9522        PackageParser.Package pkg;
9523        synchronized (mPackages) {
9524            pkg = mPackages.get(packageName);
9525            if (pkg == null) {
9526                throw new IllegalArgumentException("Unknown package: " + packageName);
9527            }
9528        }
9529        /* Only the shell, root, or the app user should be able to dump profiles. */
9530        int callingUid = Binder.getCallingUid();
9531        if (callingUid != Process.SHELL_UID &&
9532            callingUid != Process.ROOT_UID &&
9533            callingUid != pkg.applicationInfo.uid) {
9534            throw new SecurityException("dumpProfiles");
9535        }
9536
9537        synchronized (mInstallLock) {
9538            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9539            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9540            try {
9541                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9542                String codePaths = TextUtils.join(";", allCodePaths);
9543                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9544            } catch (InstallerException e) {
9545                Slog.w(TAG, "Failed to dump profiles", e);
9546            }
9547            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9548        }
9549    }
9550
9551    @Override
9552    public void forceDexOpt(String packageName) {
9553        enforceSystemOrRoot("forceDexOpt");
9554
9555        PackageParser.Package pkg;
9556        synchronized (mPackages) {
9557            pkg = mPackages.get(packageName);
9558            if (pkg == null) {
9559                throw new IllegalArgumentException("Unknown package: " + packageName);
9560            }
9561        }
9562
9563        synchronized (mInstallLock) {
9564            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9565
9566            // Whoever is calling forceDexOpt wants a compiled package.
9567            // Don't use profiles since that may cause compilation to be skipped.
9568            final int res = performDexOptInternalWithDependenciesLI(
9569                    pkg,
9570                    new DexoptOptions(packageName,
9571                            getDefaultCompilerFilter(),
9572                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9573
9574            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9575            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9576                throw new IllegalStateException("Failed to dexopt: " + res);
9577            }
9578        }
9579    }
9580
9581    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9582        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9583            Slog.w(TAG, "Unable to update from " + oldPkg.name
9584                    + " to " + newPkg.packageName
9585                    + ": old package not in system partition");
9586            return false;
9587        } else if (mPackages.get(oldPkg.name) != null) {
9588            Slog.w(TAG, "Unable to update from " + oldPkg.name
9589                    + " to " + newPkg.packageName
9590                    + ": old package still exists");
9591            return false;
9592        }
9593        return true;
9594    }
9595
9596    void removeCodePathLI(File codePath) {
9597        if (codePath.isDirectory()) {
9598            try {
9599                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9600            } catch (InstallerException e) {
9601                Slog.w(TAG, "Failed to remove code path", e);
9602            }
9603        } else {
9604            codePath.delete();
9605        }
9606    }
9607
9608    private int[] resolveUserIds(int userId) {
9609        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9610    }
9611
9612    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9613        if (pkg == null) {
9614            Slog.wtf(TAG, "Package was null!", new Throwable());
9615            return;
9616        }
9617        clearAppDataLeafLIF(pkg, userId, flags);
9618        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9619        for (int i = 0; i < childCount; i++) {
9620            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9621        }
9622    }
9623
9624    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9625        final PackageSetting ps;
9626        synchronized (mPackages) {
9627            ps = mSettings.mPackages.get(pkg.packageName);
9628        }
9629        for (int realUserId : resolveUserIds(userId)) {
9630            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9631            try {
9632                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9633                        ceDataInode);
9634            } catch (InstallerException e) {
9635                Slog.w(TAG, String.valueOf(e));
9636            }
9637        }
9638    }
9639
9640    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9641        if (pkg == null) {
9642            Slog.wtf(TAG, "Package was null!", new Throwable());
9643            return;
9644        }
9645        destroyAppDataLeafLIF(pkg, userId, flags);
9646        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9647        for (int i = 0; i < childCount; i++) {
9648            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9649        }
9650    }
9651
9652    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9653        final PackageSetting ps;
9654        synchronized (mPackages) {
9655            ps = mSettings.mPackages.get(pkg.packageName);
9656        }
9657        for (int realUserId : resolveUserIds(userId)) {
9658            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9659            try {
9660                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9661                        ceDataInode);
9662            } catch (InstallerException e) {
9663                Slog.w(TAG, String.valueOf(e));
9664            }
9665            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9666        }
9667    }
9668
9669    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9670        if (pkg == null) {
9671            Slog.wtf(TAG, "Package was null!", new Throwable());
9672            return;
9673        }
9674        destroyAppProfilesLeafLIF(pkg);
9675        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9676        for (int i = 0; i < childCount; i++) {
9677            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9678        }
9679    }
9680
9681    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9682        try {
9683            mInstaller.destroyAppProfiles(pkg.packageName);
9684        } catch (InstallerException e) {
9685            Slog.w(TAG, String.valueOf(e));
9686        }
9687    }
9688
9689    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9690        if (pkg == null) {
9691            Slog.wtf(TAG, "Package was null!", new Throwable());
9692            return;
9693        }
9694        clearAppProfilesLeafLIF(pkg);
9695        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9696        for (int i = 0; i < childCount; i++) {
9697            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9698        }
9699    }
9700
9701    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9702        try {
9703            mInstaller.clearAppProfiles(pkg.packageName);
9704        } catch (InstallerException e) {
9705            Slog.w(TAG, String.valueOf(e));
9706        }
9707    }
9708
9709    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9710            long lastUpdateTime) {
9711        // Set parent install/update time
9712        PackageSetting ps = (PackageSetting) pkg.mExtras;
9713        if (ps != null) {
9714            ps.firstInstallTime = firstInstallTime;
9715            ps.lastUpdateTime = lastUpdateTime;
9716        }
9717        // Set children install/update time
9718        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9719        for (int i = 0; i < childCount; i++) {
9720            PackageParser.Package childPkg = pkg.childPackages.get(i);
9721            ps = (PackageSetting) childPkg.mExtras;
9722            if (ps != null) {
9723                ps.firstInstallTime = firstInstallTime;
9724                ps.lastUpdateTime = lastUpdateTime;
9725            }
9726        }
9727    }
9728
9729    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9730            SharedLibraryEntry file,
9731            PackageParser.Package changingLib) {
9732        if (file.path != null) {
9733            usesLibraryFiles.add(file.path);
9734            return;
9735        }
9736        PackageParser.Package p = mPackages.get(file.apk);
9737        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9738            // If we are doing this while in the middle of updating a library apk,
9739            // then we need to make sure to use that new apk for determining the
9740            // dependencies here.  (We haven't yet finished committing the new apk
9741            // to the package manager state.)
9742            if (p == null || p.packageName.equals(changingLib.packageName)) {
9743                p = changingLib;
9744            }
9745        }
9746        if (p != null) {
9747            usesLibraryFiles.addAll(p.getAllCodePaths());
9748            if (p.usesLibraryFiles != null) {
9749                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9750            }
9751        }
9752    }
9753
9754    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9755            PackageParser.Package changingLib) throws PackageManagerException {
9756        if (pkg == null) {
9757            return;
9758        }
9759        // The collection used here must maintain the order of addition (so
9760        // that libraries are searched in the correct order) and must have no
9761        // duplicates.
9762        Set<String> usesLibraryFiles = null;
9763        if (pkg.usesLibraries != null) {
9764            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9765                    null, null, pkg.packageName, changingLib, true,
9766                    pkg.applicationInfo.targetSdkVersion, null);
9767        }
9768        if (pkg.usesStaticLibraries != null) {
9769            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9770                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9771                    pkg.packageName, changingLib, true,
9772                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9773        }
9774        if (pkg.usesOptionalLibraries != null) {
9775            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9776                    null, null, pkg.packageName, changingLib, false,
9777                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9778        }
9779        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9780            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9781        } else {
9782            pkg.usesLibraryFiles = null;
9783        }
9784    }
9785
9786    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9787            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
9788            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9789            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9790            throws PackageManagerException {
9791        final int libCount = requestedLibraries.size();
9792        for (int i = 0; i < libCount; i++) {
9793            final String libName = requestedLibraries.get(i);
9794            final int libVersion = requiredVersions != null ? requiredVersions[i]
9795                    : SharedLibraryInfo.VERSION_UNDEFINED;
9796            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9797            if (libEntry == null) {
9798                if (required) {
9799                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9800                            "Package " + packageName + " requires unavailable shared library "
9801                                    + libName + "; failing!");
9802                } else if (DEBUG_SHARED_LIBRARIES) {
9803                    Slog.i(TAG, "Package " + packageName
9804                            + " desires unavailable shared library "
9805                            + libName + "; ignoring!");
9806                }
9807            } else {
9808                if (requiredVersions != null && requiredCertDigests != null) {
9809                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9810                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9811                            "Package " + packageName + " requires unavailable static shared"
9812                                    + " library " + libName + " version "
9813                                    + libEntry.info.getVersion() + "; failing!");
9814                    }
9815
9816                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9817                    if (libPkg == null) {
9818                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9819                                "Package " + packageName + " requires unavailable static shared"
9820                                        + " library; failing!");
9821                    }
9822
9823                    final String[] expectedCertDigests = requiredCertDigests[i];
9824                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9825                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9826                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9827                            : PackageUtils.computeSignaturesSha256Digests(
9828                                    new Signature[]{libPkg.mSignatures[0]});
9829
9830                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9831                    // target O we don't parse the "additional-certificate" tags similarly
9832                    // how we only consider all certs only for apps targeting O (see above).
9833                    // Therefore, the size check is safe to make.
9834                    if (expectedCertDigests.length != libCertDigests.length) {
9835                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9836                                "Package " + packageName + " requires differently signed" +
9837                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9838                    }
9839
9840                    // Use a predictable order as signature order may vary
9841                    Arrays.sort(libCertDigests);
9842                    Arrays.sort(expectedCertDigests);
9843
9844                    final int certCount = libCertDigests.length;
9845                    for (int j = 0; j < certCount; j++) {
9846                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9847                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9848                                    "Package " + packageName + " requires differently signed" +
9849                                            " static shared library; failing!");
9850                        }
9851                    }
9852                }
9853
9854                if (outUsedLibraries == null) {
9855                    // Use LinkedHashSet to preserve the order of files added to
9856                    // usesLibraryFiles while eliminating duplicates.
9857                    outUsedLibraries = new LinkedHashSet<>();
9858                }
9859                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9860            }
9861        }
9862        return outUsedLibraries;
9863    }
9864
9865    private static boolean hasString(List<String> list, List<String> which) {
9866        if (list == null) {
9867            return false;
9868        }
9869        for (int i=list.size()-1; i>=0; i--) {
9870            for (int j=which.size()-1; j>=0; j--) {
9871                if (which.get(j).equals(list.get(i))) {
9872                    return true;
9873                }
9874            }
9875        }
9876        return false;
9877    }
9878
9879    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9880            PackageParser.Package changingPkg) {
9881        ArrayList<PackageParser.Package> res = null;
9882        for (PackageParser.Package pkg : mPackages.values()) {
9883            if (changingPkg != null
9884                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9885                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9886                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9887                            changingPkg.staticSharedLibName)) {
9888                return null;
9889            }
9890            if (res == null) {
9891                res = new ArrayList<>();
9892            }
9893            res.add(pkg);
9894            try {
9895                updateSharedLibrariesLPr(pkg, changingPkg);
9896            } catch (PackageManagerException e) {
9897                // If a system app update or an app and a required lib missing we
9898                // delete the package and for updated system apps keep the data as
9899                // it is better for the user to reinstall than to be in an limbo
9900                // state. Also libs disappearing under an app should never happen
9901                // - just in case.
9902                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9903                    final int flags = pkg.isUpdatedSystemApp()
9904                            ? PackageManager.DELETE_KEEP_DATA : 0;
9905                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9906                            flags , null, true, null);
9907                }
9908                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9909            }
9910        }
9911        return res;
9912    }
9913
9914    /**
9915     * Derive the value of the {@code cpuAbiOverride} based on the provided
9916     * value and an optional stored value from the package settings.
9917     */
9918    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9919        String cpuAbiOverride = null;
9920
9921        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9922            cpuAbiOverride = null;
9923        } else if (abiOverride != null) {
9924            cpuAbiOverride = abiOverride;
9925        } else if (settings != null) {
9926            cpuAbiOverride = settings.cpuAbiOverrideString;
9927        }
9928
9929        return cpuAbiOverride;
9930    }
9931
9932    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9933            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9934                    throws PackageManagerException {
9935        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9936        // If the package has children and this is the first dive in the function
9937        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9938        // whether all packages (parent and children) would be successfully scanned
9939        // before the actual scan since scanning mutates internal state and we want
9940        // to atomically install the package and its children.
9941        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9942            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9943                scanFlags |= SCAN_CHECK_ONLY;
9944            }
9945        } else {
9946            scanFlags &= ~SCAN_CHECK_ONLY;
9947        }
9948
9949        final PackageParser.Package scannedPkg;
9950        try {
9951            // Scan the parent
9952            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9953            // Scan the children
9954            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9955            for (int i = 0; i < childCount; i++) {
9956                PackageParser.Package childPkg = pkg.childPackages.get(i);
9957                scanPackageLI(childPkg, policyFlags,
9958                        scanFlags, currentTime, user);
9959            }
9960        } finally {
9961            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9962        }
9963
9964        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9965            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9966        }
9967
9968        return scannedPkg;
9969    }
9970
9971    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9972            int scanFlags, long currentTime, @Nullable UserHandle user)
9973                    throws PackageManagerException {
9974        boolean success = false;
9975        try {
9976            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9977                    currentTime, user);
9978            success = true;
9979            return res;
9980        } finally {
9981            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9982                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9983                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9984                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9985                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9986            }
9987        }
9988    }
9989
9990    /**
9991     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9992     */
9993    private static boolean apkHasCode(String fileName) {
9994        StrictJarFile jarFile = null;
9995        try {
9996            jarFile = new StrictJarFile(fileName,
9997                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9998            return jarFile.findEntry("classes.dex") != null;
9999        } catch (IOException ignore) {
10000        } finally {
10001            try {
10002                if (jarFile != null) {
10003                    jarFile.close();
10004                }
10005            } catch (IOException ignore) {}
10006        }
10007        return false;
10008    }
10009
10010    /**
10011     * Enforces code policy for the package. This ensures that if an APK has
10012     * declared hasCode="true" in its manifest that the APK actually contains
10013     * code.
10014     *
10015     * @throws PackageManagerException If bytecode could not be found when it should exist
10016     */
10017    private static void assertCodePolicy(PackageParser.Package pkg)
10018            throws PackageManagerException {
10019        final boolean shouldHaveCode =
10020                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10021        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10022            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10023                    "Package " + pkg.baseCodePath + " code is missing");
10024        }
10025
10026        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10027            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10028                final boolean splitShouldHaveCode =
10029                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10030                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10031                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10032                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10033                }
10034            }
10035        }
10036    }
10037
10038    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10039            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10040                    throws PackageManagerException {
10041        if (DEBUG_PACKAGE_SCANNING) {
10042            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10043                Log.d(TAG, "Scanning package " + pkg.packageName);
10044        }
10045
10046        applyPolicy(pkg, policyFlags);
10047
10048        assertPackageIsValid(pkg, policyFlags, scanFlags);
10049
10050        if (Build.IS_DEBUGGABLE &&
10051                pkg.isPrivilegedApp() &&
10052                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10053            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10054        }
10055
10056        // Initialize package source and resource directories
10057        final File scanFile = new File(pkg.codePath);
10058        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10059        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10060
10061        SharedUserSetting suid = null;
10062        PackageSetting pkgSetting = null;
10063
10064        // Getting the package setting may have a side-effect, so if we
10065        // are only checking if scan would succeed, stash a copy of the
10066        // old setting to restore at the end.
10067        PackageSetting nonMutatedPs = null;
10068
10069        // We keep references to the derived CPU Abis from settings in oder to reuse
10070        // them in the case where we're not upgrading or booting for the first time.
10071        String primaryCpuAbiFromSettings = null;
10072        String secondaryCpuAbiFromSettings = null;
10073
10074        // writer
10075        synchronized (mPackages) {
10076            if (pkg.mSharedUserId != null) {
10077                // SIDE EFFECTS; may potentially allocate a new shared user
10078                suid = mSettings.getSharedUserLPw(
10079                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10080                if (DEBUG_PACKAGE_SCANNING) {
10081                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10082                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10083                                + "): packages=" + suid.packages);
10084                }
10085            }
10086
10087            // Check if we are renaming from an original package name.
10088            PackageSetting origPackage = null;
10089            String realName = null;
10090            if (pkg.mOriginalPackages != null) {
10091                // This package may need to be renamed to a previously
10092                // installed name.  Let's check on that...
10093                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10094                if (pkg.mOriginalPackages.contains(renamed)) {
10095                    // This package had originally been installed as the
10096                    // original name, and we have already taken care of
10097                    // transitioning to the new one.  Just update the new
10098                    // one to continue using the old name.
10099                    realName = pkg.mRealPackage;
10100                    if (!pkg.packageName.equals(renamed)) {
10101                        // Callers into this function may have already taken
10102                        // care of renaming the package; only do it here if
10103                        // it is not already done.
10104                        pkg.setPackageName(renamed);
10105                    }
10106                } else {
10107                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10108                        if ((origPackage = mSettings.getPackageLPr(
10109                                pkg.mOriginalPackages.get(i))) != null) {
10110                            // We do have the package already installed under its
10111                            // original name...  should we use it?
10112                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10113                                // New package is not compatible with original.
10114                                origPackage = null;
10115                                continue;
10116                            } else if (origPackage.sharedUser != null) {
10117                                // Make sure uid is compatible between packages.
10118                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10119                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10120                                            + " to " + pkg.packageName + ": old uid "
10121                                            + origPackage.sharedUser.name
10122                                            + " differs from " + pkg.mSharedUserId);
10123                                    origPackage = null;
10124                                    continue;
10125                                }
10126                                // TODO: Add case when shared user id is added [b/28144775]
10127                            } else {
10128                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10129                                        + pkg.packageName + " to old name " + origPackage.name);
10130                            }
10131                            break;
10132                        }
10133                    }
10134                }
10135            }
10136
10137            if (mTransferedPackages.contains(pkg.packageName)) {
10138                Slog.w(TAG, "Package " + pkg.packageName
10139                        + " was transferred to another, but its .apk remains");
10140            }
10141
10142            // See comments in nonMutatedPs declaration
10143            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10144                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10145                if (foundPs != null) {
10146                    nonMutatedPs = new PackageSetting(foundPs);
10147                }
10148            }
10149
10150            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10151                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10152                if (foundPs != null) {
10153                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10154                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10155                }
10156            }
10157
10158            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10159            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10160                PackageManagerService.reportSettingsProblem(Log.WARN,
10161                        "Package " + pkg.packageName + " shared user changed from "
10162                                + (pkgSetting.sharedUser != null
10163                                        ? pkgSetting.sharedUser.name : "<nothing>")
10164                                + " to "
10165                                + (suid != null ? suid.name : "<nothing>")
10166                                + "; replacing with new");
10167                pkgSetting = null;
10168            }
10169            final PackageSetting oldPkgSetting =
10170                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10171            final PackageSetting disabledPkgSetting =
10172                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10173
10174            String[] usesStaticLibraries = null;
10175            if (pkg.usesStaticLibraries != null) {
10176                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10177                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10178            }
10179
10180            if (pkgSetting == null) {
10181                final String parentPackageName = (pkg.parentPackage != null)
10182                        ? pkg.parentPackage.packageName : null;
10183                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10184                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10185                // REMOVE SharedUserSetting from method; update in a separate call
10186                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10187                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10188                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10189                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10190                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10191                        true /*allowInstall*/, instantApp, virtualPreload,
10192                        parentPackageName, pkg.getChildPackageNames(),
10193                        UserManagerService.getInstance(), usesStaticLibraries,
10194                        pkg.usesStaticLibrariesVersions);
10195                // SIDE EFFECTS; updates system state; move elsewhere
10196                if (origPackage != null) {
10197                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10198                }
10199                mSettings.addUserToSettingLPw(pkgSetting);
10200            } else {
10201                // REMOVE SharedUserSetting from method; update in a separate call.
10202                //
10203                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10204                // secondaryCpuAbi are not known at this point so we always update them
10205                // to null here, only to reset them at a later point.
10206                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10207                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10208                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10209                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10210                        UserManagerService.getInstance(), usesStaticLibraries,
10211                        pkg.usesStaticLibrariesVersions);
10212            }
10213            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10214            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10215
10216            // SIDE EFFECTS; modifies system state; move elsewhere
10217            if (pkgSetting.origPackage != null) {
10218                // If we are first transitioning from an original package,
10219                // fix up the new package's name now.  We need to do this after
10220                // looking up the package under its new name, so getPackageLP
10221                // can take care of fiddling things correctly.
10222                pkg.setPackageName(origPackage.name);
10223
10224                // File a report about this.
10225                String msg = "New package " + pkgSetting.realName
10226                        + " renamed to replace old package " + pkgSetting.name;
10227                reportSettingsProblem(Log.WARN, msg);
10228
10229                // Make a note of it.
10230                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10231                    mTransferedPackages.add(origPackage.name);
10232                }
10233
10234                // No longer need to retain this.
10235                pkgSetting.origPackage = null;
10236            }
10237
10238            // SIDE EFFECTS; modifies system state; move elsewhere
10239            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10240                // Make a note of it.
10241                mTransferedPackages.add(pkg.packageName);
10242            }
10243
10244            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10245                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10246            }
10247
10248            if ((scanFlags & SCAN_BOOTING) == 0
10249                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10250                // Check all shared libraries and map to their actual file path.
10251                // We only do this here for apps not on a system dir, because those
10252                // are the only ones that can fail an install due to this.  We
10253                // will take care of the system apps by updating all of their
10254                // library paths after the scan is done. Also during the initial
10255                // scan don't update any libs as we do this wholesale after all
10256                // apps are scanned to avoid dependency based scanning.
10257                updateSharedLibrariesLPr(pkg, null);
10258            }
10259
10260            if (mFoundPolicyFile) {
10261                SELinuxMMAC.assignSeInfoValue(pkg);
10262            }
10263            pkg.applicationInfo.uid = pkgSetting.appId;
10264            pkg.mExtras = pkgSetting;
10265
10266
10267            // Static shared libs have same package with different versions where
10268            // we internally use a synthetic package name to allow multiple versions
10269            // of the same package, therefore we need to compare signatures against
10270            // the package setting for the latest library version.
10271            PackageSetting signatureCheckPs = pkgSetting;
10272            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10273                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10274                if (libraryEntry != null) {
10275                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10276                }
10277            }
10278
10279            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10280                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10281                    // We just determined the app is signed correctly, so bring
10282                    // over the latest parsed certs.
10283                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10284                } else {
10285                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10286                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10287                                "Package " + pkg.packageName + " upgrade keys do not match the "
10288                                + "previously installed version");
10289                    } else {
10290                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10291                        String msg = "System package " + pkg.packageName
10292                                + " signature changed; retaining data.";
10293                        reportSettingsProblem(Log.WARN, msg);
10294                    }
10295                }
10296            } else {
10297                try {
10298                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10299                    verifySignaturesLP(signatureCheckPs, pkg);
10300                    // We just determined the app is signed correctly, so bring
10301                    // over the latest parsed certs.
10302                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10303                } catch (PackageManagerException e) {
10304                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10305                        throw e;
10306                    }
10307                    // The signature has changed, but this package is in the system
10308                    // image...  let's recover!
10309                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10310                    // However...  if this package is part of a shared user, but it
10311                    // doesn't match the signature of the shared user, let's fail.
10312                    // What this means is that you can't change the signatures
10313                    // associated with an overall shared user, which doesn't seem all
10314                    // that unreasonable.
10315                    if (signatureCheckPs.sharedUser != null) {
10316                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10317                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10318                            throw new PackageManagerException(
10319                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10320                                    "Signature mismatch for shared user: "
10321                                            + pkgSetting.sharedUser);
10322                        }
10323                    }
10324                    // File a report about this.
10325                    String msg = "System package " + pkg.packageName
10326                            + " signature changed; retaining data.";
10327                    reportSettingsProblem(Log.WARN, msg);
10328                }
10329            }
10330
10331            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10332                // This package wants to adopt ownership of permissions from
10333                // another package.
10334                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10335                    final String origName = pkg.mAdoptPermissions.get(i);
10336                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10337                    if (orig != null) {
10338                        if (verifyPackageUpdateLPr(orig, pkg)) {
10339                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10340                                    + pkg.packageName);
10341                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10342                            mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10343                        }
10344                    }
10345                }
10346            }
10347        }
10348
10349        pkg.applicationInfo.processName = fixProcessName(
10350                pkg.applicationInfo.packageName,
10351                pkg.applicationInfo.processName);
10352
10353        if (pkg != mPlatformPackage) {
10354            // Get all of our default paths setup
10355            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10356        }
10357
10358        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10359
10360        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10361            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10362                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10363                final boolean extractNativeLibs = !pkg.isLibrary();
10364                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10365                        mAppLib32InstallDir);
10366                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10367
10368                // Some system apps still use directory structure for native libraries
10369                // in which case we might end up not detecting abi solely based on apk
10370                // structure. Try to detect abi based on directory structure.
10371                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10372                        pkg.applicationInfo.primaryCpuAbi == null) {
10373                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10374                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10375                }
10376            } else {
10377                // This is not a first boot or an upgrade, don't bother deriving the
10378                // ABI during the scan. Instead, trust the value that was stored in the
10379                // package setting.
10380                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10381                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10382
10383                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10384
10385                if (DEBUG_ABI_SELECTION) {
10386                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10387                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10388                        pkg.applicationInfo.secondaryCpuAbi);
10389                }
10390            }
10391        } else {
10392            if ((scanFlags & SCAN_MOVE) != 0) {
10393                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10394                // but we already have this packages package info in the PackageSetting. We just
10395                // use that and derive the native library path based on the new codepath.
10396                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10397                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10398            }
10399
10400            // Set native library paths again. For moves, the path will be updated based on the
10401            // ABIs we've determined above. For non-moves, the path will be updated based on the
10402            // ABIs we determined during compilation, but the path will depend on the final
10403            // package path (after the rename away from the stage path).
10404            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10405        }
10406
10407        // This is a special case for the "system" package, where the ABI is
10408        // dictated by the zygote configuration (and init.rc). We should keep track
10409        // of this ABI so that we can deal with "normal" applications that run under
10410        // the same UID correctly.
10411        if (mPlatformPackage == pkg) {
10412            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10413                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10414        }
10415
10416        // If there's a mismatch between the abi-override in the package setting
10417        // and the abiOverride specified for the install. Warn about this because we
10418        // would've already compiled the app without taking the package setting into
10419        // account.
10420        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10421            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10422                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10423                        " for package " + pkg.packageName);
10424            }
10425        }
10426
10427        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10428        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10429        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10430
10431        // Copy the derived override back to the parsed package, so that we can
10432        // update the package settings accordingly.
10433        pkg.cpuAbiOverride = cpuAbiOverride;
10434
10435        if (DEBUG_ABI_SELECTION) {
10436            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10437                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10438                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10439        }
10440
10441        // Push the derived path down into PackageSettings so we know what to
10442        // clean up at uninstall time.
10443        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10444
10445        if (DEBUG_ABI_SELECTION) {
10446            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10447                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10448                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10449        }
10450
10451        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10452        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10453            // We don't do this here during boot because we can do it all
10454            // at once after scanning all existing packages.
10455            //
10456            // We also do this *before* we perform dexopt on this package, so that
10457            // we can avoid redundant dexopts, and also to make sure we've got the
10458            // code and package path correct.
10459            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10460        }
10461
10462        if (mFactoryTest && pkg.requestedPermissions.contains(
10463                android.Manifest.permission.FACTORY_TEST)) {
10464            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10465        }
10466
10467        if (isSystemApp(pkg)) {
10468            pkgSetting.isOrphaned = true;
10469        }
10470
10471        // Take care of first install / last update times.
10472        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10473        if (currentTime != 0) {
10474            if (pkgSetting.firstInstallTime == 0) {
10475                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10476            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10477                pkgSetting.lastUpdateTime = currentTime;
10478            }
10479        } else if (pkgSetting.firstInstallTime == 0) {
10480            // We need *something*.  Take time time stamp of the file.
10481            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10482        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10483            if (scanFileTime != pkgSetting.timeStamp) {
10484                // A package on the system image has changed; consider this
10485                // to be an update.
10486                pkgSetting.lastUpdateTime = scanFileTime;
10487            }
10488        }
10489        pkgSetting.setTimeStamp(scanFileTime);
10490
10491        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10492            if (nonMutatedPs != null) {
10493                synchronized (mPackages) {
10494                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10495                }
10496            }
10497        } else {
10498            final int userId = user == null ? 0 : user.getIdentifier();
10499            // Modify state for the given package setting
10500            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10501                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10502            if (pkgSetting.getInstantApp(userId)) {
10503                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10504            }
10505        }
10506        return pkg;
10507    }
10508
10509    /**
10510     * Applies policy to the parsed package based upon the given policy flags.
10511     * Ensures the package is in a good state.
10512     * <p>
10513     * Implementation detail: This method must NOT have any side effect. It would
10514     * ideally be static, but, it requires locks to read system state.
10515     */
10516    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10517        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10518            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10519            if (pkg.applicationInfo.isDirectBootAware()) {
10520                // we're direct boot aware; set for all components
10521                for (PackageParser.Service s : pkg.services) {
10522                    s.info.encryptionAware = s.info.directBootAware = true;
10523                }
10524                for (PackageParser.Provider p : pkg.providers) {
10525                    p.info.encryptionAware = p.info.directBootAware = true;
10526                }
10527                for (PackageParser.Activity a : pkg.activities) {
10528                    a.info.encryptionAware = a.info.directBootAware = true;
10529                }
10530                for (PackageParser.Activity r : pkg.receivers) {
10531                    r.info.encryptionAware = r.info.directBootAware = true;
10532                }
10533            }
10534            if (compressedFileExists(pkg.codePath)) {
10535                pkg.isStub = true;
10536            }
10537        } else {
10538            // Only allow system apps to be flagged as core apps.
10539            pkg.coreApp = false;
10540            // clear flags not applicable to regular apps
10541            pkg.applicationInfo.privateFlags &=
10542                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10543            pkg.applicationInfo.privateFlags &=
10544                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10545        }
10546        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10547
10548        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10549            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10550        }
10551
10552        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
10553            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10554        }
10555
10556        if (!isSystemApp(pkg)) {
10557            // Only system apps can use these features.
10558            pkg.mOriginalPackages = null;
10559            pkg.mRealPackage = null;
10560            pkg.mAdoptPermissions = null;
10561        }
10562    }
10563
10564    /**
10565     * Asserts the parsed package is valid according to the given policy. If the
10566     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10567     * <p>
10568     * Implementation detail: This method must NOT have any side effects. It would
10569     * ideally be static, but, it requires locks to read system state.
10570     *
10571     * @throws PackageManagerException If the package fails any of the validation checks
10572     */
10573    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10574            throws PackageManagerException {
10575        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10576            assertCodePolicy(pkg);
10577        }
10578
10579        if (pkg.applicationInfo.getCodePath() == null ||
10580                pkg.applicationInfo.getResourcePath() == null) {
10581            // Bail out. The resource and code paths haven't been set.
10582            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10583                    "Code and resource paths haven't been set correctly");
10584        }
10585
10586        // Make sure we're not adding any bogus keyset info
10587        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10588        ksms.assertScannedPackageValid(pkg);
10589
10590        synchronized (mPackages) {
10591            // The special "android" package can only be defined once
10592            if (pkg.packageName.equals("android")) {
10593                if (mAndroidApplication != null) {
10594                    Slog.w(TAG, "*************************************************");
10595                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10596                    Slog.w(TAG, " codePath=" + pkg.codePath);
10597                    Slog.w(TAG, "*************************************************");
10598                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10599                            "Core android package being redefined.  Skipping.");
10600                }
10601            }
10602
10603            // A package name must be unique; don't allow duplicates
10604            if (mPackages.containsKey(pkg.packageName)) {
10605                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10606                        "Application package " + pkg.packageName
10607                        + " already installed.  Skipping duplicate.");
10608            }
10609
10610            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10611                // Static libs have a synthetic package name containing the version
10612                // but we still want the base name to be unique.
10613                if (mPackages.containsKey(pkg.manifestPackageName)) {
10614                    throw new PackageManagerException(
10615                            "Duplicate static shared lib provider package");
10616                }
10617
10618                // Static shared libraries should have at least O target SDK
10619                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10620                    throw new PackageManagerException(
10621                            "Packages declaring static-shared libs must target O SDK or higher");
10622                }
10623
10624                // Package declaring static a shared lib cannot be instant apps
10625                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10626                    throw new PackageManagerException(
10627                            "Packages declaring static-shared libs cannot be instant apps");
10628                }
10629
10630                // Package declaring static a shared lib cannot be renamed since the package
10631                // name is synthetic and apps can't code around package manager internals.
10632                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10633                    throw new PackageManagerException(
10634                            "Packages declaring static-shared libs cannot be renamed");
10635                }
10636
10637                // Package declaring static a shared lib cannot declare child packages
10638                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10639                    throw new PackageManagerException(
10640                            "Packages declaring static-shared libs cannot have child packages");
10641                }
10642
10643                // Package declaring static a shared lib cannot declare dynamic libs
10644                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10645                    throw new PackageManagerException(
10646                            "Packages declaring static-shared libs cannot declare dynamic libs");
10647                }
10648
10649                // Package declaring static a shared lib cannot declare shared users
10650                if (pkg.mSharedUserId != null) {
10651                    throw new PackageManagerException(
10652                            "Packages declaring static-shared libs cannot declare shared users");
10653                }
10654
10655                // Static shared libs cannot declare activities
10656                if (!pkg.activities.isEmpty()) {
10657                    throw new PackageManagerException(
10658                            "Static shared libs cannot declare activities");
10659                }
10660
10661                // Static shared libs cannot declare services
10662                if (!pkg.services.isEmpty()) {
10663                    throw new PackageManagerException(
10664                            "Static shared libs cannot declare services");
10665                }
10666
10667                // Static shared libs cannot declare providers
10668                if (!pkg.providers.isEmpty()) {
10669                    throw new PackageManagerException(
10670                            "Static shared libs cannot declare content providers");
10671                }
10672
10673                // Static shared libs cannot declare receivers
10674                if (!pkg.receivers.isEmpty()) {
10675                    throw new PackageManagerException(
10676                            "Static shared libs cannot declare broadcast receivers");
10677                }
10678
10679                // Static shared libs cannot declare permission groups
10680                if (!pkg.permissionGroups.isEmpty()) {
10681                    throw new PackageManagerException(
10682                            "Static shared libs cannot declare permission groups");
10683                }
10684
10685                // Static shared libs cannot declare permissions
10686                if (!pkg.permissions.isEmpty()) {
10687                    throw new PackageManagerException(
10688                            "Static shared libs cannot declare permissions");
10689                }
10690
10691                // Static shared libs cannot declare protected broadcasts
10692                if (pkg.protectedBroadcasts != null) {
10693                    throw new PackageManagerException(
10694                            "Static shared libs cannot declare protected broadcasts");
10695                }
10696
10697                // Static shared libs cannot be overlay targets
10698                if (pkg.mOverlayTarget != null) {
10699                    throw new PackageManagerException(
10700                            "Static shared libs cannot be overlay targets");
10701                }
10702
10703                // The version codes must be ordered as lib versions
10704                int minVersionCode = Integer.MIN_VALUE;
10705                int maxVersionCode = Integer.MAX_VALUE;
10706
10707                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10708                        pkg.staticSharedLibName);
10709                if (versionedLib != null) {
10710                    final int versionCount = versionedLib.size();
10711                    for (int i = 0; i < versionCount; i++) {
10712                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10713                        final int libVersionCode = libInfo.getDeclaringPackage()
10714                                .getVersionCode();
10715                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10716                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10717                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10718                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10719                        } else {
10720                            minVersionCode = maxVersionCode = libVersionCode;
10721                            break;
10722                        }
10723                    }
10724                }
10725                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10726                    throw new PackageManagerException("Static shared"
10727                            + " lib version codes must be ordered as lib versions");
10728                }
10729            }
10730
10731            // Only privileged apps and updated privileged apps can add child packages.
10732            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10733                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10734                    throw new PackageManagerException("Only privileged apps can add child "
10735                            + "packages. Ignoring package " + pkg.packageName);
10736                }
10737                final int childCount = pkg.childPackages.size();
10738                for (int i = 0; i < childCount; i++) {
10739                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10740                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10741                            childPkg.packageName)) {
10742                        throw new PackageManagerException("Can't override child of "
10743                                + "another disabled app. Ignoring package " + pkg.packageName);
10744                    }
10745                }
10746            }
10747
10748            // If we're only installing presumed-existing packages, require that the
10749            // scanned APK is both already known and at the path previously established
10750            // for it.  Previously unknown packages we pick up normally, but if we have an
10751            // a priori expectation about this package's install presence, enforce it.
10752            // With a singular exception for new system packages. When an OTA contains
10753            // a new system package, we allow the codepath to change from a system location
10754            // to the user-installed location. If we don't allow this change, any newer,
10755            // user-installed version of the application will be ignored.
10756            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10757                if (mExpectingBetter.containsKey(pkg.packageName)) {
10758                    logCriticalInfo(Log.WARN,
10759                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10760                } else {
10761                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10762                    if (known != null) {
10763                        if (DEBUG_PACKAGE_SCANNING) {
10764                            Log.d(TAG, "Examining " + pkg.codePath
10765                                    + " and requiring known paths " + known.codePathString
10766                                    + " & " + known.resourcePathString);
10767                        }
10768                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10769                                || !pkg.applicationInfo.getResourcePath().equals(
10770                                        known.resourcePathString)) {
10771                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10772                                    "Application package " + pkg.packageName
10773                                    + " found at " + pkg.applicationInfo.getCodePath()
10774                                    + " but expected at " + known.codePathString
10775                                    + "; ignoring.");
10776                        }
10777                    } else {
10778                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10779                                "Application package " + pkg.packageName
10780                                + " not found; ignoring.");
10781                    }
10782                }
10783            }
10784
10785            // Verify that this new package doesn't have any content providers
10786            // that conflict with existing packages.  Only do this if the
10787            // package isn't already installed, since we don't want to break
10788            // things that are installed.
10789            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10790                final int N = pkg.providers.size();
10791                int i;
10792                for (i=0; i<N; i++) {
10793                    PackageParser.Provider p = pkg.providers.get(i);
10794                    if (p.info.authority != null) {
10795                        String names[] = p.info.authority.split(";");
10796                        for (int j = 0; j < names.length; j++) {
10797                            if (mProvidersByAuthority.containsKey(names[j])) {
10798                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10799                                final String otherPackageName =
10800                                        ((other != null && other.getComponentName() != null) ?
10801                                                other.getComponentName().getPackageName() : "?");
10802                                throw new PackageManagerException(
10803                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10804                                        "Can't install because provider name " + names[j]
10805                                                + " (in package " + pkg.applicationInfo.packageName
10806                                                + ") is already used by " + otherPackageName);
10807                            }
10808                        }
10809                    }
10810                }
10811            }
10812        }
10813    }
10814
10815    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10816            int type, String declaringPackageName, int declaringVersionCode) {
10817        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10818        if (versionedLib == null) {
10819            versionedLib = new SparseArray<>();
10820            mSharedLibraries.put(name, versionedLib);
10821            if (type == SharedLibraryInfo.TYPE_STATIC) {
10822                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10823            }
10824        } else if (versionedLib.indexOfKey(version) >= 0) {
10825            return false;
10826        }
10827        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10828                version, type, declaringPackageName, declaringVersionCode);
10829        versionedLib.put(version, libEntry);
10830        return true;
10831    }
10832
10833    private boolean removeSharedLibraryLPw(String name, int version) {
10834        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10835        if (versionedLib == null) {
10836            return false;
10837        }
10838        final int libIdx = versionedLib.indexOfKey(version);
10839        if (libIdx < 0) {
10840            return false;
10841        }
10842        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10843        versionedLib.remove(version);
10844        if (versionedLib.size() <= 0) {
10845            mSharedLibraries.remove(name);
10846            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10847                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10848                        .getPackageName());
10849            }
10850        }
10851        return true;
10852    }
10853
10854    /**
10855     * Adds a scanned package to the system. When this method is finished, the package will
10856     * be available for query, resolution, etc...
10857     */
10858    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10859            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10860        final String pkgName = pkg.packageName;
10861        if (mCustomResolverComponentName != null &&
10862                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10863            setUpCustomResolverActivity(pkg);
10864        }
10865
10866        if (pkg.packageName.equals("android")) {
10867            synchronized (mPackages) {
10868                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10869                    // Set up information for our fall-back user intent resolution activity.
10870                    mPlatformPackage = pkg;
10871                    pkg.mVersionCode = mSdkVersion;
10872                    mAndroidApplication = pkg.applicationInfo;
10873                    if (!mResolverReplaced) {
10874                        mResolveActivity.applicationInfo = mAndroidApplication;
10875                        mResolveActivity.name = ResolverActivity.class.getName();
10876                        mResolveActivity.packageName = mAndroidApplication.packageName;
10877                        mResolveActivity.processName = "system:ui";
10878                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10879                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10880                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10881                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10882                        mResolveActivity.exported = true;
10883                        mResolveActivity.enabled = true;
10884                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10885                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10886                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10887                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10888                                | ActivityInfo.CONFIG_ORIENTATION
10889                                | ActivityInfo.CONFIG_KEYBOARD
10890                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10891                        mResolveInfo.activityInfo = mResolveActivity;
10892                        mResolveInfo.priority = 0;
10893                        mResolveInfo.preferredOrder = 0;
10894                        mResolveInfo.match = 0;
10895                        mResolveComponentName = new ComponentName(
10896                                mAndroidApplication.packageName, mResolveActivity.name);
10897                    }
10898                }
10899            }
10900        }
10901
10902        ArrayList<PackageParser.Package> clientLibPkgs = null;
10903        // writer
10904        synchronized (mPackages) {
10905            boolean hasStaticSharedLibs = false;
10906
10907            // Any app can add new static shared libraries
10908            if (pkg.staticSharedLibName != null) {
10909                // Static shared libs don't allow renaming as they have synthetic package
10910                // names to allow install of multiple versions, so use name from manifest.
10911                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10912                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10913                        pkg.manifestPackageName, pkg.mVersionCode)) {
10914                    hasStaticSharedLibs = true;
10915                } else {
10916                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10917                                + pkg.staticSharedLibName + " already exists; skipping");
10918                }
10919                // Static shared libs cannot be updated once installed since they
10920                // use synthetic package name which includes the version code, so
10921                // not need to update other packages's shared lib dependencies.
10922            }
10923
10924            if (!hasStaticSharedLibs
10925                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10926                // Only system apps can add new dynamic shared libraries.
10927                if (pkg.libraryNames != null) {
10928                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10929                        String name = pkg.libraryNames.get(i);
10930                        boolean allowed = false;
10931                        if (pkg.isUpdatedSystemApp()) {
10932                            // New library entries can only be added through the
10933                            // system image.  This is important to get rid of a lot
10934                            // of nasty edge cases: for example if we allowed a non-
10935                            // system update of the app to add a library, then uninstalling
10936                            // the update would make the library go away, and assumptions
10937                            // we made such as through app install filtering would now
10938                            // have allowed apps on the device which aren't compatible
10939                            // with it.  Better to just have the restriction here, be
10940                            // conservative, and create many fewer cases that can negatively
10941                            // impact the user experience.
10942                            final PackageSetting sysPs = mSettings
10943                                    .getDisabledSystemPkgLPr(pkg.packageName);
10944                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10945                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10946                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10947                                        allowed = true;
10948                                        break;
10949                                    }
10950                                }
10951                            }
10952                        } else {
10953                            allowed = true;
10954                        }
10955                        if (allowed) {
10956                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10957                                    SharedLibraryInfo.VERSION_UNDEFINED,
10958                                    SharedLibraryInfo.TYPE_DYNAMIC,
10959                                    pkg.packageName, pkg.mVersionCode)) {
10960                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10961                                        + name + " already exists; skipping");
10962                            }
10963                        } else {
10964                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10965                                    + name + " that is not declared on system image; skipping");
10966                        }
10967                    }
10968
10969                    if ((scanFlags & SCAN_BOOTING) == 0) {
10970                        // If we are not booting, we need to update any applications
10971                        // that are clients of our shared library.  If we are booting,
10972                        // this will all be done once the scan is complete.
10973                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10974                    }
10975                }
10976            }
10977        }
10978
10979        if ((scanFlags & SCAN_BOOTING) != 0) {
10980            // No apps can run during boot scan, so they don't need to be frozen
10981        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10982            // Caller asked to not kill app, so it's probably not frozen
10983        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10984            // Caller asked us to ignore frozen check for some reason; they
10985            // probably didn't know the package name
10986        } else {
10987            // We're doing major surgery on this package, so it better be frozen
10988            // right now to keep it from launching
10989            checkPackageFrozen(pkgName);
10990        }
10991
10992        // Also need to kill any apps that are dependent on the library.
10993        if (clientLibPkgs != null) {
10994            for (int i=0; i<clientLibPkgs.size(); i++) {
10995                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10996                killApplication(clientPkg.applicationInfo.packageName,
10997                        clientPkg.applicationInfo.uid, "update lib");
10998            }
10999        }
11000
11001        // writer
11002        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11003
11004        synchronized (mPackages) {
11005            // We don't expect installation to fail beyond this point
11006
11007            // Add the new setting to mSettings
11008            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11009            // Add the new setting to mPackages
11010            mPackages.put(pkg.applicationInfo.packageName, pkg);
11011            // Make sure we don't accidentally delete its data.
11012            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11013            while (iter.hasNext()) {
11014                PackageCleanItem item = iter.next();
11015                if (pkgName.equals(item.packageName)) {
11016                    iter.remove();
11017                }
11018            }
11019
11020            // Add the package's KeySets to the global KeySetManagerService
11021            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11022            ksms.addScannedPackageLPw(pkg);
11023
11024            int N = pkg.providers.size();
11025            StringBuilder r = null;
11026            int i;
11027            for (i=0; i<N; i++) {
11028                PackageParser.Provider p = pkg.providers.get(i);
11029                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11030                        p.info.processName);
11031                mProviders.addProvider(p);
11032                p.syncable = p.info.isSyncable;
11033                if (p.info.authority != null) {
11034                    String names[] = p.info.authority.split(";");
11035                    p.info.authority = null;
11036                    for (int j = 0; j < names.length; j++) {
11037                        if (j == 1 && p.syncable) {
11038                            // We only want the first authority for a provider to possibly be
11039                            // syncable, so if we already added this provider using a different
11040                            // authority clear the syncable flag. We copy the provider before
11041                            // changing it because the mProviders object contains a reference
11042                            // to a provider that we don't want to change.
11043                            // Only do this for the second authority since the resulting provider
11044                            // object can be the same for all future authorities for this provider.
11045                            p = new PackageParser.Provider(p);
11046                            p.syncable = false;
11047                        }
11048                        if (!mProvidersByAuthority.containsKey(names[j])) {
11049                            mProvidersByAuthority.put(names[j], p);
11050                            if (p.info.authority == null) {
11051                                p.info.authority = names[j];
11052                            } else {
11053                                p.info.authority = p.info.authority + ";" + names[j];
11054                            }
11055                            if (DEBUG_PACKAGE_SCANNING) {
11056                                if (chatty)
11057                                    Log.d(TAG, "Registered content provider: " + names[j]
11058                                            + ", className = " + p.info.name + ", isSyncable = "
11059                                            + p.info.isSyncable);
11060                            }
11061                        } else {
11062                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11063                            Slog.w(TAG, "Skipping provider name " + names[j] +
11064                                    " (in package " + pkg.applicationInfo.packageName +
11065                                    "): name already used by "
11066                                    + ((other != null && other.getComponentName() != null)
11067                                            ? other.getComponentName().getPackageName() : "?"));
11068                        }
11069                    }
11070                }
11071                if (chatty) {
11072                    if (r == null) {
11073                        r = new StringBuilder(256);
11074                    } else {
11075                        r.append(' ');
11076                    }
11077                    r.append(p.info.name);
11078                }
11079            }
11080            if (r != null) {
11081                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11082            }
11083
11084            N = pkg.services.size();
11085            r = null;
11086            for (i=0; i<N; i++) {
11087                PackageParser.Service s = pkg.services.get(i);
11088                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11089                        s.info.processName);
11090                mServices.addService(s);
11091                if (chatty) {
11092                    if (r == null) {
11093                        r = new StringBuilder(256);
11094                    } else {
11095                        r.append(' ');
11096                    }
11097                    r.append(s.info.name);
11098                }
11099            }
11100            if (r != null) {
11101                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11102            }
11103
11104            N = pkg.receivers.size();
11105            r = null;
11106            for (i=0; i<N; i++) {
11107                PackageParser.Activity a = pkg.receivers.get(i);
11108                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11109                        a.info.processName);
11110                mReceivers.addActivity(a, "receiver");
11111                if (chatty) {
11112                    if (r == null) {
11113                        r = new StringBuilder(256);
11114                    } else {
11115                        r.append(' ');
11116                    }
11117                    r.append(a.info.name);
11118                }
11119            }
11120            if (r != null) {
11121                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11122            }
11123
11124            N = pkg.activities.size();
11125            r = null;
11126            for (i=0; i<N; i++) {
11127                PackageParser.Activity a = pkg.activities.get(i);
11128                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11129                        a.info.processName);
11130                mActivities.addActivity(a, "activity");
11131                if (chatty) {
11132                    if (r == null) {
11133                        r = new StringBuilder(256);
11134                    } else {
11135                        r.append(' ');
11136                    }
11137                    r.append(a.info.name);
11138                }
11139            }
11140            if (r != null) {
11141                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11142            }
11143
11144            N = pkg.permissionGroups.size();
11145            r = null;
11146            for (i=0; i<N; i++) {
11147                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11148                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11149                final String curPackageName = cur == null ? null : cur.info.packageName;
11150                // Dont allow ephemeral apps to define new permission groups.
11151                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11152                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11153                            + pg.info.packageName
11154                            + " ignored: instant apps cannot define new permission groups.");
11155                    continue;
11156                }
11157                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11158                if (cur == null || isPackageUpdate) {
11159                    mPermissionGroups.put(pg.info.name, pg);
11160                    if (chatty) {
11161                        if (r == null) {
11162                            r = new StringBuilder(256);
11163                        } else {
11164                            r.append(' ');
11165                        }
11166                        if (isPackageUpdate) {
11167                            r.append("UPD:");
11168                        }
11169                        r.append(pg.info.name);
11170                    }
11171                } else {
11172                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11173                            + pg.info.packageName + " ignored: original from "
11174                            + cur.info.packageName);
11175                    if (chatty) {
11176                        if (r == null) {
11177                            r = new StringBuilder(256);
11178                        } else {
11179                            r.append(' ');
11180                        }
11181                        r.append("DUP:");
11182                        r.append(pg.info.name);
11183                    }
11184                }
11185            }
11186            if (r != null) {
11187                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11188            }
11189
11190
11191            // Dont allow ephemeral apps to define new permissions.
11192            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11193                Slog.w(TAG, "Permissions from package " + pkg.packageName
11194                        + " ignored: instant apps cannot define new permissions.");
11195            } else {
11196                mPermissionManager.addAllPermissions(pkg, chatty);
11197            }
11198
11199            N = pkg.instrumentation.size();
11200            r = null;
11201            for (i=0; i<N; i++) {
11202                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11203                a.info.packageName = pkg.applicationInfo.packageName;
11204                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11205                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11206                a.info.splitNames = pkg.splitNames;
11207                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11208                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11209                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11210                a.info.dataDir = pkg.applicationInfo.dataDir;
11211                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11212                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11213                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11214                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11215                mInstrumentation.put(a.getComponentName(), a);
11216                if (chatty) {
11217                    if (r == null) {
11218                        r = new StringBuilder(256);
11219                    } else {
11220                        r.append(' ');
11221                    }
11222                    r.append(a.info.name);
11223                }
11224            }
11225            if (r != null) {
11226                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11227            }
11228
11229            if (pkg.protectedBroadcasts != null) {
11230                N = pkg.protectedBroadcasts.size();
11231                synchronized (mProtectedBroadcasts) {
11232                    for (i = 0; i < N; i++) {
11233                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11234                    }
11235                }
11236            }
11237        }
11238
11239        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11240    }
11241
11242    /**
11243     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11244     * is derived purely on the basis of the contents of {@code scanFile} and
11245     * {@code cpuAbiOverride}.
11246     *
11247     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11248     */
11249    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11250                                 String cpuAbiOverride, boolean extractLibs,
11251                                 File appLib32InstallDir)
11252            throws PackageManagerException {
11253        // Give ourselves some initial paths; we'll come back for another
11254        // pass once we've determined ABI below.
11255        setNativeLibraryPaths(pkg, appLib32InstallDir);
11256
11257        // We would never need to extract libs for forward-locked and external packages,
11258        // since the container service will do it for us. We shouldn't attempt to
11259        // extract libs from system app when it was not updated.
11260        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11261                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11262            extractLibs = false;
11263        }
11264
11265        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11266        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11267
11268        NativeLibraryHelper.Handle handle = null;
11269        try {
11270            handle = NativeLibraryHelper.Handle.create(pkg);
11271            // TODO(multiArch): This can be null for apps that didn't go through the
11272            // usual installation process. We can calculate it again, like we
11273            // do during install time.
11274            //
11275            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11276            // unnecessary.
11277            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11278
11279            // Null out the abis so that they can be recalculated.
11280            pkg.applicationInfo.primaryCpuAbi = null;
11281            pkg.applicationInfo.secondaryCpuAbi = null;
11282            if (isMultiArch(pkg.applicationInfo)) {
11283                // Warn if we've set an abiOverride for multi-lib packages..
11284                // By definition, we need to copy both 32 and 64 bit libraries for
11285                // such packages.
11286                if (pkg.cpuAbiOverride != null
11287                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11288                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11289                }
11290
11291                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11292                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11293                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11294                    if (extractLibs) {
11295                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11296                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11297                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11298                                useIsaSpecificSubdirs);
11299                    } else {
11300                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11301                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11302                    }
11303                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11304                }
11305
11306                // Shared library native code should be in the APK zip aligned
11307                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11308                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11309                            "Shared library native lib extraction not supported");
11310                }
11311
11312                maybeThrowExceptionForMultiArchCopy(
11313                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11314
11315                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11316                    if (extractLibs) {
11317                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11318                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11319                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11320                                useIsaSpecificSubdirs);
11321                    } else {
11322                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11323                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11324                    }
11325                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11326                }
11327
11328                maybeThrowExceptionForMultiArchCopy(
11329                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11330
11331                if (abi64 >= 0) {
11332                    // Shared library native libs should be in the APK zip aligned
11333                    if (extractLibs && pkg.isLibrary()) {
11334                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11335                                "Shared library native lib extraction not supported");
11336                    }
11337                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11338                }
11339
11340                if (abi32 >= 0) {
11341                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11342                    if (abi64 >= 0) {
11343                        if (pkg.use32bitAbi) {
11344                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11345                            pkg.applicationInfo.primaryCpuAbi = abi;
11346                        } else {
11347                            pkg.applicationInfo.secondaryCpuAbi = abi;
11348                        }
11349                    } else {
11350                        pkg.applicationInfo.primaryCpuAbi = abi;
11351                    }
11352                }
11353            } else {
11354                String[] abiList = (cpuAbiOverride != null) ?
11355                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11356
11357                // Enable gross and lame hacks for apps that are built with old
11358                // SDK tools. We must scan their APKs for renderscript bitcode and
11359                // not launch them if it's present. Don't bother checking on devices
11360                // that don't have 64 bit support.
11361                boolean needsRenderScriptOverride = false;
11362                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11363                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11364                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11365                    needsRenderScriptOverride = true;
11366                }
11367
11368                final int copyRet;
11369                if (extractLibs) {
11370                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11371                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11372                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11373                } else {
11374                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11375                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11376                }
11377                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11378
11379                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11380                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11381                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11382                }
11383
11384                if (copyRet >= 0) {
11385                    // Shared libraries that have native libs must be multi-architecture
11386                    if (pkg.isLibrary()) {
11387                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11388                                "Shared library with native libs must be multiarch");
11389                    }
11390                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11391                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11392                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11393                } else if (needsRenderScriptOverride) {
11394                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11395                }
11396            }
11397        } catch (IOException ioe) {
11398            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11399        } finally {
11400            IoUtils.closeQuietly(handle);
11401        }
11402
11403        // Now that we've calculated the ABIs and determined if it's an internal app,
11404        // we will go ahead and populate the nativeLibraryPath.
11405        setNativeLibraryPaths(pkg, appLib32InstallDir);
11406    }
11407
11408    /**
11409     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11410     * i.e, so that all packages can be run inside a single process if required.
11411     *
11412     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11413     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11414     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11415     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11416     * updating a package that belongs to a shared user.
11417     *
11418     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11419     * adds unnecessary complexity.
11420     */
11421    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11422            PackageParser.Package scannedPackage) {
11423        String requiredInstructionSet = null;
11424        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11425            requiredInstructionSet = VMRuntime.getInstructionSet(
11426                     scannedPackage.applicationInfo.primaryCpuAbi);
11427        }
11428
11429        PackageSetting requirer = null;
11430        for (PackageSetting ps : packagesForUser) {
11431            // If packagesForUser contains scannedPackage, we skip it. This will happen
11432            // when scannedPackage is an update of an existing package. Without this check,
11433            // we will never be able to change the ABI of any package belonging to a shared
11434            // user, even if it's compatible with other packages.
11435            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11436                if (ps.primaryCpuAbiString == null) {
11437                    continue;
11438                }
11439
11440                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11441                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11442                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11443                    // this but there's not much we can do.
11444                    String errorMessage = "Instruction set mismatch, "
11445                            + ((requirer == null) ? "[caller]" : requirer)
11446                            + " requires " + requiredInstructionSet + " whereas " + ps
11447                            + " requires " + instructionSet;
11448                    Slog.w(TAG, errorMessage);
11449                }
11450
11451                if (requiredInstructionSet == null) {
11452                    requiredInstructionSet = instructionSet;
11453                    requirer = ps;
11454                }
11455            }
11456        }
11457
11458        if (requiredInstructionSet != null) {
11459            String adjustedAbi;
11460            if (requirer != null) {
11461                // requirer != null implies that either scannedPackage was null or that scannedPackage
11462                // did not require an ABI, in which case we have to adjust scannedPackage to match
11463                // the ABI of the set (which is the same as requirer's ABI)
11464                adjustedAbi = requirer.primaryCpuAbiString;
11465                if (scannedPackage != null) {
11466                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11467                }
11468            } else {
11469                // requirer == null implies that we're updating all ABIs in the set to
11470                // match scannedPackage.
11471                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11472            }
11473
11474            for (PackageSetting ps : packagesForUser) {
11475                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11476                    if (ps.primaryCpuAbiString != null) {
11477                        continue;
11478                    }
11479
11480                    ps.primaryCpuAbiString = adjustedAbi;
11481                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11482                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11483                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11484                        if (DEBUG_ABI_SELECTION) {
11485                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11486                                    + " (requirer="
11487                                    + (requirer != null ? requirer.pkg : "null")
11488                                    + ", scannedPackage="
11489                                    + (scannedPackage != null ? scannedPackage : "null")
11490                                    + ")");
11491                        }
11492                        try {
11493                            mInstaller.rmdex(ps.codePathString,
11494                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11495                        } catch (InstallerException ignored) {
11496                        }
11497                    }
11498                }
11499            }
11500        }
11501    }
11502
11503    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11504        synchronized (mPackages) {
11505            mResolverReplaced = true;
11506            // Set up information for custom user intent resolution activity.
11507            mResolveActivity.applicationInfo = pkg.applicationInfo;
11508            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11509            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11510            mResolveActivity.processName = pkg.applicationInfo.packageName;
11511            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11512            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11513                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11514            mResolveActivity.theme = 0;
11515            mResolveActivity.exported = true;
11516            mResolveActivity.enabled = true;
11517            mResolveInfo.activityInfo = mResolveActivity;
11518            mResolveInfo.priority = 0;
11519            mResolveInfo.preferredOrder = 0;
11520            mResolveInfo.match = 0;
11521            mResolveComponentName = mCustomResolverComponentName;
11522            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11523                    mResolveComponentName);
11524        }
11525    }
11526
11527    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11528        if (installerActivity == null) {
11529            if (DEBUG_EPHEMERAL) {
11530                Slog.d(TAG, "Clear ephemeral installer activity");
11531            }
11532            mInstantAppInstallerActivity = null;
11533            return;
11534        }
11535
11536        if (DEBUG_EPHEMERAL) {
11537            Slog.d(TAG, "Set ephemeral installer activity: "
11538                    + installerActivity.getComponentName());
11539        }
11540        // Set up information for ephemeral installer activity
11541        mInstantAppInstallerActivity = installerActivity;
11542        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11543                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11544        mInstantAppInstallerActivity.exported = true;
11545        mInstantAppInstallerActivity.enabled = true;
11546        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11547        mInstantAppInstallerInfo.priority = 0;
11548        mInstantAppInstallerInfo.preferredOrder = 1;
11549        mInstantAppInstallerInfo.isDefault = true;
11550        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11551                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11552    }
11553
11554    private static String calculateBundledApkRoot(final String codePathString) {
11555        final File codePath = new File(codePathString);
11556        final File codeRoot;
11557        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11558            codeRoot = Environment.getRootDirectory();
11559        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11560            codeRoot = Environment.getOemDirectory();
11561        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11562            codeRoot = Environment.getVendorDirectory();
11563        } else {
11564            // Unrecognized code path; take its top real segment as the apk root:
11565            // e.g. /something/app/blah.apk => /something
11566            try {
11567                File f = codePath.getCanonicalFile();
11568                File parent = f.getParentFile();    // non-null because codePath is a file
11569                File tmp;
11570                while ((tmp = parent.getParentFile()) != null) {
11571                    f = parent;
11572                    parent = tmp;
11573                }
11574                codeRoot = f;
11575                Slog.w(TAG, "Unrecognized code path "
11576                        + codePath + " - using " + codeRoot);
11577            } catch (IOException e) {
11578                // Can't canonicalize the code path -- shenanigans?
11579                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11580                return Environment.getRootDirectory().getPath();
11581            }
11582        }
11583        return codeRoot.getPath();
11584    }
11585
11586    /**
11587     * Derive and set the location of native libraries for the given package,
11588     * which varies depending on where and how the package was installed.
11589     */
11590    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11591        final ApplicationInfo info = pkg.applicationInfo;
11592        final String codePath = pkg.codePath;
11593        final File codeFile = new File(codePath);
11594        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11595        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11596
11597        info.nativeLibraryRootDir = null;
11598        info.nativeLibraryRootRequiresIsa = false;
11599        info.nativeLibraryDir = null;
11600        info.secondaryNativeLibraryDir = null;
11601
11602        if (isApkFile(codeFile)) {
11603            // Monolithic install
11604            if (bundledApp) {
11605                // If "/system/lib64/apkname" exists, assume that is the per-package
11606                // native library directory to use; otherwise use "/system/lib/apkname".
11607                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11608                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11609                        getPrimaryInstructionSet(info));
11610
11611                // This is a bundled system app so choose the path based on the ABI.
11612                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11613                // is just the default path.
11614                final String apkName = deriveCodePathName(codePath);
11615                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11616                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11617                        apkName).getAbsolutePath();
11618
11619                if (info.secondaryCpuAbi != null) {
11620                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11621                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11622                            secondaryLibDir, apkName).getAbsolutePath();
11623                }
11624            } else if (asecApp) {
11625                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11626                        .getAbsolutePath();
11627            } else {
11628                final String apkName = deriveCodePathName(codePath);
11629                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11630                        .getAbsolutePath();
11631            }
11632
11633            info.nativeLibraryRootRequiresIsa = false;
11634            info.nativeLibraryDir = info.nativeLibraryRootDir;
11635        } else {
11636            // Cluster install
11637            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11638            info.nativeLibraryRootRequiresIsa = true;
11639
11640            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11641                    getPrimaryInstructionSet(info)).getAbsolutePath();
11642
11643            if (info.secondaryCpuAbi != null) {
11644                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11645                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11646            }
11647        }
11648    }
11649
11650    /**
11651     * Calculate the abis and roots for a bundled app. These can uniquely
11652     * be determined from the contents of the system partition, i.e whether
11653     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11654     * of this information, and instead assume that the system was built
11655     * sensibly.
11656     */
11657    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11658                                           PackageSetting pkgSetting) {
11659        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11660
11661        // If "/system/lib64/apkname" exists, assume that is the per-package
11662        // native library directory to use; otherwise use "/system/lib/apkname".
11663        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11664        setBundledAppAbi(pkg, apkRoot, apkName);
11665        // pkgSetting might be null during rescan following uninstall of updates
11666        // to a bundled app, so accommodate that possibility.  The settings in
11667        // that case will be established later from the parsed package.
11668        //
11669        // If the settings aren't null, sync them up with what we've just derived.
11670        // note that apkRoot isn't stored in the package settings.
11671        if (pkgSetting != null) {
11672            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11673            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11674        }
11675    }
11676
11677    /**
11678     * Deduces the ABI of a bundled app and sets the relevant fields on the
11679     * parsed pkg object.
11680     *
11681     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11682     *        under which system libraries are installed.
11683     * @param apkName the name of the installed package.
11684     */
11685    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11686        final File codeFile = new File(pkg.codePath);
11687
11688        final boolean has64BitLibs;
11689        final boolean has32BitLibs;
11690        if (isApkFile(codeFile)) {
11691            // Monolithic install
11692            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11693            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11694        } else {
11695            // Cluster install
11696            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11697            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11698                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11699                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11700                has64BitLibs = (new File(rootDir, isa)).exists();
11701            } else {
11702                has64BitLibs = false;
11703            }
11704            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11705                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11706                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11707                has32BitLibs = (new File(rootDir, isa)).exists();
11708            } else {
11709                has32BitLibs = false;
11710            }
11711        }
11712
11713        if (has64BitLibs && !has32BitLibs) {
11714            // The package has 64 bit libs, but not 32 bit libs. Its primary
11715            // ABI should be 64 bit. We can safely assume here that the bundled
11716            // native libraries correspond to the most preferred ABI in the list.
11717
11718            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11719            pkg.applicationInfo.secondaryCpuAbi = null;
11720        } else if (has32BitLibs && !has64BitLibs) {
11721            // The package has 32 bit libs but not 64 bit libs. Its primary
11722            // ABI should be 32 bit.
11723
11724            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11725            pkg.applicationInfo.secondaryCpuAbi = null;
11726        } else if (has32BitLibs && has64BitLibs) {
11727            // The application has both 64 and 32 bit bundled libraries. We check
11728            // here that the app declares multiArch support, and warn if it doesn't.
11729            //
11730            // We will be lenient here and record both ABIs. The primary will be the
11731            // ABI that's higher on the list, i.e, a device that's configured to prefer
11732            // 64 bit apps will see a 64 bit primary ABI,
11733
11734            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11735                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11736            }
11737
11738            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11739                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11740                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11741            } else {
11742                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11743                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11744            }
11745        } else {
11746            pkg.applicationInfo.primaryCpuAbi = null;
11747            pkg.applicationInfo.secondaryCpuAbi = null;
11748        }
11749    }
11750
11751    private void killApplication(String pkgName, int appId, String reason) {
11752        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11753    }
11754
11755    private void killApplication(String pkgName, int appId, int userId, String reason) {
11756        // Request the ActivityManager to kill the process(only for existing packages)
11757        // so that we do not end up in a confused state while the user is still using the older
11758        // version of the application while the new one gets installed.
11759        final long token = Binder.clearCallingIdentity();
11760        try {
11761            IActivityManager am = ActivityManager.getService();
11762            if (am != null) {
11763                try {
11764                    am.killApplication(pkgName, appId, userId, reason);
11765                } catch (RemoteException e) {
11766                }
11767            }
11768        } finally {
11769            Binder.restoreCallingIdentity(token);
11770        }
11771    }
11772
11773    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11774        // Remove the parent package setting
11775        PackageSetting ps = (PackageSetting) pkg.mExtras;
11776        if (ps != null) {
11777            removePackageLI(ps, chatty);
11778        }
11779        // Remove the child package setting
11780        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11781        for (int i = 0; i < childCount; i++) {
11782            PackageParser.Package childPkg = pkg.childPackages.get(i);
11783            ps = (PackageSetting) childPkg.mExtras;
11784            if (ps != null) {
11785                removePackageLI(ps, chatty);
11786            }
11787        }
11788    }
11789
11790    void removePackageLI(PackageSetting ps, boolean chatty) {
11791        if (DEBUG_INSTALL) {
11792            if (chatty)
11793                Log.d(TAG, "Removing package " + ps.name);
11794        }
11795
11796        // writer
11797        synchronized (mPackages) {
11798            mPackages.remove(ps.name);
11799            final PackageParser.Package pkg = ps.pkg;
11800            if (pkg != null) {
11801                cleanPackageDataStructuresLILPw(pkg, chatty);
11802            }
11803        }
11804    }
11805
11806    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11807        if (DEBUG_INSTALL) {
11808            if (chatty)
11809                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11810        }
11811
11812        // writer
11813        synchronized (mPackages) {
11814            // Remove the parent package
11815            mPackages.remove(pkg.applicationInfo.packageName);
11816            cleanPackageDataStructuresLILPw(pkg, chatty);
11817
11818            // Remove the child packages
11819            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11820            for (int i = 0; i < childCount; i++) {
11821                PackageParser.Package childPkg = pkg.childPackages.get(i);
11822                mPackages.remove(childPkg.applicationInfo.packageName);
11823                cleanPackageDataStructuresLILPw(childPkg, chatty);
11824            }
11825        }
11826    }
11827
11828    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11829        int N = pkg.providers.size();
11830        StringBuilder r = null;
11831        int i;
11832        for (i=0; i<N; i++) {
11833            PackageParser.Provider p = pkg.providers.get(i);
11834            mProviders.removeProvider(p);
11835            if (p.info.authority == null) {
11836
11837                /* There was another ContentProvider with this authority when
11838                 * this app was installed so this authority is null,
11839                 * Ignore it as we don't have to unregister the provider.
11840                 */
11841                continue;
11842            }
11843            String names[] = p.info.authority.split(";");
11844            for (int j = 0; j < names.length; j++) {
11845                if (mProvidersByAuthority.get(names[j]) == p) {
11846                    mProvidersByAuthority.remove(names[j]);
11847                    if (DEBUG_REMOVE) {
11848                        if (chatty)
11849                            Log.d(TAG, "Unregistered content provider: " + names[j]
11850                                    + ", className = " + p.info.name + ", isSyncable = "
11851                                    + p.info.isSyncable);
11852                    }
11853                }
11854            }
11855            if (DEBUG_REMOVE && chatty) {
11856                if (r == null) {
11857                    r = new StringBuilder(256);
11858                } else {
11859                    r.append(' ');
11860                }
11861                r.append(p.info.name);
11862            }
11863        }
11864        if (r != null) {
11865            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11866        }
11867
11868        N = pkg.services.size();
11869        r = null;
11870        for (i=0; i<N; i++) {
11871            PackageParser.Service s = pkg.services.get(i);
11872            mServices.removeService(s);
11873            if (chatty) {
11874                if (r == null) {
11875                    r = new StringBuilder(256);
11876                } else {
11877                    r.append(' ');
11878                }
11879                r.append(s.info.name);
11880            }
11881        }
11882        if (r != null) {
11883            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11884        }
11885
11886        N = pkg.receivers.size();
11887        r = null;
11888        for (i=0; i<N; i++) {
11889            PackageParser.Activity a = pkg.receivers.get(i);
11890            mReceivers.removeActivity(a, "receiver");
11891            if (DEBUG_REMOVE && chatty) {
11892                if (r == null) {
11893                    r = new StringBuilder(256);
11894                } else {
11895                    r.append(' ');
11896                }
11897                r.append(a.info.name);
11898            }
11899        }
11900        if (r != null) {
11901            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11902        }
11903
11904        N = pkg.activities.size();
11905        r = null;
11906        for (i=0; i<N; i++) {
11907            PackageParser.Activity a = pkg.activities.get(i);
11908            mActivities.removeActivity(a, "activity");
11909            if (DEBUG_REMOVE && chatty) {
11910                if (r == null) {
11911                    r = new StringBuilder(256);
11912                } else {
11913                    r.append(' ');
11914                }
11915                r.append(a.info.name);
11916            }
11917        }
11918        if (r != null) {
11919            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11920        }
11921
11922        mPermissionManager.removeAllPermissions(pkg, chatty);
11923
11924        N = pkg.instrumentation.size();
11925        r = null;
11926        for (i=0; i<N; i++) {
11927            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11928            mInstrumentation.remove(a.getComponentName());
11929            if (DEBUG_REMOVE && chatty) {
11930                if (r == null) {
11931                    r = new StringBuilder(256);
11932                } else {
11933                    r.append(' ');
11934                }
11935                r.append(a.info.name);
11936            }
11937        }
11938        if (r != null) {
11939            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11940        }
11941
11942        r = null;
11943        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11944            // Only system apps can hold shared libraries.
11945            if (pkg.libraryNames != null) {
11946                for (i = 0; i < pkg.libraryNames.size(); i++) {
11947                    String name = pkg.libraryNames.get(i);
11948                    if (removeSharedLibraryLPw(name, 0)) {
11949                        if (DEBUG_REMOVE && chatty) {
11950                            if (r == null) {
11951                                r = new StringBuilder(256);
11952                            } else {
11953                                r.append(' ');
11954                            }
11955                            r.append(name);
11956                        }
11957                    }
11958                }
11959            }
11960        }
11961
11962        r = null;
11963
11964        // Any package can hold static shared libraries.
11965        if (pkg.staticSharedLibName != null) {
11966            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11967                if (DEBUG_REMOVE && chatty) {
11968                    if (r == null) {
11969                        r = new StringBuilder(256);
11970                    } else {
11971                        r.append(' ');
11972                    }
11973                    r.append(pkg.staticSharedLibName);
11974                }
11975            }
11976        }
11977
11978        if (r != null) {
11979            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11980        }
11981    }
11982
11983    public static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11984    public static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11985    public static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11986
11987    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11988        // Update the parent permissions
11989        updatePermissionsLPw(pkg.packageName, pkg, flags);
11990        // Update the child permissions
11991        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11992        for (int i = 0; i < childCount; i++) {
11993            PackageParser.Package childPkg = pkg.childPackages.get(i);
11994            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11995        }
11996    }
11997
11998    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11999            int flags) {
12000        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12001        updatePermissionsLocked(changingPkg, pkgInfo, volumeUuid, flags);
12002    }
12003
12004    private void updatePermissionsLocked(String changingPkg,
12005            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12006        // TODO: Most of the methods exposing BasePermission internals [source package name,
12007        // etc..] shouldn't be needed. Instead, when we've parsed a permission that doesn't
12008        // have package settings, we should make note of it elsewhere [map between
12009        // source package name and BasePermission] and cycle through that here. Then we
12010        // define a single method on BasePermission that takes a PackageSetting, changing
12011        // package name and a package.
12012        // NOTE: With this approach, we also don't need to tree trees differently than
12013        // normal permissions. Today, we need two separate loops because these BasePermission
12014        // objects are stored separately.
12015        // Make sure there are no dangling permission trees.
12016        flags = mPermissionManager.updatePermissionTrees(changingPkg, pkgInfo, flags);
12017
12018        // Make sure all dynamic permissions have been assigned to a package,
12019        // and make sure there are no dangling permissions.
12020        flags = mPermissionManager.updatePermissions(changingPkg, pkgInfo, flags);
12021
12022        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12023        // Now update the permissions for all packages, in particular
12024        // replace the granted permissions of the system packages.
12025        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12026            for (PackageParser.Package pkg : mPackages.values()) {
12027                if (pkg != pkgInfo) {
12028                    // Only replace for packages on requested volume
12029                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12030                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12031                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12032                    grantPermissionsLPw(pkg, replace, changingPkg);
12033                }
12034            }
12035        }
12036
12037        if (pkgInfo != null) {
12038            // Only replace for packages on requested volume
12039            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12040            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12041                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12042            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12043        }
12044        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12045    }
12046
12047    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12048            String packageOfInterest) {
12049        // IMPORTANT: There are two types of permissions: install and runtime.
12050        // Install time permissions are granted when the app is installed to
12051        // all device users and users added in the future. Runtime permissions
12052        // are granted at runtime explicitly to specific users. Normal and signature
12053        // protected permissions are install time permissions. Dangerous permissions
12054        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12055        // otherwise they are runtime permissions. This function does not manage
12056        // runtime permissions except for the case an app targeting Lollipop MR1
12057        // being upgraded to target a newer SDK, in which case dangerous permissions
12058        // are transformed from install time to runtime ones.
12059
12060        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12061        if (ps == null) {
12062            return;
12063        }
12064
12065        PermissionsState permissionsState = ps.getPermissionsState();
12066        PermissionsState origPermissions = permissionsState;
12067
12068        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12069
12070        boolean runtimePermissionsRevoked = false;
12071        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12072
12073        boolean changedInstallPermission = false;
12074
12075        if (replace) {
12076            ps.installPermissionsFixed = false;
12077            if (!ps.isSharedUser()) {
12078                origPermissions = new PermissionsState(permissionsState);
12079                permissionsState.reset();
12080            } else {
12081                // We need to know only about runtime permission changes since the
12082                // calling code always writes the install permissions state but
12083                // the runtime ones are written only if changed. The only cases of
12084                // changed runtime permissions here are promotion of an install to
12085                // runtime and revocation of a runtime from a shared user.
12086                changedRuntimePermissionUserIds =
12087                        mPermissionManager.revokeUnusedSharedUserPermissions(
12088                                ps.sharedUser, UserManagerService.getInstance().getUserIds());
12089                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12090                    runtimePermissionsRevoked = true;
12091                }
12092            }
12093        }
12094
12095        permissionsState.setGlobalGids(mGlobalGids);
12096
12097        final int N = pkg.requestedPermissions.size();
12098        for (int i=0; i<N; i++) {
12099            final String name = pkg.requestedPermissions.get(i);
12100            final BasePermission bp = (BasePermission) mPermissionManager.getPermissionTEMP(name);
12101            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12102                    >= Build.VERSION_CODES.M;
12103
12104            if (DEBUG_INSTALL) {
12105                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12106            }
12107
12108            if (bp == null || bp.getSourcePackageSetting() == null) {
12109                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12110                    if (DEBUG_PERMISSIONS) {
12111                        Slog.i(TAG, "Unknown permission " + name
12112                                + " in package " + pkg.packageName);
12113                    }
12114                }
12115                continue;
12116            }
12117
12118
12119            // Limit ephemeral apps to ephemeral allowed permissions.
12120            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12121                if (DEBUG_PERMISSIONS) {
12122                    Log.i(TAG, "Denying non-ephemeral permission " + bp.getName() + " for package "
12123                            + pkg.packageName);
12124                }
12125                continue;
12126            }
12127
12128            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12129                if (DEBUG_PERMISSIONS) {
12130                    Log.i(TAG, "Denying runtime-only permission " + bp.getName() + " for package "
12131                            + pkg.packageName);
12132                }
12133                continue;
12134            }
12135
12136            final String perm = bp.getName();
12137            boolean allowedSig = false;
12138            int grant = GRANT_DENIED;
12139
12140            // Keep track of app op permissions.
12141            if (bp.isAppOp()) {
12142                mSettings.addAppOpPackage(perm, pkg.packageName);
12143            }
12144
12145            if (bp.isNormal()) {
12146                // For all apps normal permissions are install time ones.
12147                grant = GRANT_INSTALL;
12148            } else if (bp.isRuntime()) {
12149                // If a permission review is required for legacy apps we represent
12150                // their permissions as always granted runtime ones since we need
12151                // to keep the review required permission flag per user while an
12152                // install permission's state is shared across all users.
12153                if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12154                    // For legacy apps dangerous permissions are install time ones.
12155                    grant = GRANT_INSTALL;
12156                } else if (origPermissions.hasInstallPermission(bp.getName())) {
12157                    // For legacy apps that became modern, install becomes runtime.
12158                    grant = GRANT_UPGRADE;
12159                } else if (mPromoteSystemApps
12160                        && isSystemApp(ps)
12161                        && mExistingSystemPackages.contains(ps.name)) {
12162                    // For legacy system apps, install becomes runtime.
12163                    // We cannot check hasInstallPermission() for system apps since those
12164                    // permissions were granted implicitly and not persisted pre-M.
12165                    grant = GRANT_UPGRADE;
12166                } else {
12167                    // For modern apps keep runtime permissions unchanged.
12168                    grant = GRANT_RUNTIME;
12169                }
12170            } else if (bp.isSignature()) {
12171                // For all apps signature permissions are install time ones.
12172                allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12173                if (allowedSig) {
12174                    grant = GRANT_INSTALL;
12175                }
12176            }
12177
12178            if (DEBUG_PERMISSIONS) {
12179                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12180            }
12181
12182            if (grant != GRANT_DENIED) {
12183                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12184                    // If this is an existing, non-system package, then
12185                    // we can't add any new permissions to it.
12186                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12187                        // Except...  if this is a permission that was added
12188                        // to the platform (note: need to only do this when
12189                        // updating the platform).
12190                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12191                            grant = GRANT_DENIED;
12192                        }
12193                    }
12194                }
12195
12196                switch (grant) {
12197                    case GRANT_INSTALL: {
12198                        // Revoke this as runtime permission to handle the case of
12199                        // a runtime permission being downgraded to an install one.
12200                        // Also in permission review mode we keep dangerous permissions
12201                        // for legacy apps
12202                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12203                            if (origPermissions.getRuntimePermissionState(
12204                                    perm, userId) != null) {
12205                                // Revoke the runtime permission and clear the flags.
12206                                origPermissions.revokeRuntimePermission(bp, userId);
12207                                origPermissions.updatePermissionFlags(bp, userId,
12208                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12209                                // If we revoked a permission permission, we have to write.
12210                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12211                                        changedRuntimePermissionUserIds, userId);
12212                            }
12213                        }
12214                        // Grant an install permission.
12215                        if (permissionsState.grantInstallPermission(bp) !=
12216                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12217                            changedInstallPermission = true;
12218                        }
12219                    } break;
12220
12221                    case GRANT_RUNTIME: {
12222                        // Grant previously granted runtime permissions.
12223                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12224                            PermissionState permissionState = origPermissions
12225                                    .getRuntimePermissionState(perm, userId);
12226                            int flags = permissionState != null
12227                                    ? permissionState.getFlags() : 0;
12228                            if (origPermissions.hasRuntimePermission(perm, userId)) {
12229                                // Don't propagate the permission in a permission review mode if
12230                                // the former was revoked, i.e. marked to not propagate on upgrade.
12231                                // Note that in a permission review mode install permissions are
12232                                // represented as constantly granted runtime ones since we need to
12233                                // keep a per user state associated with the permission. Also the
12234                                // revoke on upgrade flag is no longer applicable and is reset.
12235                                final boolean revokeOnUpgrade = (flags & PackageManager
12236                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12237                                if (revokeOnUpgrade) {
12238                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12239                                    // Since we changed the flags, we have to write.
12240                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12241                                            changedRuntimePermissionUserIds, userId);
12242                                }
12243                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12244                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12245                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12246                                        // If we cannot put the permission as it was,
12247                                        // we have to write.
12248                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12249                                                changedRuntimePermissionUserIds, userId);
12250                                    }
12251                                }
12252
12253                                // If the app supports runtime permissions no need for a review.
12254                                if (mPermissionReviewRequired
12255                                        && appSupportsRuntimePermissions
12256                                        && (flags & PackageManager
12257                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12258                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12259                                    // Since we changed the flags, we have to write.
12260                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12261                                            changedRuntimePermissionUserIds, userId);
12262                                }
12263                            } else if (mPermissionReviewRequired
12264                                    && !appSupportsRuntimePermissions) {
12265                                // For legacy apps that need a permission review, every new
12266                                // runtime permission is granted but it is pending a review.
12267                                // We also need to review only platform defined runtime
12268                                // permissions as these are the only ones the platform knows
12269                                // how to disable the API to simulate revocation as legacy
12270                                // apps don't expect to run with revoked permissions.
12271                                if (PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName())) {
12272                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12273                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12274                                        // We changed the flags, hence have to write.
12275                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12276                                                changedRuntimePermissionUserIds, userId);
12277                                    }
12278                                }
12279                                if (permissionsState.grantRuntimePermission(bp, userId)
12280                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12281                                    // We changed the permission, hence have to write.
12282                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12283                                            changedRuntimePermissionUserIds, userId);
12284                                }
12285                            }
12286                            // Propagate the permission flags.
12287                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12288                        }
12289                    } break;
12290
12291                    case GRANT_UPGRADE: {
12292                        // Grant runtime permissions for a previously held install permission.
12293                        PermissionState permissionState = origPermissions
12294                                .getInstallPermissionState(perm);
12295                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12296
12297                        if (origPermissions.revokeInstallPermission(bp)
12298                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12299                            // We will be transferring the permission flags, so clear them.
12300                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12301                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12302                            changedInstallPermission = true;
12303                        }
12304
12305                        // If the permission is not to be promoted to runtime we ignore it and
12306                        // also its other flags as they are not applicable to install permissions.
12307                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12308                            for (int userId : currentUserIds) {
12309                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12310                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12311                                    // Transfer the permission flags.
12312                                    permissionsState.updatePermissionFlags(bp, userId,
12313                                            flags, flags);
12314                                    // If we granted the permission, we have to write.
12315                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12316                                            changedRuntimePermissionUserIds, userId);
12317                                }
12318                            }
12319                        }
12320                    } break;
12321
12322                    default: {
12323                        if (packageOfInterest == null
12324                                || packageOfInterest.equals(pkg.packageName)) {
12325                            if (DEBUG_PERMISSIONS) {
12326                                Slog.i(TAG, "Not granting permission " + perm
12327                                        + " to package " + pkg.packageName
12328                                        + " because it was previously installed without");
12329                            }
12330                        }
12331                    } break;
12332                }
12333            } else {
12334                if (permissionsState.revokeInstallPermission(bp) !=
12335                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12336                    // Also drop the permission flags.
12337                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12338                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12339                    changedInstallPermission = true;
12340                    Slog.i(TAG, "Un-granting permission " + perm
12341                            + " from package " + pkg.packageName
12342                            + " (protectionLevel=" + bp.getProtectionLevel()
12343                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12344                            + ")");
12345                } else if (bp.isAppOp()) {
12346                    // Don't print warning for app op permissions, since it is fine for them
12347                    // not to be granted, there is a UI for the user to decide.
12348                    if (DEBUG_PERMISSIONS
12349                            && (packageOfInterest == null
12350                                    || packageOfInterest.equals(pkg.packageName))) {
12351                        Slog.i(TAG, "Not granting permission " + perm
12352                                + " to package " + pkg.packageName
12353                                + " (protectionLevel=" + bp.getProtectionLevel()
12354                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12355                                + ")");
12356                    }
12357                }
12358            }
12359        }
12360
12361        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12362                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12363            // This is the first that we have heard about this package, so the
12364            // permissions we have now selected are fixed until explicitly
12365            // changed.
12366            ps.installPermissionsFixed = true;
12367        }
12368
12369        // Persist the runtime permissions state for users with changes. If permissions
12370        // were revoked because no app in the shared user declares them we have to
12371        // write synchronously to avoid losing runtime permissions state.
12372        for (int userId : changedRuntimePermissionUserIds) {
12373            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12374        }
12375    }
12376
12377    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12378        boolean allowed = false;
12379        final int NP = PackageParser.NEW_PERMISSIONS.length;
12380        for (int ip=0; ip<NP; ip++) {
12381            final PackageParser.NewPermissionInfo npi
12382                    = PackageParser.NEW_PERMISSIONS[ip];
12383            if (npi.name.equals(perm)
12384                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12385                allowed = true;
12386                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12387                        + pkg.packageName);
12388                break;
12389            }
12390        }
12391        return allowed;
12392    }
12393
12394    /**
12395     * Determines whether a package is whitelisted for a particular privapp permission.
12396     *
12397     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
12398     *
12399     * <p>This handles parent/child apps.
12400     */
12401    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
12402        ArraySet<String> wlPermissions = SystemConfig.getInstance()
12403                .getPrivAppPermissions(pkg.packageName);
12404        // Let's check if this package is whitelisted...
12405        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12406        // If it's not, we'll also tail-recurse to the parent.
12407        return whitelisted ||
12408                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
12409    }
12410
12411    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12412            BasePermission bp, PermissionsState origPermissions) {
12413        boolean oemPermission = bp.isOEM();
12414        boolean privilegedPermission = bp.isPrivileged();
12415        boolean privappPermissionsDisable =
12416                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12417        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName());
12418        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12419        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12420                && !platformPackage && platformPermission) {
12421            if (!hasPrivappWhitelistEntry(perm, pkg)) {
12422                Slog.w(TAG, "Privileged permission " + perm + " for package "
12423                        + pkg.packageName + " - not in privapp-permissions whitelist");
12424                // Only report violations for apps on system image
12425                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12426                    // it's only a reportable violation if the permission isn't explicitly denied
12427                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
12428                            .getPrivAppDenyPermissions(pkg.packageName);
12429                    final boolean permissionViolation =
12430                            deniedPermissions == null || !deniedPermissions.contains(perm);
12431                    if (permissionViolation
12432                            && RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12433                        if (mPrivappPermissionsViolations == null) {
12434                            mPrivappPermissionsViolations = new ArraySet<>();
12435                        }
12436                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12437                    } else {
12438                        return false;
12439                    }
12440                }
12441                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12442                    return false;
12443                }
12444            }
12445        }
12446        boolean allowed = (compareSignatures(
12447                bp.getSourcePackageSetting().signatures.mSignatures, pkg.mSignatures)
12448                        == PackageManager.SIGNATURE_MATCH)
12449                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12450                        == PackageManager.SIGNATURE_MATCH);
12451        if (!allowed && (privilegedPermission || oemPermission)) {
12452            if (isSystemApp(pkg)) {
12453                // For updated system applications, a privileged/oem permission
12454                // is granted only if it had been defined by the original application.
12455                if (pkg.isUpdatedSystemApp()) {
12456                    final PackageSetting sysPs = mSettings
12457                            .getDisabledSystemPkgLPr(pkg.packageName);
12458                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12459                        // If the original was granted this permission, we take
12460                        // that grant decision as read and propagate it to the
12461                        // update.
12462                        if ((privilegedPermission && sysPs.isPrivileged())
12463                                || (oemPermission && sysPs.isOem()
12464                                        && canGrantOemPermission(sysPs, perm))) {
12465                            allowed = true;
12466                        }
12467                    } else {
12468                        // The system apk may have been updated with an older
12469                        // version of the one on the data partition, but which
12470                        // granted a new system permission that it didn't have
12471                        // before.  In this case we do want to allow the app to
12472                        // now get the new permission if the ancestral apk is
12473                        // privileged to get it.
12474                        if (sysPs != null && sysPs.pkg != null
12475                                && isPackageRequestingPermission(sysPs.pkg, perm)
12476                                && ((privilegedPermission && sysPs.isPrivileged())
12477                                        || (oemPermission && sysPs.isOem()
12478                                                && canGrantOemPermission(sysPs, perm)))) {
12479                            allowed = true;
12480                        }
12481                        // Also if a privileged parent package on the system image or any of
12482                        // its children requested a privileged/oem permission, the updated child
12483                        // packages can also get the permission.
12484                        if (pkg.parentPackage != null) {
12485                            final PackageSetting disabledSysParentPs = mSettings
12486                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12487                            final PackageParser.Package disabledSysParentPkg =
12488                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
12489                                    ? null : disabledSysParentPs.pkg;
12490                            if (disabledSysParentPkg != null
12491                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
12492                                            || (oemPermission && disabledSysParentPs.isOem()))) {
12493                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
12494                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
12495                                    allowed = true;
12496                                } else if (disabledSysParentPkg.childPackages != null) {
12497                                    final int count = disabledSysParentPkg.childPackages.size();
12498                                    for (int i = 0; i < count; i++) {
12499                                        final PackageParser.Package disabledSysChildPkg =
12500                                                disabledSysParentPkg.childPackages.get(i);
12501                                        final PackageSetting disabledSysChildPs =
12502                                                mSettings.getDisabledSystemPkgLPr(
12503                                                        disabledSysChildPkg.packageName);
12504                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
12505                                                && canGrantOemPermission(
12506                                                        disabledSysChildPs, perm)) {
12507                                            allowed = true;
12508                                            break;
12509                                        }
12510                                    }
12511                                }
12512                            }
12513                        }
12514                    }
12515                } else {
12516                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
12517                            || (oemPermission && isOemApp(pkg)
12518                                    && canGrantOemPermission(
12519                                            mSettings.getPackageLPr(pkg.packageName), perm));
12520                }
12521            }
12522        }
12523        if (!allowed) {
12524            if (!allowed
12525                    && bp.isPre23()
12526                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12527                // If this was a previously normal/dangerous permission that got moved
12528                // to a system permission as part of the runtime permission redesign, then
12529                // we still want to blindly grant it to old apps.
12530                allowed = true;
12531            }
12532            if (!allowed && bp.isInstaller()
12533                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12534                // If this permission is to be granted to the system installer and
12535                // this app is an installer, then it gets the permission.
12536                allowed = true;
12537            }
12538            if (!allowed && bp.isVerifier()
12539                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12540                // If this permission is to be granted to the system verifier and
12541                // this app is a verifier, then it gets the permission.
12542                allowed = true;
12543            }
12544            if (!allowed && bp.isPreInstalled()
12545                    && isSystemApp(pkg)) {
12546                // Any pre-installed system app is allowed to get this permission.
12547                allowed = true;
12548            }
12549            if (!allowed && bp.isDevelopment()) {
12550                // For development permissions, a development permission
12551                // is granted only if it was already granted.
12552                allowed = origPermissions.hasInstallPermission(perm);
12553            }
12554            if (!allowed && bp.isSetup()
12555                    && pkg.packageName.equals(mSetupWizardPackage)) {
12556                // If this permission is to be granted to the system setup wizard and
12557                // this app is a setup wizard, then it gets the permission.
12558                allowed = true;
12559            }
12560        }
12561        return allowed;
12562    }
12563
12564    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
12565        if (!ps.isOem()) {
12566            return false;
12567        }
12568        // all oem permissions must explicitly be granted or denied
12569        final Boolean granted =
12570                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
12571        if (granted == null) {
12572            throw new IllegalStateException("OEM permission" + permission + " requested by package "
12573                    + ps.name + " must be explicitly declared granted or not");
12574        }
12575        return Boolean.TRUE == granted;
12576    }
12577
12578    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12579        final int permCount = pkg.requestedPermissions.size();
12580        for (int j = 0; j < permCount; j++) {
12581            String requestedPermission = pkg.requestedPermissions.get(j);
12582            if (permission.equals(requestedPermission)) {
12583                return true;
12584            }
12585        }
12586        return false;
12587    }
12588
12589    final class ActivityIntentResolver
12590            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12591        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12592                boolean defaultOnly, int userId) {
12593            if (!sUserManager.exists(userId)) return null;
12594            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12595            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12596        }
12597
12598        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12599                int userId) {
12600            if (!sUserManager.exists(userId)) return null;
12601            mFlags = flags;
12602            return super.queryIntent(intent, resolvedType,
12603                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12604                    userId);
12605        }
12606
12607        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12608                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12609            if (!sUserManager.exists(userId)) return null;
12610            if (packageActivities == null) {
12611                return null;
12612            }
12613            mFlags = flags;
12614            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12615            final int N = packageActivities.size();
12616            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12617                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12618
12619            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12620            for (int i = 0; i < N; ++i) {
12621                intentFilters = packageActivities.get(i).intents;
12622                if (intentFilters != null && intentFilters.size() > 0) {
12623                    PackageParser.ActivityIntentInfo[] array =
12624                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12625                    intentFilters.toArray(array);
12626                    listCut.add(array);
12627                }
12628            }
12629            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12630        }
12631
12632        /**
12633         * Finds a privileged activity that matches the specified activity names.
12634         */
12635        private PackageParser.Activity findMatchingActivity(
12636                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12637            for (PackageParser.Activity sysActivity : activityList) {
12638                if (sysActivity.info.name.equals(activityInfo.name)) {
12639                    return sysActivity;
12640                }
12641                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12642                    return sysActivity;
12643                }
12644                if (sysActivity.info.targetActivity != null) {
12645                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12646                        return sysActivity;
12647                    }
12648                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12649                        return sysActivity;
12650                    }
12651                }
12652            }
12653            return null;
12654        }
12655
12656        public class IterGenerator<E> {
12657            public Iterator<E> generate(ActivityIntentInfo info) {
12658                return null;
12659            }
12660        }
12661
12662        public class ActionIterGenerator extends IterGenerator<String> {
12663            @Override
12664            public Iterator<String> generate(ActivityIntentInfo info) {
12665                return info.actionsIterator();
12666            }
12667        }
12668
12669        public class CategoriesIterGenerator extends IterGenerator<String> {
12670            @Override
12671            public Iterator<String> generate(ActivityIntentInfo info) {
12672                return info.categoriesIterator();
12673            }
12674        }
12675
12676        public class SchemesIterGenerator extends IterGenerator<String> {
12677            @Override
12678            public Iterator<String> generate(ActivityIntentInfo info) {
12679                return info.schemesIterator();
12680            }
12681        }
12682
12683        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12684            @Override
12685            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12686                return info.authoritiesIterator();
12687            }
12688        }
12689
12690        /**
12691         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12692         * MODIFIED. Do not pass in a list that should not be changed.
12693         */
12694        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12695                IterGenerator<T> generator, Iterator<T> searchIterator) {
12696            // loop through the set of actions; every one must be found in the intent filter
12697            while (searchIterator.hasNext()) {
12698                // we must have at least one filter in the list to consider a match
12699                if (intentList.size() == 0) {
12700                    break;
12701                }
12702
12703                final T searchAction = searchIterator.next();
12704
12705                // loop through the set of intent filters
12706                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12707                while (intentIter.hasNext()) {
12708                    final ActivityIntentInfo intentInfo = intentIter.next();
12709                    boolean selectionFound = false;
12710
12711                    // loop through the intent filter's selection criteria; at least one
12712                    // of them must match the searched criteria
12713                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12714                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12715                        final T intentSelection = intentSelectionIter.next();
12716                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12717                            selectionFound = true;
12718                            break;
12719                        }
12720                    }
12721
12722                    // the selection criteria wasn't found in this filter's set; this filter
12723                    // is not a potential match
12724                    if (!selectionFound) {
12725                        intentIter.remove();
12726                    }
12727                }
12728            }
12729        }
12730
12731        private boolean isProtectedAction(ActivityIntentInfo filter) {
12732            final Iterator<String> actionsIter = filter.actionsIterator();
12733            while (actionsIter != null && actionsIter.hasNext()) {
12734                final String filterAction = actionsIter.next();
12735                if (PROTECTED_ACTIONS.contains(filterAction)) {
12736                    return true;
12737                }
12738            }
12739            return false;
12740        }
12741
12742        /**
12743         * Adjusts the priority of the given intent filter according to policy.
12744         * <p>
12745         * <ul>
12746         * <li>The priority for non privileged applications is capped to '0'</li>
12747         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12748         * <li>The priority for unbundled updates to privileged applications is capped to the
12749         *      priority defined on the system partition</li>
12750         * </ul>
12751         * <p>
12752         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12753         * allowed to obtain any priority on any action.
12754         */
12755        private void adjustPriority(
12756                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12757            // nothing to do; priority is fine as-is
12758            if (intent.getPriority() <= 0) {
12759                return;
12760            }
12761
12762            final ActivityInfo activityInfo = intent.activity.info;
12763            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12764
12765            final boolean privilegedApp =
12766                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12767            if (!privilegedApp) {
12768                // non-privileged applications can never define a priority >0
12769                if (DEBUG_FILTERS) {
12770                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12771                            + " package: " + applicationInfo.packageName
12772                            + " activity: " + intent.activity.className
12773                            + " origPrio: " + intent.getPriority());
12774                }
12775                intent.setPriority(0);
12776                return;
12777            }
12778
12779            if (systemActivities == null) {
12780                // the system package is not disabled; we're parsing the system partition
12781                if (isProtectedAction(intent)) {
12782                    if (mDeferProtectedFilters) {
12783                        // We can't deal with these just yet. No component should ever obtain a
12784                        // >0 priority for a protected actions, with ONE exception -- the setup
12785                        // wizard. The setup wizard, however, cannot be known until we're able to
12786                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12787                        // until all intent filters have been processed. Chicken, meet egg.
12788                        // Let the filter temporarily have a high priority and rectify the
12789                        // priorities after all system packages have been scanned.
12790                        mProtectedFilters.add(intent);
12791                        if (DEBUG_FILTERS) {
12792                            Slog.i(TAG, "Protected action; save for later;"
12793                                    + " package: " + applicationInfo.packageName
12794                                    + " activity: " + intent.activity.className
12795                                    + " origPrio: " + intent.getPriority());
12796                        }
12797                        return;
12798                    } else {
12799                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12800                            Slog.i(TAG, "No setup wizard;"
12801                                + " All protected intents capped to priority 0");
12802                        }
12803                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12804                            if (DEBUG_FILTERS) {
12805                                Slog.i(TAG, "Found setup wizard;"
12806                                    + " allow priority " + intent.getPriority() + ";"
12807                                    + " package: " + intent.activity.info.packageName
12808                                    + " activity: " + intent.activity.className
12809                                    + " priority: " + intent.getPriority());
12810                            }
12811                            // setup wizard gets whatever it wants
12812                            return;
12813                        }
12814                        if (DEBUG_FILTERS) {
12815                            Slog.i(TAG, "Protected action; cap priority to 0;"
12816                                    + " package: " + intent.activity.info.packageName
12817                                    + " activity: " + intent.activity.className
12818                                    + " origPrio: " + intent.getPriority());
12819                        }
12820                        intent.setPriority(0);
12821                        return;
12822                    }
12823                }
12824                // privileged apps on the system image get whatever priority they request
12825                return;
12826            }
12827
12828            // privileged app unbundled update ... try to find the same activity
12829            final PackageParser.Activity foundActivity =
12830                    findMatchingActivity(systemActivities, activityInfo);
12831            if (foundActivity == null) {
12832                // this is a new activity; it cannot obtain >0 priority
12833                if (DEBUG_FILTERS) {
12834                    Slog.i(TAG, "New activity; cap priority to 0;"
12835                            + " package: " + applicationInfo.packageName
12836                            + " activity: " + intent.activity.className
12837                            + " origPrio: " + intent.getPriority());
12838                }
12839                intent.setPriority(0);
12840                return;
12841            }
12842
12843            // found activity, now check for filter equivalence
12844
12845            // a shallow copy is enough; we modify the list, not its contents
12846            final List<ActivityIntentInfo> intentListCopy =
12847                    new ArrayList<>(foundActivity.intents);
12848            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12849
12850            // find matching action subsets
12851            final Iterator<String> actionsIterator = intent.actionsIterator();
12852            if (actionsIterator != null) {
12853                getIntentListSubset(
12854                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12855                if (intentListCopy.size() == 0) {
12856                    // no more intents to match; we're not equivalent
12857                    if (DEBUG_FILTERS) {
12858                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12859                                + " package: " + applicationInfo.packageName
12860                                + " activity: " + intent.activity.className
12861                                + " origPrio: " + intent.getPriority());
12862                    }
12863                    intent.setPriority(0);
12864                    return;
12865                }
12866            }
12867
12868            // find matching category subsets
12869            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12870            if (categoriesIterator != null) {
12871                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12872                        categoriesIterator);
12873                if (intentListCopy.size() == 0) {
12874                    // no more intents to match; we're not equivalent
12875                    if (DEBUG_FILTERS) {
12876                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12877                                + " package: " + applicationInfo.packageName
12878                                + " activity: " + intent.activity.className
12879                                + " origPrio: " + intent.getPriority());
12880                    }
12881                    intent.setPriority(0);
12882                    return;
12883                }
12884            }
12885
12886            // find matching schemes subsets
12887            final Iterator<String> schemesIterator = intent.schemesIterator();
12888            if (schemesIterator != null) {
12889                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12890                        schemesIterator);
12891                if (intentListCopy.size() == 0) {
12892                    // no more intents to match; we're not equivalent
12893                    if (DEBUG_FILTERS) {
12894                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12895                                + " package: " + applicationInfo.packageName
12896                                + " activity: " + intent.activity.className
12897                                + " origPrio: " + intent.getPriority());
12898                    }
12899                    intent.setPriority(0);
12900                    return;
12901                }
12902            }
12903
12904            // find matching authorities subsets
12905            final Iterator<IntentFilter.AuthorityEntry>
12906                    authoritiesIterator = intent.authoritiesIterator();
12907            if (authoritiesIterator != null) {
12908                getIntentListSubset(intentListCopy,
12909                        new AuthoritiesIterGenerator(),
12910                        authoritiesIterator);
12911                if (intentListCopy.size() == 0) {
12912                    // no more intents to match; we're not equivalent
12913                    if (DEBUG_FILTERS) {
12914                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12915                                + " package: " + applicationInfo.packageName
12916                                + " activity: " + intent.activity.className
12917                                + " origPrio: " + intent.getPriority());
12918                    }
12919                    intent.setPriority(0);
12920                    return;
12921                }
12922            }
12923
12924            // we found matching filter(s); app gets the max priority of all intents
12925            int cappedPriority = 0;
12926            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12927                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12928            }
12929            if (intent.getPriority() > cappedPriority) {
12930                if (DEBUG_FILTERS) {
12931                    Slog.i(TAG, "Found matching filter(s);"
12932                            + " cap priority to " + cappedPriority + ";"
12933                            + " package: " + applicationInfo.packageName
12934                            + " activity: " + intent.activity.className
12935                            + " origPrio: " + intent.getPriority());
12936                }
12937                intent.setPriority(cappedPriority);
12938                return;
12939            }
12940            // all this for nothing; the requested priority was <= what was on the system
12941        }
12942
12943        public final void addActivity(PackageParser.Activity a, String type) {
12944            mActivities.put(a.getComponentName(), a);
12945            if (DEBUG_SHOW_INFO)
12946                Log.v(
12947                TAG, "  " + type + " " +
12948                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12949            if (DEBUG_SHOW_INFO)
12950                Log.v(TAG, "    Class=" + a.info.name);
12951            final int NI = a.intents.size();
12952            for (int j=0; j<NI; j++) {
12953                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12954                if ("activity".equals(type)) {
12955                    final PackageSetting ps =
12956                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12957                    final List<PackageParser.Activity> systemActivities =
12958                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12959                    adjustPriority(systemActivities, intent);
12960                }
12961                if (DEBUG_SHOW_INFO) {
12962                    Log.v(TAG, "    IntentFilter:");
12963                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12964                }
12965                if (!intent.debugCheck()) {
12966                    Log.w(TAG, "==> For Activity " + a.info.name);
12967                }
12968                addFilter(intent);
12969            }
12970        }
12971
12972        public final void removeActivity(PackageParser.Activity a, String type) {
12973            mActivities.remove(a.getComponentName());
12974            if (DEBUG_SHOW_INFO) {
12975                Log.v(TAG, "  " + type + " "
12976                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12977                                : a.info.name) + ":");
12978                Log.v(TAG, "    Class=" + a.info.name);
12979            }
12980            final int NI = a.intents.size();
12981            for (int j=0; j<NI; j++) {
12982                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12983                if (DEBUG_SHOW_INFO) {
12984                    Log.v(TAG, "    IntentFilter:");
12985                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12986                }
12987                removeFilter(intent);
12988            }
12989        }
12990
12991        @Override
12992        protected boolean allowFilterResult(
12993                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12994            ActivityInfo filterAi = filter.activity.info;
12995            for (int i=dest.size()-1; i>=0; i--) {
12996                ActivityInfo destAi = dest.get(i).activityInfo;
12997                if (destAi.name == filterAi.name
12998                        && destAi.packageName == filterAi.packageName) {
12999                    return false;
13000                }
13001            }
13002            return true;
13003        }
13004
13005        @Override
13006        protected ActivityIntentInfo[] newArray(int size) {
13007            return new ActivityIntentInfo[size];
13008        }
13009
13010        @Override
13011        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13012            if (!sUserManager.exists(userId)) return true;
13013            PackageParser.Package p = filter.activity.owner;
13014            if (p != null) {
13015                PackageSetting ps = (PackageSetting)p.mExtras;
13016                if (ps != null) {
13017                    // System apps are never considered stopped for purposes of
13018                    // filtering, because there may be no way for the user to
13019                    // actually re-launch them.
13020                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13021                            && ps.getStopped(userId);
13022                }
13023            }
13024            return false;
13025        }
13026
13027        @Override
13028        protected boolean isPackageForFilter(String packageName,
13029                PackageParser.ActivityIntentInfo info) {
13030            return packageName.equals(info.activity.owner.packageName);
13031        }
13032
13033        @Override
13034        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13035                int match, int userId) {
13036            if (!sUserManager.exists(userId)) return null;
13037            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13038                return null;
13039            }
13040            final PackageParser.Activity activity = info.activity;
13041            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13042            if (ps == null) {
13043                return null;
13044            }
13045            final PackageUserState userState = ps.readUserState(userId);
13046            ActivityInfo ai =
13047                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13048            if (ai == null) {
13049                return null;
13050            }
13051            final boolean matchExplicitlyVisibleOnly =
13052                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13053            final boolean matchVisibleToInstantApp =
13054                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13055            final boolean componentVisible =
13056                    matchVisibleToInstantApp
13057                    && info.isVisibleToInstantApp()
13058                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13059            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13060            // throw out filters that aren't visible to ephemeral apps
13061            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13062                return null;
13063            }
13064            // throw out instant app filters if we're not explicitly requesting them
13065            if (!matchInstantApp && userState.instantApp) {
13066                return null;
13067            }
13068            // throw out instant app filters if updates are available; will trigger
13069            // instant app resolution
13070            if (userState.instantApp && ps.isUpdateAvailable()) {
13071                return null;
13072            }
13073            final ResolveInfo res = new ResolveInfo();
13074            res.activityInfo = ai;
13075            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13076                res.filter = info;
13077            }
13078            if (info != null) {
13079                res.handleAllWebDataURI = info.handleAllWebDataURI();
13080            }
13081            res.priority = info.getPriority();
13082            res.preferredOrder = activity.owner.mPreferredOrder;
13083            //System.out.println("Result: " + res.activityInfo.className +
13084            //                   " = " + res.priority);
13085            res.match = match;
13086            res.isDefault = info.hasDefault;
13087            res.labelRes = info.labelRes;
13088            res.nonLocalizedLabel = info.nonLocalizedLabel;
13089            if (userNeedsBadging(userId)) {
13090                res.noResourceId = true;
13091            } else {
13092                res.icon = info.icon;
13093            }
13094            res.iconResourceId = info.icon;
13095            res.system = res.activityInfo.applicationInfo.isSystemApp();
13096            res.isInstantAppAvailable = userState.instantApp;
13097            return res;
13098        }
13099
13100        @Override
13101        protected void sortResults(List<ResolveInfo> results) {
13102            Collections.sort(results, mResolvePrioritySorter);
13103        }
13104
13105        @Override
13106        protected void dumpFilter(PrintWriter out, String prefix,
13107                PackageParser.ActivityIntentInfo filter) {
13108            out.print(prefix); out.print(
13109                    Integer.toHexString(System.identityHashCode(filter.activity)));
13110                    out.print(' ');
13111                    filter.activity.printComponentShortName(out);
13112                    out.print(" filter ");
13113                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13114        }
13115
13116        @Override
13117        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13118            return filter.activity;
13119        }
13120
13121        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13122            PackageParser.Activity activity = (PackageParser.Activity)label;
13123            out.print(prefix); out.print(
13124                    Integer.toHexString(System.identityHashCode(activity)));
13125                    out.print(' ');
13126                    activity.printComponentShortName(out);
13127            if (count > 1) {
13128                out.print(" ("); out.print(count); out.print(" filters)");
13129            }
13130            out.println();
13131        }
13132
13133        // Keys are String (activity class name), values are Activity.
13134        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13135                = new ArrayMap<ComponentName, PackageParser.Activity>();
13136        private int mFlags;
13137    }
13138
13139    private final class ServiceIntentResolver
13140            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13141        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13142                boolean defaultOnly, int userId) {
13143            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13144            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13145        }
13146
13147        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13148                int userId) {
13149            if (!sUserManager.exists(userId)) return null;
13150            mFlags = flags;
13151            return super.queryIntent(intent, resolvedType,
13152                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13153                    userId);
13154        }
13155
13156        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13157                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13158            if (!sUserManager.exists(userId)) return null;
13159            if (packageServices == null) {
13160                return null;
13161            }
13162            mFlags = flags;
13163            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13164            final int N = packageServices.size();
13165            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13166                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13167
13168            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13169            for (int i = 0; i < N; ++i) {
13170                intentFilters = packageServices.get(i).intents;
13171                if (intentFilters != null && intentFilters.size() > 0) {
13172                    PackageParser.ServiceIntentInfo[] array =
13173                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13174                    intentFilters.toArray(array);
13175                    listCut.add(array);
13176                }
13177            }
13178            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13179        }
13180
13181        public final void addService(PackageParser.Service s) {
13182            mServices.put(s.getComponentName(), s);
13183            if (DEBUG_SHOW_INFO) {
13184                Log.v(TAG, "  "
13185                        + (s.info.nonLocalizedLabel != null
13186                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13187                Log.v(TAG, "    Class=" + s.info.name);
13188            }
13189            final int NI = s.intents.size();
13190            int j;
13191            for (j=0; j<NI; j++) {
13192                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13193                if (DEBUG_SHOW_INFO) {
13194                    Log.v(TAG, "    IntentFilter:");
13195                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13196                }
13197                if (!intent.debugCheck()) {
13198                    Log.w(TAG, "==> For Service " + s.info.name);
13199                }
13200                addFilter(intent);
13201            }
13202        }
13203
13204        public final void removeService(PackageParser.Service s) {
13205            mServices.remove(s.getComponentName());
13206            if (DEBUG_SHOW_INFO) {
13207                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13208                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13209                Log.v(TAG, "    Class=" + s.info.name);
13210            }
13211            final int NI = s.intents.size();
13212            int j;
13213            for (j=0; j<NI; j++) {
13214                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13215                if (DEBUG_SHOW_INFO) {
13216                    Log.v(TAG, "    IntentFilter:");
13217                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13218                }
13219                removeFilter(intent);
13220            }
13221        }
13222
13223        @Override
13224        protected boolean allowFilterResult(
13225                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13226            ServiceInfo filterSi = filter.service.info;
13227            for (int i=dest.size()-1; i>=0; i--) {
13228                ServiceInfo destAi = dest.get(i).serviceInfo;
13229                if (destAi.name == filterSi.name
13230                        && destAi.packageName == filterSi.packageName) {
13231                    return false;
13232                }
13233            }
13234            return true;
13235        }
13236
13237        @Override
13238        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13239            return new PackageParser.ServiceIntentInfo[size];
13240        }
13241
13242        @Override
13243        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13244            if (!sUserManager.exists(userId)) return true;
13245            PackageParser.Package p = filter.service.owner;
13246            if (p != null) {
13247                PackageSetting ps = (PackageSetting)p.mExtras;
13248                if (ps != null) {
13249                    // System apps are never considered stopped for purposes of
13250                    // filtering, because there may be no way for the user to
13251                    // actually re-launch them.
13252                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13253                            && ps.getStopped(userId);
13254                }
13255            }
13256            return false;
13257        }
13258
13259        @Override
13260        protected boolean isPackageForFilter(String packageName,
13261                PackageParser.ServiceIntentInfo info) {
13262            return packageName.equals(info.service.owner.packageName);
13263        }
13264
13265        @Override
13266        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13267                int match, int userId) {
13268            if (!sUserManager.exists(userId)) return null;
13269            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13270            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13271                return null;
13272            }
13273            final PackageParser.Service service = info.service;
13274            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13275            if (ps == null) {
13276                return null;
13277            }
13278            final PackageUserState userState = ps.readUserState(userId);
13279            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13280                    userState, userId);
13281            if (si == null) {
13282                return null;
13283            }
13284            final boolean matchVisibleToInstantApp =
13285                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13286            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13287            // throw out filters that aren't visible to ephemeral apps
13288            if (matchVisibleToInstantApp
13289                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13290                return null;
13291            }
13292            // throw out ephemeral filters if we're not explicitly requesting them
13293            if (!isInstantApp && userState.instantApp) {
13294                return null;
13295            }
13296            // throw out instant app filters if updates are available; will trigger
13297            // instant app resolution
13298            if (userState.instantApp && ps.isUpdateAvailable()) {
13299                return null;
13300            }
13301            final ResolveInfo res = new ResolveInfo();
13302            res.serviceInfo = si;
13303            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13304                res.filter = filter;
13305            }
13306            res.priority = info.getPriority();
13307            res.preferredOrder = service.owner.mPreferredOrder;
13308            res.match = match;
13309            res.isDefault = info.hasDefault;
13310            res.labelRes = info.labelRes;
13311            res.nonLocalizedLabel = info.nonLocalizedLabel;
13312            res.icon = info.icon;
13313            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13314            return res;
13315        }
13316
13317        @Override
13318        protected void sortResults(List<ResolveInfo> results) {
13319            Collections.sort(results, mResolvePrioritySorter);
13320        }
13321
13322        @Override
13323        protected void dumpFilter(PrintWriter out, String prefix,
13324                PackageParser.ServiceIntentInfo filter) {
13325            out.print(prefix); out.print(
13326                    Integer.toHexString(System.identityHashCode(filter.service)));
13327                    out.print(' ');
13328                    filter.service.printComponentShortName(out);
13329                    out.print(" filter ");
13330                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13331        }
13332
13333        @Override
13334        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13335            return filter.service;
13336        }
13337
13338        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13339            PackageParser.Service service = (PackageParser.Service)label;
13340            out.print(prefix); out.print(
13341                    Integer.toHexString(System.identityHashCode(service)));
13342                    out.print(' ');
13343                    service.printComponentShortName(out);
13344            if (count > 1) {
13345                out.print(" ("); out.print(count); out.print(" filters)");
13346            }
13347            out.println();
13348        }
13349
13350//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13351//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13352//            final List<ResolveInfo> retList = Lists.newArrayList();
13353//            while (i.hasNext()) {
13354//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13355//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13356//                    retList.add(resolveInfo);
13357//                }
13358//            }
13359//            return retList;
13360//        }
13361
13362        // Keys are String (activity class name), values are Activity.
13363        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13364                = new ArrayMap<ComponentName, PackageParser.Service>();
13365        private int mFlags;
13366    }
13367
13368    private final class ProviderIntentResolver
13369            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13370        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13371                boolean defaultOnly, int userId) {
13372            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13373            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13374        }
13375
13376        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13377                int userId) {
13378            if (!sUserManager.exists(userId))
13379                return null;
13380            mFlags = flags;
13381            return super.queryIntent(intent, resolvedType,
13382                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13383                    userId);
13384        }
13385
13386        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13387                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13388            if (!sUserManager.exists(userId))
13389                return null;
13390            if (packageProviders == null) {
13391                return null;
13392            }
13393            mFlags = flags;
13394            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13395            final int N = packageProviders.size();
13396            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13397                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13398
13399            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13400            for (int i = 0; i < N; ++i) {
13401                intentFilters = packageProviders.get(i).intents;
13402                if (intentFilters != null && intentFilters.size() > 0) {
13403                    PackageParser.ProviderIntentInfo[] array =
13404                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13405                    intentFilters.toArray(array);
13406                    listCut.add(array);
13407                }
13408            }
13409            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13410        }
13411
13412        public final void addProvider(PackageParser.Provider p) {
13413            if (mProviders.containsKey(p.getComponentName())) {
13414                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13415                return;
13416            }
13417
13418            mProviders.put(p.getComponentName(), p);
13419            if (DEBUG_SHOW_INFO) {
13420                Log.v(TAG, "  "
13421                        + (p.info.nonLocalizedLabel != null
13422                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13423                Log.v(TAG, "    Class=" + p.info.name);
13424            }
13425            final int NI = p.intents.size();
13426            int j;
13427            for (j = 0; j < NI; j++) {
13428                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13429                if (DEBUG_SHOW_INFO) {
13430                    Log.v(TAG, "    IntentFilter:");
13431                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13432                }
13433                if (!intent.debugCheck()) {
13434                    Log.w(TAG, "==> For Provider " + p.info.name);
13435                }
13436                addFilter(intent);
13437            }
13438        }
13439
13440        public final void removeProvider(PackageParser.Provider p) {
13441            mProviders.remove(p.getComponentName());
13442            if (DEBUG_SHOW_INFO) {
13443                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13444                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13445                Log.v(TAG, "    Class=" + p.info.name);
13446            }
13447            final int NI = p.intents.size();
13448            int j;
13449            for (j = 0; j < NI; j++) {
13450                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13451                if (DEBUG_SHOW_INFO) {
13452                    Log.v(TAG, "    IntentFilter:");
13453                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13454                }
13455                removeFilter(intent);
13456            }
13457        }
13458
13459        @Override
13460        protected boolean allowFilterResult(
13461                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13462            ProviderInfo filterPi = filter.provider.info;
13463            for (int i = dest.size() - 1; i >= 0; i--) {
13464                ProviderInfo destPi = dest.get(i).providerInfo;
13465                if (destPi.name == filterPi.name
13466                        && destPi.packageName == filterPi.packageName) {
13467                    return false;
13468                }
13469            }
13470            return true;
13471        }
13472
13473        @Override
13474        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13475            return new PackageParser.ProviderIntentInfo[size];
13476        }
13477
13478        @Override
13479        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13480            if (!sUserManager.exists(userId))
13481                return true;
13482            PackageParser.Package p = filter.provider.owner;
13483            if (p != null) {
13484                PackageSetting ps = (PackageSetting) p.mExtras;
13485                if (ps != null) {
13486                    // System apps are never considered stopped for purposes of
13487                    // filtering, because there may be no way for the user to
13488                    // actually re-launch them.
13489                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13490                            && ps.getStopped(userId);
13491                }
13492            }
13493            return false;
13494        }
13495
13496        @Override
13497        protected boolean isPackageForFilter(String packageName,
13498                PackageParser.ProviderIntentInfo info) {
13499            return packageName.equals(info.provider.owner.packageName);
13500        }
13501
13502        @Override
13503        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13504                int match, int userId) {
13505            if (!sUserManager.exists(userId))
13506                return null;
13507            final PackageParser.ProviderIntentInfo info = filter;
13508            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13509                return null;
13510            }
13511            final PackageParser.Provider provider = info.provider;
13512            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13513            if (ps == null) {
13514                return null;
13515            }
13516            final PackageUserState userState = ps.readUserState(userId);
13517            final boolean matchVisibleToInstantApp =
13518                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13519            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13520            // throw out filters that aren't visible to instant applications
13521            if (matchVisibleToInstantApp
13522                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13523                return null;
13524            }
13525            // throw out instant application filters if we're not explicitly requesting them
13526            if (!isInstantApp && userState.instantApp) {
13527                return null;
13528            }
13529            // throw out instant application filters if updates are available; will trigger
13530            // instant application resolution
13531            if (userState.instantApp && ps.isUpdateAvailable()) {
13532                return null;
13533            }
13534            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13535                    userState, userId);
13536            if (pi == null) {
13537                return null;
13538            }
13539            final ResolveInfo res = new ResolveInfo();
13540            res.providerInfo = pi;
13541            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13542                res.filter = filter;
13543            }
13544            res.priority = info.getPriority();
13545            res.preferredOrder = provider.owner.mPreferredOrder;
13546            res.match = match;
13547            res.isDefault = info.hasDefault;
13548            res.labelRes = info.labelRes;
13549            res.nonLocalizedLabel = info.nonLocalizedLabel;
13550            res.icon = info.icon;
13551            res.system = res.providerInfo.applicationInfo.isSystemApp();
13552            return res;
13553        }
13554
13555        @Override
13556        protected void sortResults(List<ResolveInfo> results) {
13557            Collections.sort(results, mResolvePrioritySorter);
13558        }
13559
13560        @Override
13561        protected void dumpFilter(PrintWriter out, String prefix,
13562                PackageParser.ProviderIntentInfo filter) {
13563            out.print(prefix);
13564            out.print(
13565                    Integer.toHexString(System.identityHashCode(filter.provider)));
13566            out.print(' ');
13567            filter.provider.printComponentShortName(out);
13568            out.print(" filter ");
13569            out.println(Integer.toHexString(System.identityHashCode(filter)));
13570        }
13571
13572        @Override
13573        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13574            return filter.provider;
13575        }
13576
13577        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13578            PackageParser.Provider provider = (PackageParser.Provider)label;
13579            out.print(prefix); out.print(
13580                    Integer.toHexString(System.identityHashCode(provider)));
13581                    out.print(' ');
13582                    provider.printComponentShortName(out);
13583            if (count > 1) {
13584                out.print(" ("); out.print(count); out.print(" filters)");
13585            }
13586            out.println();
13587        }
13588
13589        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13590                = new ArrayMap<ComponentName, PackageParser.Provider>();
13591        private int mFlags;
13592    }
13593
13594    static final class EphemeralIntentResolver
13595            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13596        /**
13597         * The result that has the highest defined order. Ordering applies on a
13598         * per-package basis. Mapping is from package name to Pair of order and
13599         * EphemeralResolveInfo.
13600         * <p>
13601         * NOTE: This is implemented as a field variable for convenience and efficiency.
13602         * By having a field variable, we're able to track filter ordering as soon as
13603         * a non-zero order is defined. Otherwise, multiple loops across the result set
13604         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13605         * this needs to be contained entirely within {@link #filterResults}.
13606         */
13607        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13608
13609        @Override
13610        protected AuxiliaryResolveInfo[] newArray(int size) {
13611            return new AuxiliaryResolveInfo[size];
13612        }
13613
13614        @Override
13615        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13616            return true;
13617        }
13618
13619        @Override
13620        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13621                int userId) {
13622            if (!sUserManager.exists(userId)) {
13623                return null;
13624            }
13625            final String packageName = responseObj.resolveInfo.getPackageName();
13626            final Integer order = responseObj.getOrder();
13627            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13628                    mOrderResult.get(packageName);
13629            // ordering is enabled and this item's order isn't high enough
13630            if (lastOrderResult != null && lastOrderResult.first >= order) {
13631                return null;
13632            }
13633            final InstantAppResolveInfo res = responseObj.resolveInfo;
13634            if (order > 0) {
13635                // non-zero order, enable ordering
13636                mOrderResult.put(packageName, new Pair<>(order, res));
13637            }
13638            return responseObj;
13639        }
13640
13641        @Override
13642        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13643            // only do work if ordering is enabled [most of the time it won't be]
13644            if (mOrderResult.size() == 0) {
13645                return;
13646            }
13647            int resultSize = results.size();
13648            for (int i = 0; i < resultSize; i++) {
13649                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13650                final String packageName = info.getPackageName();
13651                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13652                if (savedInfo == null) {
13653                    // package doesn't having ordering
13654                    continue;
13655                }
13656                if (savedInfo.second == info) {
13657                    // circled back to the highest ordered item; remove from order list
13658                    mOrderResult.remove(packageName);
13659                    if (mOrderResult.size() == 0) {
13660                        // no more ordered items
13661                        break;
13662                    }
13663                    continue;
13664                }
13665                // item has a worse order, remove it from the result list
13666                results.remove(i);
13667                resultSize--;
13668                i--;
13669            }
13670        }
13671    }
13672
13673    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13674            new Comparator<ResolveInfo>() {
13675        public int compare(ResolveInfo r1, ResolveInfo r2) {
13676            int v1 = r1.priority;
13677            int v2 = r2.priority;
13678            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13679            if (v1 != v2) {
13680                return (v1 > v2) ? -1 : 1;
13681            }
13682            v1 = r1.preferredOrder;
13683            v2 = r2.preferredOrder;
13684            if (v1 != v2) {
13685                return (v1 > v2) ? -1 : 1;
13686            }
13687            if (r1.isDefault != r2.isDefault) {
13688                return r1.isDefault ? -1 : 1;
13689            }
13690            v1 = r1.match;
13691            v2 = r2.match;
13692            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13693            if (v1 != v2) {
13694                return (v1 > v2) ? -1 : 1;
13695            }
13696            if (r1.system != r2.system) {
13697                return r1.system ? -1 : 1;
13698            }
13699            if (r1.activityInfo != null) {
13700                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13701            }
13702            if (r1.serviceInfo != null) {
13703                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13704            }
13705            if (r1.providerInfo != null) {
13706                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13707            }
13708            return 0;
13709        }
13710    };
13711
13712    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13713            new Comparator<ProviderInfo>() {
13714        public int compare(ProviderInfo p1, ProviderInfo p2) {
13715            final int v1 = p1.initOrder;
13716            final int v2 = p2.initOrder;
13717            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13718        }
13719    };
13720
13721    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13722            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13723            final int[] userIds) {
13724        mHandler.post(new Runnable() {
13725            @Override
13726            public void run() {
13727                try {
13728                    final IActivityManager am = ActivityManager.getService();
13729                    if (am == null) return;
13730                    final int[] resolvedUserIds;
13731                    if (userIds == null) {
13732                        resolvedUserIds = am.getRunningUserIds();
13733                    } else {
13734                        resolvedUserIds = userIds;
13735                    }
13736                    for (int id : resolvedUserIds) {
13737                        final Intent intent = new Intent(action,
13738                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13739                        if (extras != null) {
13740                            intent.putExtras(extras);
13741                        }
13742                        if (targetPkg != null) {
13743                            intent.setPackage(targetPkg);
13744                        }
13745                        // Modify the UID when posting to other users
13746                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13747                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13748                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13749                            intent.putExtra(Intent.EXTRA_UID, uid);
13750                        }
13751                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13752                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13753                        if (DEBUG_BROADCASTS) {
13754                            RuntimeException here = new RuntimeException("here");
13755                            here.fillInStackTrace();
13756                            Slog.d(TAG, "Sending to user " + id + ": "
13757                                    + intent.toShortString(false, true, false, false)
13758                                    + " " + intent.getExtras(), here);
13759                        }
13760                        am.broadcastIntent(null, intent, null, finishedReceiver,
13761                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13762                                null, finishedReceiver != null, false, id);
13763                    }
13764                } catch (RemoteException ex) {
13765                }
13766            }
13767        });
13768    }
13769
13770    /**
13771     * Check if the external storage media is available. This is true if there
13772     * is a mounted external storage medium or if the external storage is
13773     * emulated.
13774     */
13775    private boolean isExternalMediaAvailable() {
13776        return mMediaMounted || Environment.isExternalStorageEmulated();
13777    }
13778
13779    @Override
13780    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13781        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13782            return null;
13783        }
13784        // writer
13785        synchronized (mPackages) {
13786            if (!isExternalMediaAvailable()) {
13787                // If the external storage is no longer mounted at this point,
13788                // the caller may not have been able to delete all of this
13789                // packages files and can not delete any more.  Bail.
13790                return null;
13791            }
13792            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13793            if (lastPackage != null) {
13794                pkgs.remove(lastPackage);
13795            }
13796            if (pkgs.size() > 0) {
13797                return pkgs.get(0);
13798            }
13799        }
13800        return null;
13801    }
13802
13803    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13804        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13805                userId, andCode ? 1 : 0, packageName);
13806        if (mSystemReady) {
13807            msg.sendToTarget();
13808        } else {
13809            if (mPostSystemReadyMessages == null) {
13810                mPostSystemReadyMessages = new ArrayList<>();
13811            }
13812            mPostSystemReadyMessages.add(msg);
13813        }
13814    }
13815
13816    void startCleaningPackages() {
13817        // reader
13818        if (!isExternalMediaAvailable()) {
13819            return;
13820        }
13821        synchronized (mPackages) {
13822            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13823                return;
13824            }
13825        }
13826        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13827        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13828        IActivityManager am = ActivityManager.getService();
13829        if (am != null) {
13830            int dcsUid = -1;
13831            synchronized (mPackages) {
13832                if (!mDefaultContainerWhitelisted) {
13833                    mDefaultContainerWhitelisted = true;
13834                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13835                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13836                }
13837            }
13838            try {
13839                if (dcsUid > 0) {
13840                    am.backgroundWhitelistUid(dcsUid);
13841                }
13842                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13843                        UserHandle.USER_SYSTEM);
13844            } catch (RemoteException e) {
13845            }
13846        }
13847    }
13848
13849    @Override
13850    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13851            int installFlags, String installerPackageName, int userId) {
13852        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13853
13854        final int callingUid = Binder.getCallingUid();
13855        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13856                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13857
13858        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13859            try {
13860                if (observer != null) {
13861                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13862                }
13863            } catch (RemoteException re) {
13864            }
13865            return;
13866        }
13867
13868        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13869            installFlags |= PackageManager.INSTALL_FROM_ADB;
13870
13871        } else {
13872            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13873            // about installerPackageName.
13874
13875            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13876            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13877        }
13878
13879        UserHandle user;
13880        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13881            user = UserHandle.ALL;
13882        } else {
13883            user = new UserHandle(userId);
13884        }
13885
13886        // Only system components can circumvent runtime permissions when installing.
13887        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13888                && mContext.checkCallingOrSelfPermission(Manifest.permission
13889                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13890            throw new SecurityException("You need the "
13891                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13892                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13893        }
13894
13895        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13896                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13897            throw new IllegalArgumentException(
13898                    "New installs into ASEC containers no longer supported");
13899        }
13900
13901        final File originFile = new File(originPath);
13902        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13903
13904        final Message msg = mHandler.obtainMessage(INIT_COPY);
13905        final VerificationInfo verificationInfo = new VerificationInfo(
13906                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13907        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13908                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13909                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13910                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13911        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13912        msg.obj = params;
13913
13914        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13915                System.identityHashCode(msg.obj));
13916        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13917                System.identityHashCode(msg.obj));
13918
13919        mHandler.sendMessage(msg);
13920    }
13921
13922
13923    /**
13924     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13925     * it is acting on behalf on an enterprise or the user).
13926     *
13927     * Note that the ordering of the conditionals in this method is important. The checks we perform
13928     * are as follows, in this order:
13929     *
13930     * 1) If the install is being performed by a system app, we can trust the app to have set the
13931     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13932     *    what it is.
13933     * 2) If the install is being performed by a device or profile owner app, the install reason
13934     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13935     *    set the install reason correctly. If the app targets an older SDK version where install
13936     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13937     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13938     * 3) In all other cases, the install is being performed by a regular app that is neither part
13939     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13940     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13941     *    set to enterprise policy and if so, change it to unknown instead.
13942     */
13943    private int fixUpInstallReason(String installerPackageName, int installerUid,
13944            int installReason) {
13945        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13946                == PERMISSION_GRANTED) {
13947            // If the install is being performed by a system app, we trust that app to have set the
13948            // install reason correctly.
13949            return installReason;
13950        }
13951
13952        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13953            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13954        if (dpm != null) {
13955            ComponentName owner = null;
13956            try {
13957                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13958                if (owner == null) {
13959                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13960                }
13961            } catch (RemoteException e) {
13962            }
13963            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13964                // If the install is being performed by a device or profile owner, the install
13965                // reason should be enterprise policy.
13966                return PackageManager.INSTALL_REASON_POLICY;
13967            }
13968        }
13969
13970        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13971            // If the install is being performed by a regular app (i.e. neither system app nor
13972            // device or profile owner), we have no reason to believe that the app is acting on
13973            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13974            // change it to unknown instead.
13975            return PackageManager.INSTALL_REASON_UNKNOWN;
13976        }
13977
13978        // If the install is being performed by a regular app and the install reason was set to any
13979        // value but enterprise policy, leave the install reason unchanged.
13980        return installReason;
13981    }
13982
13983    void installStage(String packageName, File stagedDir,
13984            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13985            String installerPackageName, int installerUid, UserHandle user,
13986            Certificate[][] certificates) {
13987        if (DEBUG_EPHEMERAL) {
13988            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13989                Slog.d(TAG, "Ephemeral install of " + packageName);
13990            }
13991        }
13992        final VerificationInfo verificationInfo = new VerificationInfo(
13993                sessionParams.originatingUri, sessionParams.referrerUri,
13994                sessionParams.originatingUid, installerUid);
13995
13996        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13997
13998        final Message msg = mHandler.obtainMessage(INIT_COPY);
13999        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14000                sessionParams.installReason);
14001        final InstallParams params = new InstallParams(origin, null, observer,
14002                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14003                verificationInfo, user, sessionParams.abiOverride,
14004                sessionParams.grantedRuntimePermissions, certificates, installReason);
14005        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14006        msg.obj = params;
14007
14008        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14009                System.identityHashCode(msg.obj));
14010        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14011                System.identityHashCode(msg.obj));
14012
14013        mHandler.sendMessage(msg);
14014    }
14015
14016    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14017            int userId) {
14018        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14019        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14020                false /*startReceiver*/, pkgSetting.appId, userId);
14021
14022        // Send a session commit broadcast
14023        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14024        info.installReason = pkgSetting.getInstallReason(userId);
14025        info.appPackageName = packageName;
14026        sendSessionCommitBroadcast(info, userId);
14027    }
14028
14029    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14030            boolean includeStopped, int appId, int... userIds) {
14031        if (ArrayUtils.isEmpty(userIds)) {
14032            return;
14033        }
14034        Bundle extras = new Bundle(1);
14035        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14036        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14037
14038        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14039                packageName, extras, 0, null, null, userIds);
14040        if (sendBootCompleted) {
14041            mHandler.post(() -> {
14042                        for (int userId : userIds) {
14043                            sendBootCompletedBroadcastToSystemApp(
14044                                    packageName, includeStopped, userId);
14045                        }
14046                    }
14047            );
14048        }
14049    }
14050
14051    /**
14052     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14053     * automatically without needing an explicit launch.
14054     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14055     */
14056    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14057            int userId) {
14058        // If user is not running, the app didn't miss any broadcast
14059        if (!mUserManagerInternal.isUserRunning(userId)) {
14060            return;
14061        }
14062        final IActivityManager am = ActivityManager.getService();
14063        try {
14064            // Deliver LOCKED_BOOT_COMPLETED first
14065            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14066                    .setPackage(packageName);
14067            if (includeStopped) {
14068                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14069            }
14070            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14071            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14072                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14073
14074            // Deliver BOOT_COMPLETED only if user is unlocked
14075            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14076                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14077                if (includeStopped) {
14078                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14079                }
14080                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14081                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14082            }
14083        } catch (RemoteException e) {
14084            throw e.rethrowFromSystemServer();
14085        }
14086    }
14087
14088    @Override
14089    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14090            int userId) {
14091        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14092        PackageSetting pkgSetting;
14093        final int callingUid = Binder.getCallingUid();
14094        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14095                true /* requireFullPermission */, true /* checkShell */,
14096                "setApplicationHiddenSetting for user " + userId);
14097
14098        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14099            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14100            return false;
14101        }
14102
14103        long callingId = Binder.clearCallingIdentity();
14104        try {
14105            boolean sendAdded = false;
14106            boolean sendRemoved = false;
14107            // writer
14108            synchronized (mPackages) {
14109                pkgSetting = mSettings.mPackages.get(packageName);
14110                if (pkgSetting == null) {
14111                    return false;
14112                }
14113                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14114                    return false;
14115                }
14116                // Do not allow "android" is being disabled
14117                if ("android".equals(packageName)) {
14118                    Slog.w(TAG, "Cannot hide package: android");
14119                    return false;
14120                }
14121                // Cannot hide static shared libs as they are considered
14122                // a part of the using app (emulating static linking). Also
14123                // static libs are installed always on internal storage.
14124                PackageParser.Package pkg = mPackages.get(packageName);
14125                if (pkg != null && pkg.staticSharedLibName != null) {
14126                    Slog.w(TAG, "Cannot hide package: " + packageName
14127                            + " providing static shared library: "
14128                            + pkg.staticSharedLibName);
14129                    return false;
14130                }
14131                // Only allow protected packages to hide themselves.
14132                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14133                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14134                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14135                    return false;
14136                }
14137
14138                if (pkgSetting.getHidden(userId) != hidden) {
14139                    pkgSetting.setHidden(hidden, userId);
14140                    mSettings.writePackageRestrictionsLPr(userId);
14141                    if (hidden) {
14142                        sendRemoved = true;
14143                    } else {
14144                        sendAdded = true;
14145                    }
14146                }
14147            }
14148            if (sendAdded) {
14149                sendPackageAddedForUser(packageName, pkgSetting, userId);
14150                return true;
14151            }
14152            if (sendRemoved) {
14153                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14154                        "hiding pkg");
14155                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14156                return true;
14157            }
14158        } finally {
14159            Binder.restoreCallingIdentity(callingId);
14160        }
14161        return false;
14162    }
14163
14164    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14165            int userId) {
14166        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14167        info.removedPackage = packageName;
14168        info.installerPackageName = pkgSetting.installerPackageName;
14169        info.removedUsers = new int[] {userId};
14170        info.broadcastUsers = new int[] {userId};
14171        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14172        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14173    }
14174
14175    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14176        if (pkgList.length > 0) {
14177            Bundle extras = new Bundle(1);
14178            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14179
14180            sendPackageBroadcast(
14181                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14182                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14183                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14184                    new int[] {userId});
14185        }
14186    }
14187
14188    /**
14189     * Returns true if application is not found or there was an error. Otherwise it returns
14190     * the hidden state of the package for the given user.
14191     */
14192    @Override
14193    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14194        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14195        final int callingUid = Binder.getCallingUid();
14196        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14197                true /* requireFullPermission */, false /* checkShell */,
14198                "getApplicationHidden for user " + userId);
14199        PackageSetting ps;
14200        long callingId = Binder.clearCallingIdentity();
14201        try {
14202            // writer
14203            synchronized (mPackages) {
14204                ps = mSettings.mPackages.get(packageName);
14205                if (ps == null) {
14206                    return true;
14207                }
14208                if (filterAppAccessLPr(ps, callingUid, userId)) {
14209                    return true;
14210                }
14211                return ps.getHidden(userId);
14212            }
14213        } finally {
14214            Binder.restoreCallingIdentity(callingId);
14215        }
14216    }
14217
14218    /**
14219     * @hide
14220     */
14221    @Override
14222    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14223            int installReason) {
14224        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14225                null);
14226        PackageSetting pkgSetting;
14227        final int callingUid = Binder.getCallingUid();
14228        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14229                true /* requireFullPermission */, true /* checkShell */,
14230                "installExistingPackage for user " + userId);
14231        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14232            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14233        }
14234
14235        long callingId = Binder.clearCallingIdentity();
14236        try {
14237            boolean installed = false;
14238            final boolean instantApp =
14239                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14240            final boolean fullApp =
14241                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14242
14243            // writer
14244            synchronized (mPackages) {
14245                pkgSetting = mSettings.mPackages.get(packageName);
14246                if (pkgSetting == null) {
14247                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14248                }
14249                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14250                    // only allow the existing package to be used if it's installed as a full
14251                    // application for at least one user
14252                    boolean installAllowed = false;
14253                    for (int checkUserId : sUserManager.getUserIds()) {
14254                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14255                        if (installAllowed) {
14256                            break;
14257                        }
14258                    }
14259                    if (!installAllowed) {
14260                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14261                    }
14262                }
14263                if (!pkgSetting.getInstalled(userId)) {
14264                    pkgSetting.setInstalled(true, userId);
14265                    pkgSetting.setHidden(false, userId);
14266                    pkgSetting.setInstallReason(installReason, userId);
14267                    mSettings.writePackageRestrictionsLPr(userId);
14268                    mSettings.writeKernelMappingLPr(pkgSetting);
14269                    installed = true;
14270                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14271                    // upgrade app from instant to full; we don't allow app downgrade
14272                    installed = true;
14273                }
14274                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14275            }
14276
14277            if (installed) {
14278                if (pkgSetting.pkg != null) {
14279                    synchronized (mInstallLock) {
14280                        // We don't need to freeze for a brand new install
14281                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14282                    }
14283                }
14284                sendPackageAddedForUser(packageName, pkgSetting, userId);
14285                synchronized (mPackages) {
14286                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14287                }
14288            }
14289        } finally {
14290            Binder.restoreCallingIdentity(callingId);
14291        }
14292
14293        return PackageManager.INSTALL_SUCCEEDED;
14294    }
14295
14296    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14297            boolean instantApp, boolean fullApp) {
14298        // no state specified; do nothing
14299        if (!instantApp && !fullApp) {
14300            return;
14301        }
14302        if (userId != UserHandle.USER_ALL) {
14303            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14304                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14305            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14306                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14307            }
14308        } else {
14309            for (int currentUserId : sUserManager.getUserIds()) {
14310                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14311                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14312                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14313                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14314                }
14315            }
14316        }
14317    }
14318
14319    boolean isUserRestricted(int userId, String restrictionKey) {
14320        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14321        if (restrictions.getBoolean(restrictionKey, false)) {
14322            Log.w(TAG, "User is restricted: " + restrictionKey);
14323            return true;
14324        }
14325        return false;
14326    }
14327
14328    @Override
14329    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14330            int userId) {
14331        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14332        final int callingUid = Binder.getCallingUid();
14333        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14334                true /* requireFullPermission */, true /* checkShell */,
14335                "setPackagesSuspended for user " + userId);
14336
14337        if (ArrayUtils.isEmpty(packageNames)) {
14338            return packageNames;
14339        }
14340
14341        // List of package names for whom the suspended state has changed.
14342        List<String> changedPackages = new ArrayList<>(packageNames.length);
14343        // List of package names for whom the suspended state is not set as requested in this
14344        // method.
14345        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14346        long callingId = Binder.clearCallingIdentity();
14347        try {
14348            for (int i = 0; i < packageNames.length; i++) {
14349                String packageName = packageNames[i];
14350                boolean changed = false;
14351                final int appId;
14352                synchronized (mPackages) {
14353                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14354                    if (pkgSetting == null
14355                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14356                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14357                                + "\". Skipping suspending/un-suspending.");
14358                        unactionedPackages.add(packageName);
14359                        continue;
14360                    }
14361                    appId = pkgSetting.appId;
14362                    if (pkgSetting.getSuspended(userId) != suspended) {
14363                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14364                            unactionedPackages.add(packageName);
14365                            continue;
14366                        }
14367                        pkgSetting.setSuspended(suspended, userId);
14368                        mSettings.writePackageRestrictionsLPr(userId);
14369                        changed = true;
14370                        changedPackages.add(packageName);
14371                    }
14372                }
14373
14374                if (changed && suspended) {
14375                    killApplication(packageName, UserHandle.getUid(userId, appId),
14376                            "suspending package");
14377                }
14378            }
14379        } finally {
14380            Binder.restoreCallingIdentity(callingId);
14381        }
14382
14383        if (!changedPackages.isEmpty()) {
14384            sendPackagesSuspendedForUser(changedPackages.toArray(
14385                    new String[changedPackages.size()]), userId, suspended);
14386        }
14387
14388        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14389    }
14390
14391    @Override
14392    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14393        final int callingUid = Binder.getCallingUid();
14394        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14395                true /* requireFullPermission */, false /* checkShell */,
14396                "isPackageSuspendedForUser for user " + userId);
14397        synchronized (mPackages) {
14398            final PackageSetting ps = mSettings.mPackages.get(packageName);
14399            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14400                throw new IllegalArgumentException("Unknown target package: " + packageName);
14401            }
14402            return ps.getSuspended(userId);
14403        }
14404    }
14405
14406    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14407        if (isPackageDeviceAdmin(packageName, userId)) {
14408            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14409                    + "\": has an active device admin");
14410            return false;
14411        }
14412
14413        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14414        if (packageName.equals(activeLauncherPackageName)) {
14415            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14416                    + "\": contains the active launcher");
14417            return false;
14418        }
14419
14420        if (packageName.equals(mRequiredInstallerPackage)) {
14421            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14422                    + "\": required for package installation");
14423            return false;
14424        }
14425
14426        if (packageName.equals(mRequiredUninstallerPackage)) {
14427            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14428                    + "\": required for package uninstallation");
14429            return false;
14430        }
14431
14432        if (packageName.equals(mRequiredVerifierPackage)) {
14433            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14434                    + "\": required for package verification");
14435            return false;
14436        }
14437
14438        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14439            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14440                    + "\": is the default dialer");
14441            return false;
14442        }
14443
14444        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14445            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14446                    + "\": protected package");
14447            return false;
14448        }
14449
14450        // Cannot suspend static shared libs as they are considered
14451        // a part of the using app (emulating static linking). Also
14452        // static libs are installed always on internal storage.
14453        PackageParser.Package pkg = mPackages.get(packageName);
14454        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14455            Slog.w(TAG, "Cannot suspend package: " + packageName
14456                    + " providing static shared library: "
14457                    + pkg.staticSharedLibName);
14458            return false;
14459        }
14460
14461        return true;
14462    }
14463
14464    private String getActiveLauncherPackageName(int userId) {
14465        Intent intent = new Intent(Intent.ACTION_MAIN);
14466        intent.addCategory(Intent.CATEGORY_HOME);
14467        ResolveInfo resolveInfo = resolveIntent(
14468                intent,
14469                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14470                PackageManager.MATCH_DEFAULT_ONLY,
14471                userId);
14472
14473        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14474    }
14475
14476    private String getDefaultDialerPackageName(int userId) {
14477        synchronized (mPackages) {
14478            return mSettings.getDefaultDialerPackageNameLPw(userId);
14479        }
14480    }
14481
14482    @Override
14483    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14484        mContext.enforceCallingOrSelfPermission(
14485                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14486                "Only package verification agents can verify applications");
14487
14488        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14489        final PackageVerificationResponse response = new PackageVerificationResponse(
14490                verificationCode, Binder.getCallingUid());
14491        msg.arg1 = id;
14492        msg.obj = response;
14493        mHandler.sendMessage(msg);
14494    }
14495
14496    @Override
14497    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14498            long millisecondsToDelay) {
14499        mContext.enforceCallingOrSelfPermission(
14500                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14501                "Only package verification agents can extend verification timeouts");
14502
14503        final PackageVerificationState state = mPendingVerification.get(id);
14504        final PackageVerificationResponse response = new PackageVerificationResponse(
14505                verificationCodeAtTimeout, Binder.getCallingUid());
14506
14507        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14508            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14509        }
14510        if (millisecondsToDelay < 0) {
14511            millisecondsToDelay = 0;
14512        }
14513        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14514                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14515            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14516        }
14517
14518        if ((state != null) && !state.timeoutExtended()) {
14519            state.extendTimeout();
14520
14521            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14522            msg.arg1 = id;
14523            msg.obj = response;
14524            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14525        }
14526    }
14527
14528    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14529            int verificationCode, UserHandle user) {
14530        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14531        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14532        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14533        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14534        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14535
14536        mContext.sendBroadcastAsUser(intent, user,
14537                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14538    }
14539
14540    private ComponentName matchComponentForVerifier(String packageName,
14541            List<ResolveInfo> receivers) {
14542        ActivityInfo targetReceiver = null;
14543
14544        final int NR = receivers.size();
14545        for (int i = 0; i < NR; i++) {
14546            final ResolveInfo info = receivers.get(i);
14547            if (info.activityInfo == null) {
14548                continue;
14549            }
14550
14551            if (packageName.equals(info.activityInfo.packageName)) {
14552                targetReceiver = info.activityInfo;
14553                break;
14554            }
14555        }
14556
14557        if (targetReceiver == null) {
14558            return null;
14559        }
14560
14561        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14562    }
14563
14564    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14565            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14566        if (pkgInfo.verifiers.length == 0) {
14567            return null;
14568        }
14569
14570        final int N = pkgInfo.verifiers.length;
14571        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14572        for (int i = 0; i < N; i++) {
14573            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14574
14575            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14576                    receivers);
14577            if (comp == null) {
14578                continue;
14579            }
14580
14581            final int verifierUid = getUidForVerifier(verifierInfo);
14582            if (verifierUid == -1) {
14583                continue;
14584            }
14585
14586            if (DEBUG_VERIFY) {
14587                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14588                        + " with the correct signature");
14589            }
14590            sufficientVerifiers.add(comp);
14591            verificationState.addSufficientVerifier(verifierUid);
14592        }
14593
14594        return sufficientVerifiers;
14595    }
14596
14597    private int getUidForVerifier(VerifierInfo verifierInfo) {
14598        synchronized (mPackages) {
14599            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14600            if (pkg == null) {
14601                return -1;
14602            } else if (pkg.mSignatures.length != 1) {
14603                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14604                        + " has more than one signature; ignoring");
14605                return -1;
14606            }
14607
14608            /*
14609             * If the public key of the package's signature does not match
14610             * our expected public key, then this is a different package and
14611             * we should skip.
14612             */
14613
14614            final byte[] expectedPublicKey;
14615            try {
14616                final Signature verifierSig = pkg.mSignatures[0];
14617                final PublicKey publicKey = verifierSig.getPublicKey();
14618                expectedPublicKey = publicKey.getEncoded();
14619            } catch (CertificateException e) {
14620                return -1;
14621            }
14622
14623            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14624
14625            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14626                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14627                        + " does not have the expected public key; ignoring");
14628                return -1;
14629            }
14630
14631            return pkg.applicationInfo.uid;
14632        }
14633    }
14634
14635    @Override
14636    public void finishPackageInstall(int token, boolean didLaunch) {
14637        enforceSystemOrRoot("Only the system is allowed to finish installs");
14638
14639        if (DEBUG_INSTALL) {
14640            Slog.v(TAG, "BM finishing package install for " + token);
14641        }
14642        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14643
14644        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14645        mHandler.sendMessage(msg);
14646    }
14647
14648    /**
14649     * Get the verification agent timeout.  Used for both the APK verifier and the
14650     * intent filter verifier.
14651     *
14652     * @return verification timeout in milliseconds
14653     */
14654    private long getVerificationTimeout() {
14655        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14656                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14657                DEFAULT_VERIFICATION_TIMEOUT);
14658    }
14659
14660    /**
14661     * Get the default verification agent response code.
14662     *
14663     * @return default verification response code
14664     */
14665    private int getDefaultVerificationResponse(UserHandle user) {
14666        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14667            return PackageManager.VERIFICATION_REJECT;
14668        }
14669        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14670                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14671                DEFAULT_VERIFICATION_RESPONSE);
14672    }
14673
14674    /**
14675     * Check whether or not package verification has been enabled.
14676     *
14677     * @return true if verification should be performed
14678     */
14679    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14680        if (!DEFAULT_VERIFY_ENABLE) {
14681            return false;
14682        }
14683
14684        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14685
14686        // Check if installing from ADB
14687        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14688            // Do not run verification in a test harness environment
14689            if (ActivityManager.isRunningInTestHarness()) {
14690                return false;
14691            }
14692            if (ensureVerifyAppsEnabled) {
14693                return true;
14694            }
14695            // Check if the developer does not want package verification for ADB installs
14696            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14697                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14698                return false;
14699            }
14700        } else {
14701            // only when not installed from ADB, skip verification for instant apps when
14702            // the installer and verifier are the same.
14703            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14704                if (mInstantAppInstallerActivity != null
14705                        && mInstantAppInstallerActivity.packageName.equals(
14706                                mRequiredVerifierPackage)) {
14707                    try {
14708                        mContext.getSystemService(AppOpsManager.class)
14709                                .checkPackage(installerUid, mRequiredVerifierPackage);
14710                        if (DEBUG_VERIFY) {
14711                            Slog.i(TAG, "disable verification for instant app");
14712                        }
14713                        return false;
14714                    } catch (SecurityException ignore) { }
14715                }
14716            }
14717        }
14718
14719        if (ensureVerifyAppsEnabled) {
14720            return true;
14721        }
14722
14723        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14724                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14725    }
14726
14727    @Override
14728    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14729            throws RemoteException {
14730        mContext.enforceCallingOrSelfPermission(
14731                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14732                "Only intentfilter verification agents can verify applications");
14733
14734        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14735        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14736                Binder.getCallingUid(), verificationCode, failedDomains);
14737        msg.arg1 = id;
14738        msg.obj = response;
14739        mHandler.sendMessage(msg);
14740    }
14741
14742    @Override
14743    public int getIntentVerificationStatus(String packageName, int userId) {
14744        final int callingUid = Binder.getCallingUid();
14745        if (UserHandle.getUserId(callingUid) != userId) {
14746            mContext.enforceCallingOrSelfPermission(
14747                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14748                    "getIntentVerificationStatus" + userId);
14749        }
14750        if (getInstantAppPackageName(callingUid) != null) {
14751            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14752        }
14753        synchronized (mPackages) {
14754            final PackageSetting ps = mSettings.mPackages.get(packageName);
14755            if (ps == null
14756                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14757                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14758            }
14759            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14760        }
14761    }
14762
14763    @Override
14764    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14765        mContext.enforceCallingOrSelfPermission(
14766                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14767
14768        boolean result = false;
14769        synchronized (mPackages) {
14770            final PackageSetting ps = mSettings.mPackages.get(packageName);
14771            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14772                return false;
14773            }
14774            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14775        }
14776        if (result) {
14777            scheduleWritePackageRestrictionsLocked(userId);
14778        }
14779        return result;
14780    }
14781
14782    @Override
14783    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14784            String packageName) {
14785        final int callingUid = Binder.getCallingUid();
14786        if (getInstantAppPackageName(callingUid) != null) {
14787            return ParceledListSlice.emptyList();
14788        }
14789        synchronized (mPackages) {
14790            final PackageSetting ps = mSettings.mPackages.get(packageName);
14791            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14792                return ParceledListSlice.emptyList();
14793            }
14794            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14795        }
14796    }
14797
14798    @Override
14799    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14800        if (TextUtils.isEmpty(packageName)) {
14801            return ParceledListSlice.emptyList();
14802        }
14803        final int callingUid = Binder.getCallingUid();
14804        final int callingUserId = UserHandle.getUserId(callingUid);
14805        synchronized (mPackages) {
14806            PackageParser.Package pkg = mPackages.get(packageName);
14807            if (pkg == null || pkg.activities == null) {
14808                return ParceledListSlice.emptyList();
14809            }
14810            if (pkg.mExtras == null) {
14811                return ParceledListSlice.emptyList();
14812            }
14813            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14814            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14815                return ParceledListSlice.emptyList();
14816            }
14817            final int count = pkg.activities.size();
14818            ArrayList<IntentFilter> result = new ArrayList<>();
14819            for (int n=0; n<count; n++) {
14820                PackageParser.Activity activity = pkg.activities.get(n);
14821                if (activity.intents != null && activity.intents.size() > 0) {
14822                    result.addAll(activity.intents);
14823                }
14824            }
14825            return new ParceledListSlice<>(result);
14826        }
14827    }
14828
14829    @Override
14830    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14831        mContext.enforceCallingOrSelfPermission(
14832                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14833        if (UserHandle.getCallingUserId() != userId) {
14834            mContext.enforceCallingOrSelfPermission(
14835                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14836        }
14837
14838        synchronized (mPackages) {
14839            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14840            if (packageName != null) {
14841                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14842                        packageName, userId);
14843            }
14844            return result;
14845        }
14846    }
14847
14848    @Override
14849    public String getDefaultBrowserPackageName(int userId) {
14850        if (UserHandle.getCallingUserId() != userId) {
14851            mContext.enforceCallingOrSelfPermission(
14852                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14853        }
14854        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14855            return null;
14856        }
14857        synchronized (mPackages) {
14858            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14859        }
14860    }
14861
14862    /**
14863     * Get the "allow unknown sources" setting.
14864     *
14865     * @return the current "allow unknown sources" setting
14866     */
14867    private int getUnknownSourcesSettings() {
14868        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14869                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14870                -1);
14871    }
14872
14873    @Override
14874    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14875        final int callingUid = Binder.getCallingUid();
14876        if (getInstantAppPackageName(callingUid) != null) {
14877            return;
14878        }
14879        // writer
14880        synchronized (mPackages) {
14881            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14882            if (targetPackageSetting == null
14883                    || filterAppAccessLPr(
14884                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14885                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14886            }
14887
14888            PackageSetting installerPackageSetting;
14889            if (installerPackageName != null) {
14890                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14891                if (installerPackageSetting == null) {
14892                    throw new IllegalArgumentException("Unknown installer package: "
14893                            + installerPackageName);
14894                }
14895            } else {
14896                installerPackageSetting = null;
14897            }
14898
14899            Signature[] callerSignature;
14900            Object obj = mSettings.getUserIdLPr(callingUid);
14901            if (obj != null) {
14902                if (obj instanceof SharedUserSetting) {
14903                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14904                } else if (obj instanceof PackageSetting) {
14905                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14906                } else {
14907                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14908                }
14909            } else {
14910                throw new SecurityException("Unknown calling UID: " + callingUid);
14911            }
14912
14913            // Verify: can't set installerPackageName to a package that is
14914            // not signed with the same cert as the caller.
14915            if (installerPackageSetting != null) {
14916                if (compareSignatures(callerSignature,
14917                        installerPackageSetting.signatures.mSignatures)
14918                        != PackageManager.SIGNATURE_MATCH) {
14919                    throw new SecurityException(
14920                            "Caller does not have same cert as new installer package "
14921                            + installerPackageName);
14922                }
14923            }
14924
14925            // Verify: if target already has an installer package, it must
14926            // be signed with the same cert as the caller.
14927            if (targetPackageSetting.installerPackageName != null) {
14928                PackageSetting setting = mSettings.mPackages.get(
14929                        targetPackageSetting.installerPackageName);
14930                // If the currently set package isn't valid, then it's always
14931                // okay to change it.
14932                if (setting != null) {
14933                    if (compareSignatures(callerSignature,
14934                            setting.signatures.mSignatures)
14935                            != PackageManager.SIGNATURE_MATCH) {
14936                        throw new SecurityException(
14937                                "Caller does not have same cert as old installer package "
14938                                + targetPackageSetting.installerPackageName);
14939                    }
14940                }
14941            }
14942
14943            // Okay!
14944            targetPackageSetting.installerPackageName = installerPackageName;
14945            if (installerPackageName != null) {
14946                mSettings.mInstallerPackages.add(installerPackageName);
14947            }
14948            scheduleWriteSettingsLocked();
14949        }
14950    }
14951
14952    @Override
14953    public void setApplicationCategoryHint(String packageName, int categoryHint,
14954            String callerPackageName) {
14955        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14956            throw new SecurityException("Instant applications don't have access to this method");
14957        }
14958        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14959                callerPackageName);
14960        synchronized (mPackages) {
14961            PackageSetting ps = mSettings.mPackages.get(packageName);
14962            if (ps == null) {
14963                throw new IllegalArgumentException("Unknown target package " + packageName);
14964            }
14965            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14966                throw new IllegalArgumentException("Unknown target package " + packageName);
14967            }
14968            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14969                throw new IllegalArgumentException("Calling package " + callerPackageName
14970                        + " is not installer for " + packageName);
14971            }
14972
14973            if (ps.categoryHint != categoryHint) {
14974                ps.categoryHint = categoryHint;
14975                scheduleWriteSettingsLocked();
14976            }
14977        }
14978    }
14979
14980    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14981        // Queue up an async operation since the package installation may take a little while.
14982        mHandler.post(new Runnable() {
14983            public void run() {
14984                mHandler.removeCallbacks(this);
14985                 // Result object to be returned
14986                PackageInstalledInfo res = new PackageInstalledInfo();
14987                res.setReturnCode(currentStatus);
14988                res.uid = -1;
14989                res.pkg = null;
14990                res.removedInfo = null;
14991                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14992                    args.doPreInstall(res.returnCode);
14993                    synchronized (mInstallLock) {
14994                        installPackageTracedLI(args, res);
14995                    }
14996                    args.doPostInstall(res.returnCode, res.uid);
14997                }
14998
14999                // A restore should be performed at this point if (a) the install
15000                // succeeded, (b) the operation is not an update, and (c) the new
15001                // package has not opted out of backup participation.
15002                final boolean update = res.removedInfo != null
15003                        && res.removedInfo.removedPackage != null;
15004                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15005                boolean doRestore = !update
15006                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15007
15008                // Set up the post-install work request bookkeeping.  This will be used
15009                // and cleaned up by the post-install event handling regardless of whether
15010                // there's a restore pass performed.  Token values are >= 1.
15011                int token;
15012                if (mNextInstallToken < 0) mNextInstallToken = 1;
15013                token = mNextInstallToken++;
15014
15015                PostInstallData data = new PostInstallData(args, res);
15016                mRunningInstalls.put(token, data);
15017                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15018
15019                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15020                    // Pass responsibility to the Backup Manager.  It will perform a
15021                    // restore if appropriate, then pass responsibility back to the
15022                    // Package Manager to run the post-install observer callbacks
15023                    // and broadcasts.
15024                    IBackupManager bm = IBackupManager.Stub.asInterface(
15025                            ServiceManager.getService(Context.BACKUP_SERVICE));
15026                    if (bm != null) {
15027                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15028                                + " to BM for possible restore");
15029                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15030                        try {
15031                            // TODO: http://b/22388012
15032                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15033                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15034                            } else {
15035                                doRestore = false;
15036                            }
15037                        } catch (RemoteException e) {
15038                            // can't happen; the backup manager is local
15039                        } catch (Exception e) {
15040                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15041                            doRestore = false;
15042                        }
15043                    } else {
15044                        Slog.e(TAG, "Backup Manager not found!");
15045                        doRestore = false;
15046                    }
15047                }
15048
15049                if (!doRestore) {
15050                    // No restore possible, or the Backup Manager was mysteriously not
15051                    // available -- just fire the post-install work request directly.
15052                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15053
15054                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15055
15056                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15057                    mHandler.sendMessage(msg);
15058                }
15059            }
15060        });
15061    }
15062
15063    /**
15064     * Callback from PackageSettings whenever an app is first transitioned out of the
15065     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15066     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15067     * here whether the app is the target of an ongoing install, and only send the
15068     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15069     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15070     * handling.
15071     */
15072    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15073        // Serialize this with the rest of the install-process message chain.  In the
15074        // restore-at-install case, this Runnable will necessarily run before the
15075        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15076        // are coherent.  In the non-restore case, the app has already completed install
15077        // and been launched through some other means, so it is not in a problematic
15078        // state for observers to see the FIRST_LAUNCH signal.
15079        mHandler.post(new Runnable() {
15080            @Override
15081            public void run() {
15082                for (int i = 0; i < mRunningInstalls.size(); i++) {
15083                    final PostInstallData data = mRunningInstalls.valueAt(i);
15084                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15085                        continue;
15086                    }
15087                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15088                        // right package; but is it for the right user?
15089                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15090                            if (userId == data.res.newUsers[uIndex]) {
15091                                if (DEBUG_BACKUP) {
15092                                    Slog.i(TAG, "Package " + pkgName
15093                                            + " being restored so deferring FIRST_LAUNCH");
15094                                }
15095                                return;
15096                            }
15097                        }
15098                    }
15099                }
15100                // didn't find it, so not being restored
15101                if (DEBUG_BACKUP) {
15102                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15103                }
15104                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15105            }
15106        });
15107    }
15108
15109    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15110        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15111                installerPkg, null, userIds);
15112    }
15113
15114    private abstract class HandlerParams {
15115        private static final int MAX_RETRIES = 4;
15116
15117        /**
15118         * Number of times startCopy() has been attempted and had a non-fatal
15119         * error.
15120         */
15121        private int mRetries = 0;
15122
15123        /** User handle for the user requesting the information or installation. */
15124        private final UserHandle mUser;
15125        String traceMethod;
15126        int traceCookie;
15127
15128        HandlerParams(UserHandle user) {
15129            mUser = user;
15130        }
15131
15132        UserHandle getUser() {
15133            return mUser;
15134        }
15135
15136        HandlerParams setTraceMethod(String traceMethod) {
15137            this.traceMethod = traceMethod;
15138            return this;
15139        }
15140
15141        HandlerParams setTraceCookie(int traceCookie) {
15142            this.traceCookie = traceCookie;
15143            return this;
15144        }
15145
15146        final boolean startCopy() {
15147            boolean res;
15148            try {
15149                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15150
15151                if (++mRetries > MAX_RETRIES) {
15152                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15153                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15154                    handleServiceError();
15155                    return false;
15156                } else {
15157                    handleStartCopy();
15158                    res = true;
15159                }
15160            } catch (RemoteException e) {
15161                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15162                mHandler.sendEmptyMessage(MCS_RECONNECT);
15163                res = false;
15164            }
15165            handleReturnCode();
15166            return res;
15167        }
15168
15169        final void serviceError() {
15170            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15171            handleServiceError();
15172            handleReturnCode();
15173        }
15174
15175        abstract void handleStartCopy() throws RemoteException;
15176        abstract void handleServiceError();
15177        abstract void handleReturnCode();
15178    }
15179
15180    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15181        for (File path : paths) {
15182            try {
15183                mcs.clearDirectory(path.getAbsolutePath());
15184            } catch (RemoteException e) {
15185            }
15186        }
15187    }
15188
15189    static class OriginInfo {
15190        /**
15191         * Location where install is coming from, before it has been
15192         * copied/renamed into place. This could be a single monolithic APK
15193         * file, or a cluster directory. This location may be untrusted.
15194         */
15195        final File file;
15196
15197        /**
15198         * Flag indicating that {@link #file} or {@link #cid} has already been
15199         * staged, meaning downstream users don't need to defensively copy the
15200         * contents.
15201         */
15202        final boolean staged;
15203
15204        /**
15205         * Flag indicating that {@link #file} or {@link #cid} is an already
15206         * installed app that is being moved.
15207         */
15208        final boolean existing;
15209
15210        final String resolvedPath;
15211        final File resolvedFile;
15212
15213        static OriginInfo fromNothing() {
15214            return new OriginInfo(null, false, false);
15215        }
15216
15217        static OriginInfo fromUntrustedFile(File file) {
15218            return new OriginInfo(file, false, false);
15219        }
15220
15221        static OriginInfo fromExistingFile(File file) {
15222            return new OriginInfo(file, false, true);
15223        }
15224
15225        static OriginInfo fromStagedFile(File file) {
15226            return new OriginInfo(file, true, false);
15227        }
15228
15229        private OriginInfo(File file, boolean staged, boolean existing) {
15230            this.file = file;
15231            this.staged = staged;
15232            this.existing = existing;
15233
15234            if (file != null) {
15235                resolvedPath = file.getAbsolutePath();
15236                resolvedFile = file;
15237            } else {
15238                resolvedPath = null;
15239                resolvedFile = null;
15240            }
15241        }
15242    }
15243
15244    static class MoveInfo {
15245        final int moveId;
15246        final String fromUuid;
15247        final String toUuid;
15248        final String packageName;
15249        final String dataAppName;
15250        final int appId;
15251        final String seinfo;
15252        final int targetSdkVersion;
15253
15254        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15255                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15256            this.moveId = moveId;
15257            this.fromUuid = fromUuid;
15258            this.toUuid = toUuid;
15259            this.packageName = packageName;
15260            this.dataAppName = dataAppName;
15261            this.appId = appId;
15262            this.seinfo = seinfo;
15263            this.targetSdkVersion = targetSdkVersion;
15264        }
15265    }
15266
15267    static class VerificationInfo {
15268        /** A constant used to indicate that a uid value is not present. */
15269        public static final int NO_UID = -1;
15270
15271        /** URI referencing where the package was downloaded from. */
15272        final Uri originatingUri;
15273
15274        /** HTTP referrer URI associated with the originatingURI. */
15275        final Uri referrer;
15276
15277        /** UID of the application that the install request originated from. */
15278        final int originatingUid;
15279
15280        /** UID of application requesting the install */
15281        final int installerUid;
15282
15283        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15284            this.originatingUri = originatingUri;
15285            this.referrer = referrer;
15286            this.originatingUid = originatingUid;
15287            this.installerUid = installerUid;
15288        }
15289    }
15290
15291    class InstallParams extends HandlerParams {
15292        final OriginInfo origin;
15293        final MoveInfo move;
15294        final IPackageInstallObserver2 observer;
15295        int installFlags;
15296        final String installerPackageName;
15297        final String volumeUuid;
15298        private InstallArgs mArgs;
15299        private int mRet;
15300        final String packageAbiOverride;
15301        final String[] grantedRuntimePermissions;
15302        final VerificationInfo verificationInfo;
15303        final Certificate[][] certificates;
15304        final int installReason;
15305
15306        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15307                int installFlags, String installerPackageName, String volumeUuid,
15308                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15309                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15310            super(user);
15311            this.origin = origin;
15312            this.move = move;
15313            this.observer = observer;
15314            this.installFlags = installFlags;
15315            this.installerPackageName = installerPackageName;
15316            this.volumeUuid = volumeUuid;
15317            this.verificationInfo = verificationInfo;
15318            this.packageAbiOverride = packageAbiOverride;
15319            this.grantedRuntimePermissions = grantedPermissions;
15320            this.certificates = certificates;
15321            this.installReason = installReason;
15322        }
15323
15324        @Override
15325        public String toString() {
15326            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15327                    + " file=" + origin.file + "}";
15328        }
15329
15330        private int installLocationPolicy(PackageInfoLite pkgLite) {
15331            String packageName = pkgLite.packageName;
15332            int installLocation = pkgLite.installLocation;
15333            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15334            // reader
15335            synchronized (mPackages) {
15336                // Currently installed package which the new package is attempting to replace or
15337                // null if no such package is installed.
15338                PackageParser.Package installedPkg = mPackages.get(packageName);
15339                // Package which currently owns the data which the new package will own if installed.
15340                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15341                // will be null whereas dataOwnerPkg will contain information about the package
15342                // which was uninstalled while keeping its data.
15343                PackageParser.Package dataOwnerPkg = installedPkg;
15344                if (dataOwnerPkg  == null) {
15345                    PackageSetting ps = mSettings.mPackages.get(packageName);
15346                    if (ps != null) {
15347                        dataOwnerPkg = ps.pkg;
15348                    }
15349                }
15350
15351                if (dataOwnerPkg != null) {
15352                    // If installed, the package will get access to data left on the device by its
15353                    // predecessor. As a security measure, this is permited only if this is not a
15354                    // version downgrade or if the predecessor package is marked as debuggable and
15355                    // a downgrade is explicitly requested.
15356                    //
15357                    // On debuggable platform builds, downgrades are permitted even for
15358                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15359                    // not offer security guarantees and thus it's OK to disable some security
15360                    // mechanisms to make debugging/testing easier on those builds. However, even on
15361                    // debuggable builds downgrades of packages are permitted only if requested via
15362                    // installFlags. This is because we aim to keep the behavior of debuggable
15363                    // platform builds as close as possible to the behavior of non-debuggable
15364                    // platform builds.
15365                    final boolean downgradeRequested =
15366                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15367                    final boolean packageDebuggable =
15368                                (dataOwnerPkg.applicationInfo.flags
15369                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15370                    final boolean downgradePermitted =
15371                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15372                    if (!downgradePermitted) {
15373                        try {
15374                            checkDowngrade(dataOwnerPkg, pkgLite);
15375                        } catch (PackageManagerException e) {
15376                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15377                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15378                        }
15379                    }
15380                }
15381
15382                if (installedPkg != null) {
15383                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15384                        // Check for updated system application.
15385                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15386                            if (onSd) {
15387                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15388                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15389                            }
15390                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15391                        } else {
15392                            if (onSd) {
15393                                // Install flag overrides everything.
15394                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15395                            }
15396                            // If current upgrade specifies particular preference
15397                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15398                                // Application explicitly specified internal.
15399                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15400                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15401                                // App explictly prefers external. Let policy decide
15402                            } else {
15403                                // Prefer previous location
15404                                if (isExternal(installedPkg)) {
15405                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15406                                }
15407                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15408                            }
15409                        }
15410                    } else {
15411                        // Invalid install. Return error code
15412                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15413                    }
15414                }
15415            }
15416            // All the special cases have been taken care of.
15417            // Return result based on recommended install location.
15418            if (onSd) {
15419                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15420            }
15421            return pkgLite.recommendedInstallLocation;
15422        }
15423
15424        /*
15425         * Invoke remote method to get package information and install
15426         * location values. Override install location based on default
15427         * policy if needed and then create install arguments based
15428         * on the install location.
15429         */
15430        public void handleStartCopy() throws RemoteException {
15431            int ret = PackageManager.INSTALL_SUCCEEDED;
15432
15433            // If we're already staged, we've firmly committed to an install location
15434            if (origin.staged) {
15435                if (origin.file != null) {
15436                    installFlags |= PackageManager.INSTALL_INTERNAL;
15437                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15438                } else {
15439                    throw new IllegalStateException("Invalid stage location");
15440                }
15441            }
15442
15443            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15444            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15445            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15446            PackageInfoLite pkgLite = null;
15447
15448            if (onInt && onSd) {
15449                // Check if both bits are set.
15450                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15451                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15452            } else if (onSd && ephemeral) {
15453                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15454                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15455            } else {
15456                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15457                        packageAbiOverride);
15458
15459                if (DEBUG_EPHEMERAL && ephemeral) {
15460                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15461                }
15462
15463                /*
15464                 * If we have too little free space, try to free cache
15465                 * before giving up.
15466                 */
15467                if (!origin.staged && pkgLite.recommendedInstallLocation
15468                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15469                    // TODO: focus freeing disk space on the target device
15470                    final StorageManager storage = StorageManager.from(mContext);
15471                    final long lowThreshold = storage.getStorageLowBytes(
15472                            Environment.getDataDirectory());
15473
15474                    final long sizeBytes = mContainerService.calculateInstalledSize(
15475                            origin.resolvedPath, packageAbiOverride);
15476
15477                    try {
15478                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15479                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15480                                installFlags, packageAbiOverride);
15481                    } catch (InstallerException e) {
15482                        Slog.w(TAG, "Failed to free cache", e);
15483                    }
15484
15485                    /*
15486                     * The cache free must have deleted the file we
15487                     * downloaded to install.
15488                     *
15489                     * TODO: fix the "freeCache" call to not delete
15490                     *       the file we care about.
15491                     */
15492                    if (pkgLite.recommendedInstallLocation
15493                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15494                        pkgLite.recommendedInstallLocation
15495                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15496                    }
15497                }
15498            }
15499
15500            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15501                int loc = pkgLite.recommendedInstallLocation;
15502                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15503                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15504                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15505                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15506                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15507                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15508                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15509                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15510                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15511                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15512                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15513                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15514                } else {
15515                    // Override with defaults if needed.
15516                    loc = installLocationPolicy(pkgLite);
15517                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15518                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15519                    } else if (!onSd && !onInt) {
15520                        // Override install location with flags
15521                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15522                            // Set the flag to install on external media.
15523                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15524                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15525                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15526                            if (DEBUG_EPHEMERAL) {
15527                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15528                            }
15529                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15530                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15531                                    |PackageManager.INSTALL_INTERNAL);
15532                        } else {
15533                            // Make sure the flag for installing on external
15534                            // media is unset
15535                            installFlags |= PackageManager.INSTALL_INTERNAL;
15536                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15537                        }
15538                    }
15539                }
15540            }
15541
15542            final InstallArgs args = createInstallArgs(this);
15543            mArgs = args;
15544
15545            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15546                // TODO: http://b/22976637
15547                // Apps installed for "all" users use the device owner to verify the app
15548                UserHandle verifierUser = getUser();
15549                if (verifierUser == UserHandle.ALL) {
15550                    verifierUser = UserHandle.SYSTEM;
15551                }
15552
15553                /*
15554                 * Determine if we have any installed package verifiers. If we
15555                 * do, then we'll defer to them to verify the packages.
15556                 */
15557                final int requiredUid = mRequiredVerifierPackage == null ? -1
15558                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15559                                verifierUser.getIdentifier());
15560                final int installerUid =
15561                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15562                if (!origin.existing && requiredUid != -1
15563                        && isVerificationEnabled(
15564                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15565                    final Intent verification = new Intent(
15566                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15567                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15568                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15569                            PACKAGE_MIME_TYPE);
15570                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15571
15572                    // Query all live verifiers based on current user state
15573                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15574                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15575                            false /*allowDynamicSplits*/);
15576
15577                    if (DEBUG_VERIFY) {
15578                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15579                                + verification.toString() + " with " + pkgLite.verifiers.length
15580                                + " optional verifiers");
15581                    }
15582
15583                    final int verificationId = mPendingVerificationToken++;
15584
15585                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15586
15587                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15588                            installerPackageName);
15589
15590                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15591                            installFlags);
15592
15593                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15594                            pkgLite.packageName);
15595
15596                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15597                            pkgLite.versionCode);
15598
15599                    if (verificationInfo != null) {
15600                        if (verificationInfo.originatingUri != null) {
15601                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15602                                    verificationInfo.originatingUri);
15603                        }
15604                        if (verificationInfo.referrer != null) {
15605                            verification.putExtra(Intent.EXTRA_REFERRER,
15606                                    verificationInfo.referrer);
15607                        }
15608                        if (verificationInfo.originatingUid >= 0) {
15609                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15610                                    verificationInfo.originatingUid);
15611                        }
15612                        if (verificationInfo.installerUid >= 0) {
15613                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15614                                    verificationInfo.installerUid);
15615                        }
15616                    }
15617
15618                    final PackageVerificationState verificationState = new PackageVerificationState(
15619                            requiredUid, args);
15620
15621                    mPendingVerification.append(verificationId, verificationState);
15622
15623                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15624                            receivers, verificationState);
15625
15626                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15627                    final long idleDuration = getVerificationTimeout();
15628
15629                    /*
15630                     * If any sufficient verifiers were listed in the package
15631                     * manifest, attempt to ask them.
15632                     */
15633                    if (sufficientVerifiers != null) {
15634                        final int N = sufficientVerifiers.size();
15635                        if (N == 0) {
15636                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15637                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15638                        } else {
15639                            for (int i = 0; i < N; i++) {
15640                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15641                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15642                                        verifierComponent.getPackageName(), idleDuration,
15643                                        verifierUser.getIdentifier(), false, "package verifier");
15644
15645                                final Intent sufficientIntent = new Intent(verification);
15646                                sufficientIntent.setComponent(verifierComponent);
15647                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15648                            }
15649                        }
15650                    }
15651
15652                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15653                            mRequiredVerifierPackage, receivers);
15654                    if (ret == PackageManager.INSTALL_SUCCEEDED
15655                            && mRequiredVerifierPackage != null) {
15656                        Trace.asyncTraceBegin(
15657                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15658                        /*
15659                         * Send the intent to the required verification agent,
15660                         * but only start the verification timeout after the
15661                         * target BroadcastReceivers have run.
15662                         */
15663                        verification.setComponent(requiredVerifierComponent);
15664                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15665                                mRequiredVerifierPackage, idleDuration,
15666                                verifierUser.getIdentifier(), false, "package verifier");
15667                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15668                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15669                                new BroadcastReceiver() {
15670                                    @Override
15671                                    public void onReceive(Context context, Intent intent) {
15672                                        final Message msg = mHandler
15673                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15674                                        msg.arg1 = verificationId;
15675                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15676                                    }
15677                                }, null, 0, null, null);
15678
15679                        /*
15680                         * We don't want the copy to proceed until verification
15681                         * succeeds, so null out this field.
15682                         */
15683                        mArgs = null;
15684                    }
15685                } else {
15686                    /*
15687                     * No package verification is enabled, so immediately start
15688                     * the remote call to initiate copy using temporary file.
15689                     */
15690                    ret = args.copyApk(mContainerService, true);
15691                }
15692            }
15693
15694            mRet = ret;
15695        }
15696
15697        @Override
15698        void handleReturnCode() {
15699            // If mArgs is null, then MCS couldn't be reached. When it
15700            // reconnects, it will try again to install. At that point, this
15701            // will succeed.
15702            if (mArgs != null) {
15703                processPendingInstall(mArgs, mRet);
15704            }
15705        }
15706
15707        @Override
15708        void handleServiceError() {
15709            mArgs = createInstallArgs(this);
15710            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15711        }
15712    }
15713
15714    private InstallArgs createInstallArgs(InstallParams params) {
15715        if (params.move != null) {
15716            return new MoveInstallArgs(params);
15717        } else {
15718            return new FileInstallArgs(params);
15719        }
15720    }
15721
15722    /**
15723     * Create args that describe an existing installed package. Typically used
15724     * when cleaning up old installs, or used as a move source.
15725     */
15726    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15727            String resourcePath, String[] instructionSets) {
15728        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15729    }
15730
15731    static abstract class InstallArgs {
15732        /** @see InstallParams#origin */
15733        final OriginInfo origin;
15734        /** @see InstallParams#move */
15735        final MoveInfo move;
15736
15737        final IPackageInstallObserver2 observer;
15738        // Always refers to PackageManager flags only
15739        final int installFlags;
15740        final String installerPackageName;
15741        final String volumeUuid;
15742        final UserHandle user;
15743        final String abiOverride;
15744        final String[] installGrantPermissions;
15745        /** If non-null, drop an async trace when the install completes */
15746        final String traceMethod;
15747        final int traceCookie;
15748        final Certificate[][] certificates;
15749        final int installReason;
15750
15751        // The list of instruction sets supported by this app. This is currently
15752        // only used during the rmdex() phase to clean up resources. We can get rid of this
15753        // if we move dex files under the common app path.
15754        /* nullable */ String[] instructionSets;
15755
15756        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15757                int installFlags, String installerPackageName, String volumeUuid,
15758                UserHandle user, String[] instructionSets,
15759                String abiOverride, String[] installGrantPermissions,
15760                String traceMethod, int traceCookie, Certificate[][] certificates,
15761                int installReason) {
15762            this.origin = origin;
15763            this.move = move;
15764            this.installFlags = installFlags;
15765            this.observer = observer;
15766            this.installerPackageName = installerPackageName;
15767            this.volumeUuid = volumeUuid;
15768            this.user = user;
15769            this.instructionSets = instructionSets;
15770            this.abiOverride = abiOverride;
15771            this.installGrantPermissions = installGrantPermissions;
15772            this.traceMethod = traceMethod;
15773            this.traceCookie = traceCookie;
15774            this.certificates = certificates;
15775            this.installReason = installReason;
15776        }
15777
15778        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15779        abstract int doPreInstall(int status);
15780
15781        /**
15782         * Rename package into final resting place. All paths on the given
15783         * scanned package should be updated to reflect the rename.
15784         */
15785        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15786        abstract int doPostInstall(int status, int uid);
15787
15788        /** @see PackageSettingBase#codePathString */
15789        abstract String getCodePath();
15790        /** @see PackageSettingBase#resourcePathString */
15791        abstract String getResourcePath();
15792
15793        // Need installer lock especially for dex file removal.
15794        abstract void cleanUpResourcesLI();
15795        abstract boolean doPostDeleteLI(boolean delete);
15796
15797        /**
15798         * Called before the source arguments are copied. This is used mostly
15799         * for MoveParams when it needs to read the source file to put it in the
15800         * destination.
15801         */
15802        int doPreCopy() {
15803            return PackageManager.INSTALL_SUCCEEDED;
15804        }
15805
15806        /**
15807         * Called after the source arguments are copied. This is used mostly for
15808         * MoveParams when it needs to read the source file to put it in the
15809         * destination.
15810         */
15811        int doPostCopy(int uid) {
15812            return PackageManager.INSTALL_SUCCEEDED;
15813        }
15814
15815        protected boolean isFwdLocked() {
15816            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15817        }
15818
15819        protected boolean isExternalAsec() {
15820            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15821        }
15822
15823        protected boolean isEphemeral() {
15824            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15825        }
15826
15827        UserHandle getUser() {
15828            return user;
15829        }
15830    }
15831
15832    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15833        if (!allCodePaths.isEmpty()) {
15834            if (instructionSets == null) {
15835                throw new IllegalStateException("instructionSet == null");
15836            }
15837            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15838            for (String codePath : allCodePaths) {
15839                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15840                    try {
15841                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15842                    } catch (InstallerException ignored) {
15843                    }
15844                }
15845            }
15846        }
15847    }
15848
15849    /**
15850     * Logic to handle installation of non-ASEC applications, including copying
15851     * and renaming logic.
15852     */
15853    class FileInstallArgs extends InstallArgs {
15854        private File codeFile;
15855        private File resourceFile;
15856
15857        // Example topology:
15858        // /data/app/com.example/base.apk
15859        // /data/app/com.example/split_foo.apk
15860        // /data/app/com.example/lib/arm/libfoo.so
15861        // /data/app/com.example/lib/arm64/libfoo.so
15862        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15863
15864        /** New install */
15865        FileInstallArgs(InstallParams params) {
15866            super(params.origin, params.move, params.observer, params.installFlags,
15867                    params.installerPackageName, params.volumeUuid,
15868                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15869                    params.grantedRuntimePermissions,
15870                    params.traceMethod, params.traceCookie, params.certificates,
15871                    params.installReason);
15872            if (isFwdLocked()) {
15873                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15874            }
15875        }
15876
15877        /** Existing install */
15878        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15879            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15880                    null, null, null, 0, null /*certificates*/,
15881                    PackageManager.INSTALL_REASON_UNKNOWN);
15882            this.codeFile = (codePath != null) ? new File(codePath) : null;
15883            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15884        }
15885
15886        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15887            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15888            try {
15889                return doCopyApk(imcs, temp);
15890            } finally {
15891                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15892            }
15893        }
15894
15895        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15896            if (origin.staged) {
15897                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15898                codeFile = origin.file;
15899                resourceFile = origin.file;
15900                return PackageManager.INSTALL_SUCCEEDED;
15901            }
15902
15903            try {
15904                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15905                final File tempDir =
15906                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15907                codeFile = tempDir;
15908                resourceFile = tempDir;
15909            } catch (IOException e) {
15910                Slog.w(TAG, "Failed to create copy file: " + e);
15911                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15912            }
15913
15914            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15915                @Override
15916                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15917                    if (!FileUtils.isValidExtFilename(name)) {
15918                        throw new IllegalArgumentException("Invalid filename: " + name);
15919                    }
15920                    try {
15921                        final File file = new File(codeFile, name);
15922                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15923                                O_RDWR | O_CREAT, 0644);
15924                        Os.chmod(file.getAbsolutePath(), 0644);
15925                        return new ParcelFileDescriptor(fd);
15926                    } catch (ErrnoException e) {
15927                        throw new RemoteException("Failed to open: " + e.getMessage());
15928                    }
15929                }
15930            };
15931
15932            int ret = PackageManager.INSTALL_SUCCEEDED;
15933            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15934            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15935                Slog.e(TAG, "Failed to copy package");
15936                return ret;
15937            }
15938
15939            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15940            NativeLibraryHelper.Handle handle = null;
15941            try {
15942                handle = NativeLibraryHelper.Handle.create(codeFile);
15943                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15944                        abiOverride);
15945            } catch (IOException e) {
15946                Slog.e(TAG, "Copying native libraries failed", e);
15947                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15948            } finally {
15949                IoUtils.closeQuietly(handle);
15950            }
15951
15952            return ret;
15953        }
15954
15955        int doPreInstall(int status) {
15956            if (status != PackageManager.INSTALL_SUCCEEDED) {
15957                cleanUp();
15958            }
15959            return status;
15960        }
15961
15962        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15963            if (status != PackageManager.INSTALL_SUCCEEDED) {
15964                cleanUp();
15965                return false;
15966            }
15967
15968            final File targetDir = codeFile.getParentFile();
15969            final File beforeCodeFile = codeFile;
15970            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15971
15972            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15973            try {
15974                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15975            } catch (ErrnoException e) {
15976                Slog.w(TAG, "Failed to rename", e);
15977                return false;
15978            }
15979
15980            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15981                Slog.w(TAG, "Failed to restorecon");
15982                return false;
15983            }
15984
15985            // Reflect the rename internally
15986            codeFile = afterCodeFile;
15987            resourceFile = afterCodeFile;
15988
15989            // Reflect the rename in scanned details
15990            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15991            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15992                    afterCodeFile, pkg.baseCodePath));
15993            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15994                    afterCodeFile, pkg.splitCodePaths));
15995
15996            // Reflect the rename in app info
15997            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15998            pkg.setApplicationInfoCodePath(pkg.codePath);
15999            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16000            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16001            pkg.setApplicationInfoResourcePath(pkg.codePath);
16002            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16003            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16004
16005            return true;
16006        }
16007
16008        int doPostInstall(int status, int uid) {
16009            if (status != PackageManager.INSTALL_SUCCEEDED) {
16010                cleanUp();
16011            }
16012            return status;
16013        }
16014
16015        @Override
16016        String getCodePath() {
16017            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16018        }
16019
16020        @Override
16021        String getResourcePath() {
16022            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16023        }
16024
16025        private boolean cleanUp() {
16026            if (codeFile == null || !codeFile.exists()) {
16027                return false;
16028            }
16029
16030            removeCodePathLI(codeFile);
16031
16032            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16033                resourceFile.delete();
16034            }
16035
16036            return true;
16037        }
16038
16039        void cleanUpResourcesLI() {
16040            // Try enumerating all code paths before deleting
16041            List<String> allCodePaths = Collections.EMPTY_LIST;
16042            if (codeFile != null && codeFile.exists()) {
16043                try {
16044                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16045                    allCodePaths = pkg.getAllCodePaths();
16046                } catch (PackageParserException e) {
16047                    // Ignored; we tried our best
16048                }
16049            }
16050
16051            cleanUp();
16052            removeDexFiles(allCodePaths, instructionSets);
16053        }
16054
16055        boolean doPostDeleteLI(boolean delete) {
16056            // XXX err, shouldn't we respect the delete flag?
16057            cleanUpResourcesLI();
16058            return true;
16059        }
16060    }
16061
16062    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16063            PackageManagerException {
16064        if (copyRet < 0) {
16065            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16066                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16067                throw new PackageManagerException(copyRet, message);
16068            }
16069        }
16070    }
16071
16072    /**
16073     * Extract the StorageManagerService "container ID" from the full code path of an
16074     * .apk.
16075     */
16076    static String cidFromCodePath(String fullCodePath) {
16077        int eidx = fullCodePath.lastIndexOf("/");
16078        String subStr1 = fullCodePath.substring(0, eidx);
16079        int sidx = subStr1.lastIndexOf("/");
16080        return subStr1.substring(sidx+1, eidx);
16081    }
16082
16083    /**
16084     * Logic to handle movement of existing installed applications.
16085     */
16086    class MoveInstallArgs extends InstallArgs {
16087        private File codeFile;
16088        private File resourceFile;
16089
16090        /** New install */
16091        MoveInstallArgs(InstallParams params) {
16092            super(params.origin, params.move, params.observer, params.installFlags,
16093                    params.installerPackageName, params.volumeUuid,
16094                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16095                    params.grantedRuntimePermissions,
16096                    params.traceMethod, params.traceCookie, params.certificates,
16097                    params.installReason);
16098        }
16099
16100        int copyApk(IMediaContainerService imcs, boolean temp) {
16101            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16102                    + move.fromUuid + " to " + move.toUuid);
16103            synchronized (mInstaller) {
16104                try {
16105                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16106                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16107                } catch (InstallerException e) {
16108                    Slog.w(TAG, "Failed to move app", e);
16109                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16110                }
16111            }
16112
16113            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16114            resourceFile = codeFile;
16115            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16116
16117            return PackageManager.INSTALL_SUCCEEDED;
16118        }
16119
16120        int doPreInstall(int status) {
16121            if (status != PackageManager.INSTALL_SUCCEEDED) {
16122                cleanUp(move.toUuid);
16123            }
16124            return status;
16125        }
16126
16127        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16128            if (status != PackageManager.INSTALL_SUCCEEDED) {
16129                cleanUp(move.toUuid);
16130                return false;
16131            }
16132
16133            // Reflect the move in app info
16134            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16135            pkg.setApplicationInfoCodePath(pkg.codePath);
16136            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16137            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16138            pkg.setApplicationInfoResourcePath(pkg.codePath);
16139            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16140            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16141
16142            return true;
16143        }
16144
16145        int doPostInstall(int status, int uid) {
16146            if (status == PackageManager.INSTALL_SUCCEEDED) {
16147                cleanUp(move.fromUuid);
16148            } else {
16149                cleanUp(move.toUuid);
16150            }
16151            return status;
16152        }
16153
16154        @Override
16155        String getCodePath() {
16156            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16157        }
16158
16159        @Override
16160        String getResourcePath() {
16161            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16162        }
16163
16164        private boolean cleanUp(String volumeUuid) {
16165            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16166                    move.dataAppName);
16167            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16168            final int[] userIds = sUserManager.getUserIds();
16169            synchronized (mInstallLock) {
16170                // Clean up both app data and code
16171                // All package moves are frozen until finished
16172                for (int userId : userIds) {
16173                    try {
16174                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16175                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16176                    } catch (InstallerException e) {
16177                        Slog.w(TAG, String.valueOf(e));
16178                    }
16179                }
16180                removeCodePathLI(codeFile);
16181            }
16182            return true;
16183        }
16184
16185        void cleanUpResourcesLI() {
16186            throw new UnsupportedOperationException();
16187        }
16188
16189        boolean doPostDeleteLI(boolean delete) {
16190            throw new UnsupportedOperationException();
16191        }
16192    }
16193
16194    static String getAsecPackageName(String packageCid) {
16195        int idx = packageCid.lastIndexOf("-");
16196        if (idx == -1) {
16197            return packageCid;
16198        }
16199        return packageCid.substring(0, idx);
16200    }
16201
16202    // Utility method used to create code paths based on package name and available index.
16203    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16204        String idxStr = "";
16205        int idx = 1;
16206        // Fall back to default value of idx=1 if prefix is not
16207        // part of oldCodePath
16208        if (oldCodePath != null) {
16209            String subStr = oldCodePath;
16210            // Drop the suffix right away
16211            if (suffix != null && subStr.endsWith(suffix)) {
16212                subStr = subStr.substring(0, subStr.length() - suffix.length());
16213            }
16214            // If oldCodePath already contains prefix find out the
16215            // ending index to either increment or decrement.
16216            int sidx = subStr.lastIndexOf(prefix);
16217            if (sidx != -1) {
16218                subStr = subStr.substring(sidx + prefix.length());
16219                if (subStr != null) {
16220                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16221                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16222                    }
16223                    try {
16224                        idx = Integer.parseInt(subStr);
16225                        if (idx <= 1) {
16226                            idx++;
16227                        } else {
16228                            idx--;
16229                        }
16230                    } catch(NumberFormatException e) {
16231                    }
16232                }
16233            }
16234        }
16235        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16236        return prefix + idxStr;
16237    }
16238
16239    private File getNextCodePath(File targetDir, String packageName) {
16240        File result;
16241        SecureRandom random = new SecureRandom();
16242        byte[] bytes = new byte[16];
16243        do {
16244            random.nextBytes(bytes);
16245            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16246            result = new File(targetDir, packageName + "-" + suffix);
16247        } while (result.exists());
16248        return result;
16249    }
16250
16251    // Utility method that returns the relative package path with respect
16252    // to the installation directory. Like say for /data/data/com.test-1.apk
16253    // string com.test-1 is returned.
16254    static String deriveCodePathName(String codePath) {
16255        if (codePath == null) {
16256            return null;
16257        }
16258        final File codeFile = new File(codePath);
16259        final String name = codeFile.getName();
16260        if (codeFile.isDirectory()) {
16261            return name;
16262        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16263            final int lastDot = name.lastIndexOf('.');
16264            return name.substring(0, lastDot);
16265        } else {
16266            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16267            return null;
16268        }
16269    }
16270
16271    static class PackageInstalledInfo {
16272        String name;
16273        int uid;
16274        // The set of users that originally had this package installed.
16275        int[] origUsers;
16276        // The set of users that now have this package installed.
16277        int[] newUsers;
16278        PackageParser.Package pkg;
16279        int returnCode;
16280        String returnMsg;
16281        String installerPackageName;
16282        PackageRemovedInfo removedInfo;
16283        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16284
16285        public void setError(int code, String msg) {
16286            setReturnCode(code);
16287            setReturnMessage(msg);
16288            Slog.w(TAG, msg);
16289        }
16290
16291        public void setError(String msg, PackageParserException e) {
16292            setReturnCode(e.error);
16293            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16294            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16295            for (int i = 0; i < childCount; i++) {
16296                addedChildPackages.valueAt(i).setError(msg, e);
16297            }
16298            Slog.w(TAG, msg, e);
16299        }
16300
16301        public void setError(String msg, PackageManagerException e) {
16302            returnCode = e.error;
16303            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16304            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16305            for (int i = 0; i < childCount; i++) {
16306                addedChildPackages.valueAt(i).setError(msg, e);
16307            }
16308            Slog.w(TAG, msg, e);
16309        }
16310
16311        public void setReturnCode(int returnCode) {
16312            this.returnCode = returnCode;
16313            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16314            for (int i = 0; i < childCount; i++) {
16315                addedChildPackages.valueAt(i).returnCode = returnCode;
16316            }
16317        }
16318
16319        private void setReturnMessage(String returnMsg) {
16320            this.returnMsg = returnMsg;
16321            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16322            for (int i = 0; i < childCount; i++) {
16323                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16324            }
16325        }
16326
16327        // In some error cases we want to convey more info back to the observer
16328        String origPackage;
16329        String origPermission;
16330    }
16331
16332    /*
16333     * Install a non-existing package.
16334     */
16335    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16336            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16337            PackageInstalledInfo res, int installReason) {
16338        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16339
16340        // Remember this for later, in case we need to rollback this install
16341        String pkgName = pkg.packageName;
16342
16343        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16344
16345        synchronized(mPackages) {
16346            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16347            if (renamedPackage != null) {
16348                // A package with the same name is already installed, though
16349                // it has been renamed to an older name.  The package we
16350                // are trying to install should be installed as an update to
16351                // the existing one, but that has not been requested, so bail.
16352                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16353                        + " without first uninstalling package running as "
16354                        + renamedPackage);
16355                return;
16356            }
16357            if (mPackages.containsKey(pkgName)) {
16358                // Don't allow installation over an existing package with the same name.
16359                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16360                        + " without first uninstalling.");
16361                return;
16362            }
16363        }
16364
16365        try {
16366            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16367                    System.currentTimeMillis(), user);
16368
16369            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16370
16371            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16372                prepareAppDataAfterInstallLIF(newPackage);
16373
16374            } else {
16375                // Remove package from internal structures, but keep around any
16376                // data that might have already existed
16377                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16378                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16379            }
16380        } catch (PackageManagerException e) {
16381            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16382        }
16383
16384        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16385    }
16386
16387    private boolean shouldCheckUpgradeKeySetLP(PackageSettingBase oldPs, int scanFlags) {
16388        // Can't rotate keys during boot or if sharedUser.
16389        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.isSharedUser()
16390                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16391            return false;
16392        }
16393        // app is using upgradeKeySets; make sure all are valid
16394        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16395        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16396        for (int i = 0; i < upgradeKeySets.length; i++) {
16397            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16398                Slog.wtf(TAG, "Package "
16399                         + (oldPs.name != null ? oldPs.name : "<null>")
16400                         + " contains upgrade-key-set reference to unknown key-set: "
16401                         + upgradeKeySets[i]
16402                         + " reverting to signatures check.");
16403                return false;
16404            }
16405        }
16406        return true;
16407    }
16408
16409    private boolean checkUpgradeKeySetLP(PackageSettingBase oldPS, PackageParser.Package newPkg) {
16410        // Upgrade keysets are being used.  Determine if new package has a superset of the
16411        // required keys.
16412        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16413        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16414        for (int i = 0; i < upgradeKeySets.length; i++) {
16415            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16416            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16417                return true;
16418            }
16419        }
16420        return false;
16421    }
16422
16423    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16424        try (DigestInputStream digestStream =
16425                new DigestInputStream(new FileInputStream(file), digest)) {
16426            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16427        }
16428    }
16429
16430    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16431            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16432            int installReason) {
16433        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16434
16435        final PackageParser.Package oldPackage;
16436        final PackageSetting ps;
16437        final String pkgName = pkg.packageName;
16438        final int[] allUsers;
16439        final int[] installedUsers;
16440
16441        synchronized(mPackages) {
16442            oldPackage = mPackages.get(pkgName);
16443            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16444
16445            // don't allow upgrade to target a release SDK from a pre-release SDK
16446            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16447                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16448            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16449                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16450            if (oldTargetsPreRelease
16451                    && !newTargetsPreRelease
16452                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16453                Slog.w(TAG, "Can't install package targeting released sdk");
16454                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16455                return;
16456            }
16457
16458            ps = mSettings.mPackages.get(pkgName);
16459
16460            // verify signatures are valid
16461            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16462                if (!checkUpgradeKeySetLP(ps, pkg)) {
16463                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16464                            "New package not signed by keys specified by upgrade-keysets: "
16465                                    + pkgName);
16466                    return;
16467                }
16468            } else {
16469                // default to original signature matching
16470                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16471                        != PackageManager.SIGNATURE_MATCH) {
16472                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16473                            "New package has a different signature: " + pkgName);
16474                    return;
16475                }
16476            }
16477
16478            // don't allow a system upgrade unless the upgrade hash matches
16479            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16480                byte[] digestBytes = null;
16481                try {
16482                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16483                    updateDigest(digest, new File(pkg.baseCodePath));
16484                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16485                        for (String path : pkg.splitCodePaths) {
16486                            updateDigest(digest, new File(path));
16487                        }
16488                    }
16489                    digestBytes = digest.digest();
16490                } catch (NoSuchAlgorithmException | IOException e) {
16491                    res.setError(INSTALL_FAILED_INVALID_APK,
16492                            "Could not compute hash: " + pkgName);
16493                    return;
16494                }
16495                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16496                    res.setError(INSTALL_FAILED_INVALID_APK,
16497                            "New package fails restrict-update check: " + pkgName);
16498                    return;
16499                }
16500                // retain upgrade restriction
16501                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16502            }
16503
16504            // Check for shared user id changes
16505            String invalidPackageName =
16506                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16507            if (invalidPackageName != null) {
16508                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16509                        "Package " + invalidPackageName + " tried to change user "
16510                                + oldPackage.mSharedUserId);
16511                return;
16512            }
16513
16514            // In case of rollback, remember per-user/profile install state
16515            allUsers = sUserManager.getUserIds();
16516            installedUsers = ps.queryInstalledUsers(allUsers, true);
16517
16518            // don't allow an upgrade from full to ephemeral
16519            if (isInstantApp) {
16520                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16521                    for (int currentUser : allUsers) {
16522                        if (!ps.getInstantApp(currentUser)) {
16523                            // can't downgrade from full to instant
16524                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16525                                    + " for user: " + currentUser);
16526                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16527                            return;
16528                        }
16529                    }
16530                } else if (!ps.getInstantApp(user.getIdentifier())) {
16531                    // can't downgrade from full to instant
16532                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16533                            + " for user: " + user.getIdentifier());
16534                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16535                    return;
16536                }
16537            }
16538        }
16539
16540        // Update what is removed
16541        res.removedInfo = new PackageRemovedInfo(this);
16542        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16543        res.removedInfo.removedPackage = oldPackage.packageName;
16544        res.removedInfo.installerPackageName = ps.installerPackageName;
16545        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16546        res.removedInfo.isUpdate = true;
16547        res.removedInfo.origUsers = installedUsers;
16548        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16549        for (int i = 0; i < installedUsers.length; i++) {
16550            final int userId = installedUsers[i];
16551            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16552        }
16553
16554        final int childCount = (oldPackage.childPackages != null)
16555                ? oldPackage.childPackages.size() : 0;
16556        for (int i = 0; i < childCount; i++) {
16557            boolean childPackageUpdated = false;
16558            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16559            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16560            if (res.addedChildPackages != null) {
16561                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16562                if (childRes != null) {
16563                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16564                    childRes.removedInfo.removedPackage = childPkg.packageName;
16565                    if (childPs != null) {
16566                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16567                    }
16568                    childRes.removedInfo.isUpdate = true;
16569                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16570                    childPackageUpdated = true;
16571                }
16572            }
16573            if (!childPackageUpdated) {
16574                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16575                childRemovedRes.removedPackage = childPkg.packageName;
16576                if (childPs != null) {
16577                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16578                }
16579                childRemovedRes.isUpdate = false;
16580                childRemovedRes.dataRemoved = true;
16581                synchronized (mPackages) {
16582                    if (childPs != null) {
16583                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16584                    }
16585                }
16586                if (res.removedInfo.removedChildPackages == null) {
16587                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16588                }
16589                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16590            }
16591        }
16592
16593        boolean sysPkg = (isSystemApp(oldPackage));
16594        if (sysPkg) {
16595            // Set the system/privileged/oem flags as needed
16596            final boolean privileged =
16597                    (oldPackage.applicationInfo.privateFlags
16598                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16599            final boolean oem =
16600                    (oldPackage.applicationInfo.privateFlags
16601                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16602            final int systemPolicyFlags = policyFlags
16603                    | PackageParser.PARSE_IS_SYSTEM
16604                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
16605                    | (oem ? PARSE_IS_OEM : 0);
16606
16607            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16608                    user, allUsers, installerPackageName, res, installReason);
16609        } else {
16610            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16611                    user, allUsers, installerPackageName, res, installReason);
16612        }
16613    }
16614
16615    @Override
16616    public List<String> getPreviousCodePaths(String packageName) {
16617        final int callingUid = Binder.getCallingUid();
16618        final List<String> result = new ArrayList<>();
16619        if (getInstantAppPackageName(callingUid) != null) {
16620            return result;
16621        }
16622        final PackageSetting ps = mSettings.mPackages.get(packageName);
16623        if (ps != null
16624                && ps.oldCodePaths != null
16625                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16626            result.addAll(ps.oldCodePaths);
16627        }
16628        return result;
16629    }
16630
16631    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16632            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16633            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16634            int installReason) {
16635        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16636                + deletedPackage);
16637
16638        String pkgName = deletedPackage.packageName;
16639        boolean deletedPkg = true;
16640        boolean addedPkg = false;
16641        boolean updatedSettings = false;
16642        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16643        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16644                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16645
16646        final long origUpdateTime = (pkg.mExtras != null)
16647                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16648
16649        // First delete the existing package while retaining the data directory
16650        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16651                res.removedInfo, true, pkg)) {
16652            // If the existing package wasn't successfully deleted
16653            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16654            deletedPkg = false;
16655        } else {
16656            // Successfully deleted the old package; proceed with replace.
16657
16658            // If deleted package lived in a container, give users a chance to
16659            // relinquish resources before killing.
16660            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16661                if (DEBUG_INSTALL) {
16662                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16663                }
16664                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16665                final ArrayList<String> pkgList = new ArrayList<String>(1);
16666                pkgList.add(deletedPackage.applicationInfo.packageName);
16667                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16668            }
16669
16670            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16671                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16672            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16673
16674            try {
16675                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16676                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16677                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16678                        installReason);
16679
16680                // Update the in-memory copy of the previous code paths.
16681                PackageSetting ps = mSettings.mPackages.get(pkgName);
16682                if (!killApp) {
16683                    if (ps.oldCodePaths == null) {
16684                        ps.oldCodePaths = new ArraySet<>();
16685                    }
16686                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16687                    if (deletedPackage.splitCodePaths != null) {
16688                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16689                    }
16690                } else {
16691                    ps.oldCodePaths = null;
16692                }
16693                if (ps.childPackageNames != null) {
16694                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16695                        final String childPkgName = ps.childPackageNames.get(i);
16696                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16697                        childPs.oldCodePaths = ps.oldCodePaths;
16698                    }
16699                }
16700                // set instant app status, but, only if it's explicitly specified
16701                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16702                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16703                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16704                prepareAppDataAfterInstallLIF(newPackage);
16705                addedPkg = true;
16706                mDexManager.notifyPackageUpdated(newPackage.packageName,
16707                        newPackage.baseCodePath, newPackage.splitCodePaths);
16708            } catch (PackageManagerException e) {
16709                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16710            }
16711        }
16712
16713        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16714            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16715
16716            // Revert all internal state mutations and added folders for the failed install
16717            if (addedPkg) {
16718                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16719                        res.removedInfo, true, null);
16720            }
16721
16722            // Restore the old package
16723            if (deletedPkg) {
16724                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16725                File restoreFile = new File(deletedPackage.codePath);
16726                // Parse old package
16727                boolean oldExternal = isExternal(deletedPackage);
16728                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16729                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16730                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16731                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16732                try {
16733                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16734                            null);
16735                } catch (PackageManagerException e) {
16736                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16737                            + e.getMessage());
16738                    return;
16739                }
16740
16741                synchronized (mPackages) {
16742                    // Ensure the installer package name up to date
16743                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16744
16745                    // Update permissions for restored package
16746                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16747
16748                    mSettings.writeLPr();
16749                }
16750
16751                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16752            }
16753        } else {
16754            synchronized (mPackages) {
16755                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16756                if (ps != null) {
16757                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16758                    if (res.removedInfo.removedChildPackages != null) {
16759                        final int childCount = res.removedInfo.removedChildPackages.size();
16760                        // Iterate in reverse as we may modify the collection
16761                        for (int i = childCount - 1; i >= 0; i--) {
16762                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16763                            if (res.addedChildPackages.containsKey(childPackageName)) {
16764                                res.removedInfo.removedChildPackages.removeAt(i);
16765                            } else {
16766                                PackageRemovedInfo childInfo = res.removedInfo
16767                                        .removedChildPackages.valueAt(i);
16768                                childInfo.removedForAllUsers = mPackages.get(
16769                                        childInfo.removedPackage) == null;
16770                            }
16771                        }
16772                    }
16773                }
16774            }
16775        }
16776    }
16777
16778    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16779            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16780            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16781            int installReason) {
16782        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16783                + ", old=" + deletedPackage);
16784
16785        final boolean disabledSystem;
16786
16787        // Remove existing system package
16788        removePackageLI(deletedPackage, true);
16789
16790        synchronized (mPackages) {
16791            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16792        }
16793        if (!disabledSystem) {
16794            // We didn't need to disable the .apk as a current system package,
16795            // which means we are replacing another update that is already
16796            // installed.  We need to make sure to delete the older one's .apk.
16797            res.removedInfo.args = createInstallArgsForExisting(0,
16798                    deletedPackage.applicationInfo.getCodePath(),
16799                    deletedPackage.applicationInfo.getResourcePath(),
16800                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16801        } else {
16802            res.removedInfo.args = null;
16803        }
16804
16805        // Successfully disabled the old package. Now proceed with re-installation
16806        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16807                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16808        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16809
16810        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16811        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16812                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16813
16814        PackageParser.Package newPackage = null;
16815        try {
16816            // Add the package to the internal data structures
16817            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16818
16819            // Set the update and install times
16820            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16821            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16822                    System.currentTimeMillis());
16823
16824            // Update the package dynamic state if succeeded
16825            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16826                // Now that the install succeeded make sure we remove data
16827                // directories for any child package the update removed.
16828                final int deletedChildCount = (deletedPackage.childPackages != null)
16829                        ? deletedPackage.childPackages.size() : 0;
16830                final int newChildCount = (newPackage.childPackages != null)
16831                        ? newPackage.childPackages.size() : 0;
16832                for (int i = 0; i < deletedChildCount; i++) {
16833                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16834                    boolean childPackageDeleted = true;
16835                    for (int j = 0; j < newChildCount; j++) {
16836                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16837                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16838                            childPackageDeleted = false;
16839                            break;
16840                        }
16841                    }
16842                    if (childPackageDeleted) {
16843                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16844                                deletedChildPkg.packageName);
16845                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16846                            PackageRemovedInfo removedChildRes = res.removedInfo
16847                                    .removedChildPackages.get(deletedChildPkg.packageName);
16848                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16849                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16850                        }
16851                    }
16852                }
16853
16854                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16855                        installReason);
16856                prepareAppDataAfterInstallLIF(newPackage);
16857
16858                mDexManager.notifyPackageUpdated(newPackage.packageName,
16859                            newPackage.baseCodePath, newPackage.splitCodePaths);
16860            }
16861        } catch (PackageManagerException e) {
16862            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16863            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16864        }
16865
16866        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16867            // Re installation failed. Restore old information
16868            // Remove new pkg information
16869            if (newPackage != null) {
16870                removeInstalledPackageLI(newPackage, true);
16871            }
16872            // Add back the old system package
16873            try {
16874                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16875            } catch (PackageManagerException e) {
16876                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16877            }
16878
16879            synchronized (mPackages) {
16880                if (disabledSystem) {
16881                    enableSystemPackageLPw(deletedPackage);
16882                }
16883
16884                // Ensure the installer package name up to date
16885                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16886
16887                // Update permissions for restored package
16888                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16889
16890                mSettings.writeLPr();
16891            }
16892
16893            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16894                    + " after failed upgrade");
16895        }
16896    }
16897
16898    /**
16899     * Checks whether the parent or any of the child packages have a change shared
16900     * user. For a package to be a valid update the shred users of the parent and
16901     * the children should match. We may later support changing child shared users.
16902     * @param oldPkg The updated package.
16903     * @param newPkg The update package.
16904     * @return The shared user that change between the versions.
16905     */
16906    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16907            PackageParser.Package newPkg) {
16908        // Check parent shared user
16909        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16910            return newPkg.packageName;
16911        }
16912        // Check child shared users
16913        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16914        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16915        for (int i = 0; i < newChildCount; i++) {
16916            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16917            // If this child was present, did it have the same shared user?
16918            for (int j = 0; j < oldChildCount; j++) {
16919                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16920                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16921                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16922                    return newChildPkg.packageName;
16923                }
16924            }
16925        }
16926        return null;
16927    }
16928
16929    private void removeNativeBinariesLI(PackageSetting ps) {
16930        // Remove the lib path for the parent package
16931        if (ps != null) {
16932            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16933            // Remove the lib path for the child packages
16934            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16935            for (int i = 0; i < childCount; i++) {
16936                PackageSetting childPs = null;
16937                synchronized (mPackages) {
16938                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16939                }
16940                if (childPs != null) {
16941                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16942                            .legacyNativeLibraryPathString);
16943                }
16944            }
16945        }
16946    }
16947
16948    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16949        // Enable the parent package
16950        mSettings.enableSystemPackageLPw(pkg.packageName);
16951        // Enable the child packages
16952        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16953        for (int i = 0; i < childCount; i++) {
16954            PackageParser.Package childPkg = pkg.childPackages.get(i);
16955            mSettings.enableSystemPackageLPw(childPkg.packageName);
16956        }
16957    }
16958
16959    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16960            PackageParser.Package newPkg) {
16961        // Disable the parent package (parent always replaced)
16962        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16963        // Disable the child packages
16964        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16965        for (int i = 0; i < childCount; i++) {
16966            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16967            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16968            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16969        }
16970        return disabled;
16971    }
16972
16973    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16974            String installerPackageName) {
16975        // Enable the parent package
16976        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16977        // Enable the child packages
16978        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16979        for (int i = 0; i < childCount; i++) {
16980            PackageParser.Package childPkg = pkg.childPackages.get(i);
16981            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16982        }
16983    }
16984
16985    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16986            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16987        // Update the parent package setting
16988        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16989                res, user, installReason);
16990        // Update the child packages setting
16991        final int childCount = (newPackage.childPackages != null)
16992                ? newPackage.childPackages.size() : 0;
16993        for (int i = 0; i < childCount; i++) {
16994            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16995            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16996            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16997                    childRes.origUsers, childRes, user, installReason);
16998        }
16999    }
17000
17001    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17002            String installerPackageName, int[] allUsers, int[] installedForUsers,
17003            PackageInstalledInfo res, UserHandle user, int installReason) {
17004        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17005
17006        String pkgName = newPackage.packageName;
17007        synchronized (mPackages) {
17008            //write settings. the installStatus will be incomplete at this stage.
17009            //note that the new package setting would have already been
17010            //added to mPackages. It hasn't been persisted yet.
17011            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17012            // TODO: Remove this write? It's also written at the end of this method
17013            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17014            mSettings.writeLPr();
17015            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17016        }
17017
17018        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17019        synchronized (mPackages) {
17020            updatePermissionsLPw(newPackage.packageName, newPackage,
17021                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17022                            ? UPDATE_PERMISSIONS_ALL : 0));
17023            // For system-bundled packages, we assume that installing an upgraded version
17024            // of the package implies that the user actually wants to run that new code,
17025            // so we enable the package.
17026            PackageSetting ps = mSettings.mPackages.get(pkgName);
17027            final int userId = user.getIdentifier();
17028            if (ps != null) {
17029                if (isSystemApp(newPackage)) {
17030                    if (DEBUG_INSTALL) {
17031                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17032                    }
17033                    // Enable system package for requested users
17034                    if (res.origUsers != null) {
17035                        for (int origUserId : res.origUsers) {
17036                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17037                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17038                                        origUserId, installerPackageName);
17039                            }
17040                        }
17041                    }
17042                    // Also convey the prior install/uninstall state
17043                    if (allUsers != null && installedForUsers != null) {
17044                        for (int currentUserId : allUsers) {
17045                            final boolean installed = ArrayUtils.contains(
17046                                    installedForUsers, currentUserId);
17047                            if (DEBUG_INSTALL) {
17048                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17049                            }
17050                            ps.setInstalled(installed, currentUserId);
17051                        }
17052                        // these install state changes will be persisted in the
17053                        // upcoming call to mSettings.writeLPr().
17054                    }
17055                }
17056                // It's implied that when a user requests installation, they want the app to be
17057                // installed and enabled.
17058                if (userId != UserHandle.USER_ALL) {
17059                    ps.setInstalled(true, userId);
17060                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17061                }
17062
17063                // When replacing an existing package, preserve the original install reason for all
17064                // users that had the package installed before.
17065                final Set<Integer> previousUserIds = new ArraySet<>();
17066                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17067                    final int installReasonCount = res.removedInfo.installReasons.size();
17068                    for (int i = 0; i < installReasonCount; i++) {
17069                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17070                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17071                        ps.setInstallReason(previousInstallReason, previousUserId);
17072                        previousUserIds.add(previousUserId);
17073                    }
17074                }
17075
17076                // Set install reason for users that are having the package newly installed.
17077                if (userId == UserHandle.USER_ALL) {
17078                    for (int currentUserId : sUserManager.getUserIds()) {
17079                        if (!previousUserIds.contains(currentUserId)) {
17080                            ps.setInstallReason(installReason, currentUserId);
17081                        }
17082                    }
17083                } else if (!previousUserIds.contains(userId)) {
17084                    ps.setInstallReason(installReason, userId);
17085                }
17086                mSettings.writeKernelMappingLPr(ps);
17087            }
17088            res.name = pkgName;
17089            res.uid = newPackage.applicationInfo.uid;
17090            res.pkg = newPackage;
17091            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17092            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17093            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17094            //to update install status
17095            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17096            mSettings.writeLPr();
17097            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17098        }
17099
17100        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17101    }
17102
17103    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17104        try {
17105            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17106            installPackageLI(args, res);
17107        } finally {
17108            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17109        }
17110    }
17111
17112    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17113        final int installFlags = args.installFlags;
17114        final String installerPackageName = args.installerPackageName;
17115        final String volumeUuid = args.volumeUuid;
17116        final File tmpPackageFile = new File(args.getCodePath());
17117        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17118        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17119                || (args.volumeUuid != null));
17120        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17121        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17122        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17123        final boolean virtualPreload =
17124                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
17125        boolean replace = false;
17126        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17127        if (args.move != null) {
17128            // moving a complete application; perform an initial scan on the new install location
17129            scanFlags |= SCAN_INITIAL;
17130        }
17131        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17132            scanFlags |= SCAN_DONT_KILL_APP;
17133        }
17134        if (instantApp) {
17135            scanFlags |= SCAN_AS_INSTANT_APP;
17136        }
17137        if (fullApp) {
17138            scanFlags |= SCAN_AS_FULL_APP;
17139        }
17140        if (virtualPreload) {
17141            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
17142        }
17143
17144        // Result object to be returned
17145        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17146        res.installerPackageName = installerPackageName;
17147
17148        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17149
17150        // Sanity check
17151        if (instantApp && (forwardLocked || onExternal)) {
17152            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17153                    + " external=" + onExternal);
17154            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17155            return;
17156        }
17157
17158        // Retrieve PackageSettings and parse package
17159        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17160                | PackageParser.PARSE_ENFORCE_CODE
17161                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17162                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17163                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17164                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17165        PackageParser pp = new PackageParser();
17166        pp.setSeparateProcesses(mSeparateProcesses);
17167        pp.setDisplayMetrics(mMetrics);
17168        pp.setCallback(mPackageParserCallback);
17169
17170        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17171        final PackageParser.Package pkg;
17172        try {
17173            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17174        } catch (PackageParserException e) {
17175            res.setError("Failed parse during installPackageLI", e);
17176            return;
17177        } finally {
17178            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17179        }
17180
17181        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17182        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17183            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17184            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17185                    "Instant app package must target O");
17186            return;
17187        }
17188        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17189            Slog.w(TAG, "Instant app package " + pkg.packageName
17190                    + " does not target targetSandboxVersion 2");
17191            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17192                    "Instant app package must use targetSanboxVersion 2");
17193            return;
17194        }
17195
17196        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17197            // Static shared libraries have synthetic package names
17198            renameStaticSharedLibraryPackage(pkg);
17199
17200            // No static shared libs on external storage
17201            if (onExternal) {
17202                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17203                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17204                        "Packages declaring static-shared libs cannot be updated");
17205                return;
17206            }
17207        }
17208
17209        // If we are installing a clustered package add results for the children
17210        if (pkg.childPackages != null) {
17211            synchronized (mPackages) {
17212                final int childCount = pkg.childPackages.size();
17213                for (int i = 0; i < childCount; i++) {
17214                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17215                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17216                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17217                    childRes.pkg = childPkg;
17218                    childRes.name = childPkg.packageName;
17219                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17220                    if (childPs != null) {
17221                        childRes.origUsers = childPs.queryInstalledUsers(
17222                                sUserManager.getUserIds(), true);
17223                    }
17224                    if ((mPackages.containsKey(childPkg.packageName))) {
17225                        childRes.removedInfo = new PackageRemovedInfo(this);
17226                        childRes.removedInfo.removedPackage = childPkg.packageName;
17227                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17228                    }
17229                    if (res.addedChildPackages == null) {
17230                        res.addedChildPackages = new ArrayMap<>();
17231                    }
17232                    res.addedChildPackages.put(childPkg.packageName, childRes);
17233                }
17234            }
17235        }
17236
17237        // If package doesn't declare API override, mark that we have an install
17238        // time CPU ABI override.
17239        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17240            pkg.cpuAbiOverride = args.abiOverride;
17241        }
17242
17243        String pkgName = res.name = pkg.packageName;
17244        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17245            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17246                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17247                return;
17248            }
17249        }
17250
17251        try {
17252            // either use what we've been given or parse directly from the APK
17253            if (args.certificates != null) {
17254                try {
17255                    PackageParser.populateCertificates(pkg, args.certificates);
17256                } catch (PackageParserException e) {
17257                    // there was something wrong with the certificates we were given;
17258                    // try to pull them from the APK
17259                    PackageParser.collectCertificates(pkg, parseFlags);
17260                }
17261            } else {
17262                PackageParser.collectCertificates(pkg, parseFlags);
17263            }
17264        } catch (PackageParserException e) {
17265            res.setError("Failed collect during installPackageLI", e);
17266            return;
17267        }
17268
17269        // Get rid of all references to package scan path via parser.
17270        pp = null;
17271        String oldCodePath = null;
17272        boolean systemApp = false;
17273        synchronized (mPackages) {
17274            // Check if installing already existing package
17275            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17276                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17277                if (pkg.mOriginalPackages != null
17278                        && pkg.mOriginalPackages.contains(oldName)
17279                        && mPackages.containsKey(oldName)) {
17280                    // This package is derived from an original package,
17281                    // and this device has been updating from that original
17282                    // name.  We must continue using the original name, so
17283                    // rename the new package here.
17284                    pkg.setPackageName(oldName);
17285                    pkgName = pkg.packageName;
17286                    replace = true;
17287                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17288                            + oldName + " pkgName=" + pkgName);
17289                } else if (mPackages.containsKey(pkgName)) {
17290                    // This package, under its official name, already exists
17291                    // on the device; we should replace it.
17292                    replace = true;
17293                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17294                }
17295
17296                // Child packages are installed through the parent package
17297                if (pkg.parentPackage != null) {
17298                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17299                            "Package " + pkg.packageName + " is child of package "
17300                                    + pkg.parentPackage.parentPackage + ". Child packages "
17301                                    + "can be updated only through the parent package.");
17302                    return;
17303                }
17304
17305                if (replace) {
17306                    // Prevent apps opting out from runtime permissions
17307                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17308                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17309                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17310                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17311                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17312                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17313                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17314                                        + " doesn't support runtime permissions but the old"
17315                                        + " target SDK " + oldTargetSdk + " does.");
17316                        return;
17317                    }
17318                    // Prevent apps from downgrading their targetSandbox.
17319                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17320                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17321                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17322                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17323                                "Package " + pkg.packageName + " new target sandbox "
17324                                + newTargetSandbox + " is incompatible with the previous value of"
17325                                + oldTargetSandbox + ".");
17326                        return;
17327                    }
17328
17329                    // Prevent installing of child packages
17330                    if (oldPackage.parentPackage != null) {
17331                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17332                                "Package " + pkg.packageName + " is child of package "
17333                                        + oldPackage.parentPackage + ". Child packages "
17334                                        + "can be updated only through the parent package.");
17335                        return;
17336                    }
17337                }
17338            }
17339
17340            PackageSetting ps = mSettings.mPackages.get(pkgName);
17341            if (ps != null) {
17342                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17343
17344                // Static shared libs have same package with different versions where
17345                // we internally use a synthetic package name to allow multiple versions
17346                // of the same package, therefore we need to compare signatures against
17347                // the package setting for the latest library version.
17348                PackageSetting signatureCheckPs = ps;
17349                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17350                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17351                    if (libraryEntry != null) {
17352                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17353                    }
17354                }
17355
17356                // Quick sanity check that we're signed correctly if updating;
17357                // we'll check this again later when scanning, but we want to
17358                // bail early here before tripping over redefined permissions.
17359                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17360                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17361                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17362                                + pkg.packageName + " upgrade keys do not match the "
17363                                + "previously installed version");
17364                        return;
17365                    }
17366                } else {
17367                    try {
17368                        verifySignaturesLP(signatureCheckPs, pkg);
17369                    } catch (PackageManagerException e) {
17370                        res.setError(e.error, e.getMessage());
17371                        return;
17372                    }
17373                }
17374
17375                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17376                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17377                    systemApp = (ps.pkg.applicationInfo.flags &
17378                            ApplicationInfo.FLAG_SYSTEM) != 0;
17379                }
17380                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17381            }
17382
17383            int N = pkg.permissions.size();
17384            for (int i = N-1; i >= 0; i--) {
17385                final PackageParser.Permission perm = pkg.permissions.get(i);
17386                final BasePermission bp =
17387                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17388
17389                // Don't allow anyone but the system to define ephemeral permissions.
17390                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17391                        && !systemApp) {
17392                    Slog.w(TAG, "Non-System package " + pkg.packageName
17393                            + " attempting to delcare ephemeral permission "
17394                            + perm.info.name + "; Removing ephemeral.");
17395                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17396                }
17397
17398                // Check whether the newly-scanned package wants to define an already-defined perm
17399                if (bp != null) {
17400                    // If the defining package is signed with our cert, it's okay.  This
17401                    // also includes the "updating the same package" case, of course.
17402                    // "updating same package" could also involve key-rotation.
17403                    final boolean sigsOk;
17404                    final String sourcePackageName = bp.getSourcePackageName();
17405                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17406                    if (sourcePackageName.equals(pkg.packageName)
17407                            && (shouldCheckUpgradeKeySetLP(sourcePackageSetting,
17408                                    scanFlags))) {
17409                        sigsOk = checkUpgradeKeySetLP(sourcePackageSetting, pkg);
17410                    } else {
17411                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
17412                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17413                    }
17414                    if (!sigsOk) {
17415                        // If the owning package is the system itself, we log but allow
17416                        // install to proceed; we fail the install on all other permission
17417                        // redefinitions.
17418                        if (!sourcePackageName.equals("android")) {
17419                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17420                                    + pkg.packageName + " attempting to redeclare permission "
17421                                    + perm.info.name + " already owned by " + sourcePackageName);
17422                            res.origPermission = perm.info.name;
17423                            res.origPackage = sourcePackageName;
17424                            return;
17425                        } else {
17426                            Slog.w(TAG, "Package " + pkg.packageName
17427                                    + " attempting to redeclare system permission "
17428                                    + perm.info.name + "; ignoring new declaration");
17429                            pkg.permissions.remove(i);
17430                        }
17431                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17432                        // Prevent apps to change protection level to dangerous from any other
17433                        // type as this would allow a privilege escalation where an app adds a
17434                        // normal/signature permission in other app's group and later redefines
17435                        // it as dangerous leading to the group auto-grant.
17436                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17437                                == PermissionInfo.PROTECTION_DANGEROUS) {
17438                            if (bp != null && !bp.isRuntime()) {
17439                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17440                                        + "non-runtime permission " + perm.info.name
17441                                        + " to runtime; keeping old protection level");
17442                                perm.info.protectionLevel = bp.getProtectionLevel();
17443                            }
17444                        }
17445                    }
17446                }
17447            }
17448        }
17449
17450        if (systemApp) {
17451            if (onExternal) {
17452                // Abort update; system app can't be replaced with app on sdcard
17453                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17454                        "Cannot install updates to system apps on sdcard");
17455                return;
17456            } else if (instantApp) {
17457                // Abort update; system app can't be replaced with an instant app
17458                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17459                        "Cannot update a system app with an instant app");
17460                return;
17461            }
17462        }
17463
17464        if (args.move != null) {
17465            // We did an in-place move, so dex is ready to roll
17466            scanFlags |= SCAN_NO_DEX;
17467            scanFlags |= SCAN_MOVE;
17468
17469            synchronized (mPackages) {
17470                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17471                if (ps == null) {
17472                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17473                            "Missing settings for moved package " + pkgName);
17474                }
17475
17476                // We moved the entire application as-is, so bring over the
17477                // previously derived ABI information.
17478                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17479                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17480            }
17481
17482        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17483            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17484            scanFlags |= SCAN_NO_DEX;
17485
17486            try {
17487                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17488                    args.abiOverride : pkg.cpuAbiOverride);
17489                final boolean extractNativeLibs = !pkg.isLibrary();
17490                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17491                        extractNativeLibs, mAppLib32InstallDir);
17492            } catch (PackageManagerException pme) {
17493                Slog.e(TAG, "Error deriving application ABI", pme);
17494                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17495                return;
17496            }
17497
17498            // Shared libraries for the package need to be updated.
17499            synchronized (mPackages) {
17500                try {
17501                    updateSharedLibrariesLPr(pkg, null);
17502                } catch (PackageManagerException e) {
17503                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17504                }
17505            }
17506        }
17507
17508        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17509            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17510            return;
17511        }
17512
17513        // Verify if we need to dexopt the app.
17514        //
17515        // NOTE: it is *important* to call dexopt after doRename which will sync the
17516        // package data from PackageParser.Package and its corresponding ApplicationInfo.
17517        //
17518        // We only need to dexopt if the package meets ALL of the following conditions:
17519        //   1) it is not forward locked.
17520        //   2) it is not on on an external ASEC container.
17521        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17522        //
17523        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17524        // complete, so we skip this step during installation. Instead, we'll take extra time
17525        // the first time the instant app starts. It's preferred to do it this way to provide
17526        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17527        // middle of running an instant app. The default behaviour can be overridden
17528        // via gservices.
17529        final boolean performDexopt = !forwardLocked
17530            && !pkg.applicationInfo.isExternalAsec()
17531            && (!instantApp || Global.getInt(mContext.getContentResolver(),
17532                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17533
17534        if (performDexopt) {
17535            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17536            // Do not run PackageDexOptimizer through the local performDexOpt
17537            // method because `pkg` may not be in `mPackages` yet.
17538            //
17539            // Also, don't fail application installs if the dexopt step fails.
17540            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17541                REASON_INSTALL,
17542                DexoptOptions.DEXOPT_BOOT_COMPLETE);
17543            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17544                null /* instructionSets */,
17545                getOrCreateCompilerPackageStats(pkg),
17546                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17547                dexoptOptions);
17548            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17549        }
17550
17551        // Notify BackgroundDexOptService that the package has been changed.
17552        // If this is an update of a package which used to fail to compile,
17553        // BackgroundDexOptService will remove it from its blacklist.
17554        // TODO: Layering violation
17555        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17556
17557        if (!instantApp) {
17558            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17559        } else {
17560            if (DEBUG_DOMAIN_VERIFICATION) {
17561                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17562            }
17563        }
17564
17565        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17566                "installPackageLI")) {
17567            if (replace) {
17568                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17569                    // Static libs have a synthetic package name containing the version
17570                    // and cannot be updated as an update would get a new package name,
17571                    // unless this is the exact same version code which is useful for
17572                    // development.
17573                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17574                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17575                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17576                                + "static-shared libs cannot be updated");
17577                        return;
17578                    }
17579                }
17580                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17581                        installerPackageName, res, args.installReason);
17582            } else {
17583                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17584                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17585            }
17586        }
17587
17588        synchronized (mPackages) {
17589            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17590            if (ps != null) {
17591                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17592                ps.setUpdateAvailable(false /*updateAvailable*/);
17593            }
17594
17595            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17596            for (int i = 0; i < childCount; i++) {
17597                PackageParser.Package childPkg = pkg.childPackages.get(i);
17598                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17599                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17600                if (childPs != null) {
17601                    childRes.newUsers = childPs.queryInstalledUsers(
17602                            sUserManager.getUserIds(), true);
17603                }
17604            }
17605
17606            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17607                updateSequenceNumberLP(ps, res.newUsers);
17608                updateInstantAppInstallerLocked(pkgName);
17609            }
17610        }
17611    }
17612
17613    private void startIntentFilterVerifications(int userId, boolean replacing,
17614            PackageParser.Package pkg) {
17615        if (mIntentFilterVerifierComponent == null) {
17616            Slog.w(TAG, "No IntentFilter verification will not be done as "
17617                    + "there is no IntentFilterVerifier available!");
17618            return;
17619        }
17620
17621        final int verifierUid = getPackageUid(
17622                mIntentFilterVerifierComponent.getPackageName(),
17623                MATCH_DEBUG_TRIAGED_MISSING,
17624                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17625
17626        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17627        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17628        mHandler.sendMessage(msg);
17629
17630        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17631        for (int i = 0; i < childCount; i++) {
17632            PackageParser.Package childPkg = pkg.childPackages.get(i);
17633            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17634            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17635            mHandler.sendMessage(msg);
17636        }
17637    }
17638
17639    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17640            PackageParser.Package pkg) {
17641        int size = pkg.activities.size();
17642        if (size == 0) {
17643            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17644                    "No activity, so no need to verify any IntentFilter!");
17645            return;
17646        }
17647
17648        final boolean hasDomainURLs = hasDomainURLs(pkg);
17649        if (!hasDomainURLs) {
17650            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17651                    "No domain URLs, so no need to verify any IntentFilter!");
17652            return;
17653        }
17654
17655        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17656                + " if any IntentFilter from the " + size
17657                + " Activities needs verification ...");
17658
17659        int count = 0;
17660        final String packageName = pkg.packageName;
17661
17662        synchronized (mPackages) {
17663            // If this is a new install and we see that we've already run verification for this
17664            // package, we have nothing to do: it means the state was restored from backup.
17665            if (!replacing) {
17666                IntentFilterVerificationInfo ivi =
17667                        mSettings.getIntentFilterVerificationLPr(packageName);
17668                if (ivi != null) {
17669                    if (DEBUG_DOMAIN_VERIFICATION) {
17670                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17671                                + ivi.getStatusString());
17672                    }
17673                    return;
17674                }
17675            }
17676
17677            // If any filters need to be verified, then all need to be.
17678            boolean needToVerify = false;
17679            for (PackageParser.Activity a : pkg.activities) {
17680                for (ActivityIntentInfo filter : a.intents) {
17681                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17682                        if (DEBUG_DOMAIN_VERIFICATION) {
17683                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17684                        }
17685                        needToVerify = true;
17686                        break;
17687                    }
17688                }
17689            }
17690
17691            if (needToVerify) {
17692                final int verificationId = mIntentFilterVerificationToken++;
17693                for (PackageParser.Activity a : pkg.activities) {
17694                    for (ActivityIntentInfo filter : a.intents) {
17695                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17696                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17697                                    "Verification needed for IntentFilter:" + filter.toString());
17698                            mIntentFilterVerifier.addOneIntentFilterVerification(
17699                                    verifierUid, userId, verificationId, filter, packageName);
17700                            count++;
17701                        }
17702                    }
17703                }
17704            }
17705        }
17706
17707        if (count > 0) {
17708            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17709                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17710                    +  " for userId:" + userId);
17711            mIntentFilterVerifier.startVerifications(userId);
17712        } else {
17713            if (DEBUG_DOMAIN_VERIFICATION) {
17714                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17715            }
17716        }
17717    }
17718
17719    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17720        final ComponentName cn  = filter.activity.getComponentName();
17721        final String packageName = cn.getPackageName();
17722
17723        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17724                packageName);
17725        if (ivi == null) {
17726            return true;
17727        }
17728        int status = ivi.getStatus();
17729        switch (status) {
17730            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17731            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17732                return true;
17733
17734            default:
17735                // Nothing to do
17736                return false;
17737        }
17738    }
17739
17740    private static boolean isMultiArch(ApplicationInfo info) {
17741        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17742    }
17743
17744    private static boolean isExternal(PackageParser.Package pkg) {
17745        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17746    }
17747
17748    private static boolean isExternal(PackageSetting ps) {
17749        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17750    }
17751
17752    private static boolean isSystemApp(PackageParser.Package pkg) {
17753        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17754    }
17755
17756    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17757        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17758    }
17759
17760    private static boolean isOemApp(PackageParser.Package pkg) {
17761        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17762    }
17763
17764    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17765        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17766    }
17767
17768    private static boolean isSystemApp(PackageSetting ps) {
17769        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17770    }
17771
17772    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17773        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17774    }
17775
17776    private int packageFlagsToInstallFlags(PackageSetting ps) {
17777        int installFlags = 0;
17778        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17779            // This existing package was an external ASEC install when we have
17780            // the external flag without a UUID
17781            installFlags |= PackageManager.INSTALL_EXTERNAL;
17782        }
17783        if (ps.isForwardLocked()) {
17784            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17785        }
17786        return installFlags;
17787    }
17788
17789    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17790        if (isExternal(pkg)) {
17791            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17792                return StorageManager.UUID_PRIMARY_PHYSICAL;
17793            } else {
17794                return pkg.volumeUuid;
17795            }
17796        } else {
17797            return StorageManager.UUID_PRIVATE_INTERNAL;
17798        }
17799    }
17800
17801    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17802        if (isExternal(pkg)) {
17803            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17804                return mSettings.getExternalVersion();
17805            } else {
17806                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17807            }
17808        } else {
17809            return mSettings.getInternalVersion();
17810        }
17811    }
17812
17813    private void deleteTempPackageFiles() {
17814        final FilenameFilter filter = new FilenameFilter() {
17815            public boolean accept(File dir, String name) {
17816                return name.startsWith("vmdl") && name.endsWith(".tmp");
17817            }
17818        };
17819        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17820            file.delete();
17821        }
17822    }
17823
17824    @Override
17825    public void deletePackageAsUser(String packageName, int versionCode,
17826            IPackageDeleteObserver observer, int userId, int flags) {
17827        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17828                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17829    }
17830
17831    @Override
17832    public void deletePackageVersioned(VersionedPackage versionedPackage,
17833            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17834        final int callingUid = Binder.getCallingUid();
17835        mContext.enforceCallingOrSelfPermission(
17836                android.Manifest.permission.DELETE_PACKAGES, null);
17837        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17838        Preconditions.checkNotNull(versionedPackage);
17839        Preconditions.checkNotNull(observer);
17840        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17841                PackageManager.VERSION_CODE_HIGHEST,
17842                Integer.MAX_VALUE, "versionCode must be >= -1");
17843
17844        final String packageName = versionedPackage.getPackageName();
17845        final int versionCode = versionedPackage.getVersionCode();
17846        final String internalPackageName;
17847        synchronized (mPackages) {
17848            // Normalize package name to handle renamed packages and static libs
17849            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17850                    versionedPackage.getVersionCode());
17851        }
17852
17853        final int uid = Binder.getCallingUid();
17854        if (!isOrphaned(internalPackageName)
17855                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17856            try {
17857                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17858                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17859                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17860                observer.onUserActionRequired(intent);
17861            } catch (RemoteException re) {
17862            }
17863            return;
17864        }
17865        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17866        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17867        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17868            mContext.enforceCallingOrSelfPermission(
17869                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17870                    "deletePackage for user " + userId);
17871        }
17872
17873        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17874            try {
17875                observer.onPackageDeleted(packageName,
17876                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17877            } catch (RemoteException re) {
17878            }
17879            return;
17880        }
17881
17882        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17883            try {
17884                observer.onPackageDeleted(packageName,
17885                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17886            } catch (RemoteException re) {
17887            }
17888            return;
17889        }
17890
17891        if (DEBUG_REMOVE) {
17892            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17893                    + " deleteAllUsers: " + deleteAllUsers + " version="
17894                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17895                    ? "VERSION_CODE_HIGHEST" : versionCode));
17896        }
17897        // Queue up an async operation since the package deletion may take a little while.
17898        mHandler.post(new Runnable() {
17899            public void run() {
17900                mHandler.removeCallbacks(this);
17901                int returnCode;
17902                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17903                boolean doDeletePackage = true;
17904                if (ps != null) {
17905                    final boolean targetIsInstantApp =
17906                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17907                    doDeletePackage = !targetIsInstantApp
17908                            || canViewInstantApps;
17909                }
17910                if (doDeletePackage) {
17911                    if (!deleteAllUsers) {
17912                        returnCode = deletePackageX(internalPackageName, versionCode,
17913                                userId, deleteFlags);
17914                    } else {
17915                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17916                                internalPackageName, users);
17917                        // If nobody is blocking uninstall, proceed with delete for all users
17918                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17919                            returnCode = deletePackageX(internalPackageName, versionCode,
17920                                    userId, deleteFlags);
17921                        } else {
17922                            // Otherwise uninstall individually for users with blockUninstalls=false
17923                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17924                            for (int userId : users) {
17925                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17926                                    returnCode = deletePackageX(internalPackageName, versionCode,
17927                                            userId, userFlags);
17928                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17929                                        Slog.w(TAG, "Package delete failed for user " + userId
17930                                                + ", returnCode " + returnCode);
17931                                    }
17932                                }
17933                            }
17934                            // The app has only been marked uninstalled for certain users.
17935                            // We still need to report that delete was blocked
17936                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17937                        }
17938                    }
17939                } else {
17940                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17941                }
17942                try {
17943                    observer.onPackageDeleted(packageName, returnCode, null);
17944                } catch (RemoteException e) {
17945                    Log.i(TAG, "Observer no longer exists.");
17946                } //end catch
17947            } //end run
17948        });
17949    }
17950
17951    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17952        if (pkg.staticSharedLibName != null) {
17953            return pkg.manifestPackageName;
17954        }
17955        return pkg.packageName;
17956    }
17957
17958    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17959        // Handle renamed packages
17960        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17961        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17962
17963        // Is this a static library?
17964        SparseArray<SharedLibraryEntry> versionedLib =
17965                mStaticLibsByDeclaringPackage.get(packageName);
17966        if (versionedLib == null || versionedLib.size() <= 0) {
17967            return packageName;
17968        }
17969
17970        // Figure out which lib versions the caller can see
17971        SparseIntArray versionsCallerCanSee = null;
17972        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17973        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17974                && callingAppId != Process.ROOT_UID) {
17975            versionsCallerCanSee = new SparseIntArray();
17976            String libName = versionedLib.valueAt(0).info.getName();
17977            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17978            if (uidPackages != null) {
17979                for (String uidPackage : uidPackages) {
17980                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17981                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17982                    if (libIdx >= 0) {
17983                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17984                        versionsCallerCanSee.append(libVersion, libVersion);
17985                    }
17986                }
17987            }
17988        }
17989
17990        // Caller can see nothing - done
17991        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17992            return packageName;
17993        }
17994
17995        // Find the version the caller can see and the app version code
17996        SharedLibraryEntry highestVersion = null;
17997        final int versionCount = versionedLib.size();
17998        for (int i = 0; i < versionCount; i++) {
17999            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18000            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18001                    libEntry.info.getVersion()) < 0) {
18002                continue;
18003            }
18004            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18005            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18006                if (libVersionCode == versionCode) {
18007                    return libEntry.apk;
18008                }
18009            } else if (highestVersion == null) {
18010                highestVersion = libEntry;
18011            } else if (libVersionCode  > highestVersion.info
18012                    .getDeclaringPackage().getVersionCode()) {
18013                highestVersion = libEntry;
18014            }
18015        }
18016
18017        if (highestVersion != null) {
18018            return highestVersion.apk;
18019        }
18020
18021        return packageName;
18022    }
18023
18024    boolean isCallerVerifier(int callingUid) {
18025        final int callingUserId = UserHandle.getUserId(callingUid);
18026        return mRequiredVerifierPackage != null &&
18027                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
18028    }
18029
18030    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18031        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18032              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18033            return true;
18034        }
18035        final int callingUserId = UserHandle.getUserId(callingUid);
18036        // If the caller installed the pkgName, then allow it to silently uninstall.
18037        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18038            return true;
18039        }
18040
18041        // Allow package verifier to silently uninstall.
18042        if (mRequiredVerifierPackage != null &&
18043                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18044            return true;
18045        }
18046
18047        // Allow package uninstaller to silently uninstall.
18048        if (mRequiredUninstallerPackage != null &&
18049                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18050            return true;
18051        }
18052
18053        // Allow storage manager to silently uninstall.
18054        if (mStorageManagerPackage != null &&
18055                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18056            return true;
18057        }
18058
18059        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18060        // uninstall for device owner provisioning.
18061        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18062                == PERMISSION_GRANTED) {
18063            return true;
18064        }
18065
18066        return false;
18067    }
18068
18069    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18070        int[] result = EMPTY_INT_ARRAY;
18071        for (int userId : userIds) {
18072            if (getBlockUninstallForUser(packageName, userId)) {
18073                result = ArrayUtils.appendInt(result, userId);
18074            }
18075        }
18076        return result;
18077    }
18078
18079    @Override
18080    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18081        final int callingUid = Binder.getCallingUid();
18082        if (getInstantAppPackageName(callingUid) != null
18083                && !isCallerSameApp(packageName, callingUid)) {
18084            return false;
18085        }
18086        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18087    }
18088
18089    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18090        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18091                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18092        try {
18093            if (dpm != null) {
18094                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18095                        /* callingUserOnly =*/ false);
18096                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18097                        : deviceOwnerComponentName.getPackageName();
18098                // Does the package contains the device owner?
18099                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18100                // this check is probably not needed, since DO should be registered as a device
18101                // admin on some user too. (Original bug for this: b/17657954)
18102                if (packageName.equals(deviceOwnerPackageName)) {
18103                    return true;
18104                }
18105                // Does it contain a device admin for any user?
18106                int[] users;
18107                if (userId == UserHandle.USER_ALL) {
18108                    users = sUserManager.getUserIds();
18109                } else {
18110                    users = new int[]{userId};
18111                }
18112                for (int i = 0; i < users.length; ++i) {
18113                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18114                        return true;
18115                    }
18116                }
18117            }
18118        } catch (RemoteException e) {
18119        }
18120        return false;
18121    }
18122
18123    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18124        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18125    }
18126
18127    /**
18128     *  This method is an internal method that could be get invoked either
18129     *  to delete an installed package or to clean up a failed installation.
18130     *  After deleting an installed package, a broadcast is sent to notify any
18131     *  listeners that the package has been removed. For cleaning up a failed
18132     *  installation, the broadcast is not necessary since the package's
18133     *  installation wouldn't have sent the initial broadcast either
18134     *  The key steps in deleting a package are
18135     *  deleting the package information in internal structures like mPackages,
18136     *  deleting the packages base directories through installd
18137     *  updating mSettings to reflect current status
18138     *  persisting settings for later use
18139     *  sending a broadcast if necessary
18140     */
18141    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18142        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18143        final boolean res;
18144
18145        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18146                ? UserHandle.USER_ALL : userId;
18147
18148        if (isPackageDeviceAdmin(packageName, removeUser)) {
18149            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18150            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18151        }
18152
18153        PackageSetting uninstalledPs = null;
18154        PackageParser.Package pkg = null;
18155
18156        // for the uninstall-updates case and restricted profiles, remember the per-
18157        // user handle installed state
18158        int[] allUsers;
18159        synchronized (mPackages) {
18160            uninstalledPs = mSettings.mPackages.get(packageName);
18161            if (uninstalledPs == null) {
18162                Slog.w(TAG, "Not removing non-existent package " + packageName);
18163                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18164            }
18165
18166            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18167                    && uninstalledPs.versionCode != versionCode) {
18168                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18169                        + uninstalledPs.versionCode + " != " + versionCode);
18170                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18171            }
18172
18173            // Static shared libs can be declared by any package, so let us not
18174            // allow removing a package if it provides a lib others depend on.
18175            pkg = mPackages.get(packageName);
18176
18177            allUsers = sUserManager.getUserIds();
18178
18179            if (pkg != null && pkg.staticSharedLibName != null) {
18180                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18181                        pkg.staticSharedLibVersion);
18182                if (libEntry != null) {
18183                    for (int currUserId : allUsers) {
18184                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18185                            continue;
18186                        }
18187                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18188                                libEntry.info, 0, currUserId);
18189                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18190                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18191                                    + " hosting lib " + libEntry.info.getName() + " version "
18192                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18193                                    + " for user " + currUserId);
18194                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18195                        }
18196                    }
18197                }
18198            }
18199
18200            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18201        }
18202
18203        final int freezeUser;
18204        if (isUpdatedSystemApp(uninstalledPs)
18205                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18206            // We're downgrading a system app, which will apply to all users, so
18207            // freeze them all during the downgrade
18208            freezeUser = UserHandle.USER_ALL;
18209        } else {
18210            freezeUser = removeUser;
18211        }
18212
18213        synchronized (mInstallLock) {
18214            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18215            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18216                    deleteFlags, "deletePackageX")) {
18217                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18218                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18219            }
18220            synchronized (mPackages) {
18221                if (res) {
18222                    if (pkg != null) {
18223                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18224                    }
18225                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18226                    updateInstantAppInstallerLocked(packageName);
18227                }
18228            }
18229        }
18230
18231        if (res) {
18232            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18233            info.sendPackageRemovedBroadcasts(killApp);
18234            info.sendSystemPackageUpdatedBroadcasts();
18235            info.sendSystemPackageAppearedBroadcasts();
18236        }
18237        // Force a gc here.
18238        Runtime.getRuntime().gc();
18239        // Delete the resources here after sending the broadcast to let
18240        // other processes clean up before deleting resources.
18241        if (info.args != null) {
18242            synchronized (mInstallLock) {
18243                info.args.doPostDeleteLI(true);
18244            }
18245        }
18246
18247        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18248    }
18249
18250    static class PackageRemovedInfo {
18251        final PackageSender packageSender;
18252        String removedPackage;
18253        String installerPackageName;
18254        int uid = -1;
18255        int removedAppId = -1;
18256        int[] origUsers;
18257        int[] removedUsers = null;
18258        int[] broadcastUsers = null;
18259        SparseArray<Integer> installReasons;
18260        boolean isRemovedPackageSystemUpdate = false;
18261        boolean isUpdate;
18262        boolean dataRemoved;
18263        boolean removedForAllUsers;
18264        boolean isStaticSharedLib;
18265        // Clean up resources deleted packages.
18266        InstallArgs args = null;
18267        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18268        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18269
18270        PackageRemovedInfo(PackageSender packageSender) {
18271            this.packageSender = packageSender;
18272        }
18273
18274        void sendPackageRemovedBroadcasts(boolean killApp) {
18275            sendPackageRemovedBroadcastInternal(killApp);
18276            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18277            for (int i = 0; i < childCount; i++) {
18278                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18279                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18280            }
18281        }
18282
18283        void sendSystemPackageUpdatedBroadcasts() {
18284            if (isRemovedPackageSystemUpdate) {
18285                sendSystemPackageUpdatedBroadcastsInternal();
18286                final int childCount = (removedChildPackages != null)
18287                        ? removedChildPackages.size() : 0;
18288                for (int i = 0; i < childCount; i++) {
18289                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18290                    if (childInfo.isRemovedPackageSystemUpdate) {
18291                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18292                    }
18293                }
18294            }
18295        }
18296
18297        void sendSystemPackageAppearedBroadcasts() {
18298            final int packageCount = (appearedChildPackages != null)
18299                    ? appearedChildPackages.size() : 0;
18300            for (int i = 0; i < packageCount; i++) {
18301                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18302                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18303                    true /*sendBootCompleted*/, false /*startReceiver*/,
18304                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
18305            }
18306        }
18307
18308        private void sendSystemPackageUpdatedBroadcastsInternal() {
18309            Bundle extras = new Bundle(2);
18310            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18311            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18312            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18313                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18314            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18315                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18316            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18317                null, null, 0, removedPackage, null, null);
18318            if (installerPackageName != null) {
18319                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18320                        removedPackage, extras, 0 /*flags*/,
18321                        installerPackageName, null, null);
18322                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18323                        removedPackage, extras, 0 /*flags*/,
18324                        installerPackageName, null, null);
18325            }
18326        }
18327
18328        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18329            // Don't send static shared library removal broadcasts as these
18330            // libs are visible only the the apps that depend on them an one
18331            // cannot remove the library if it has a dependency.
18332            if (isStaticSharedLib) {
18333                return;
18334            }
18335            Bundle extras = new Bundle(2);
18336            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18337            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18338            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18339            if (isUpdate || isRemovedPackageSystemUpdate) {
18340                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18341            }
18342            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18343            if (removedPackage != null) {
18344                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18345                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18346                if (installerPackageName != null) {
18347                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18348                            removedPackage, extras, 0 /*flags*/,
18349                            installerPackageName, null, broadcastUsers);
18350                }
18351                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18352                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18353                        removedPackage, extras,
18354                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18355                        null, null, broadcastUsers);
18356                }
18357            }
18358            if (removedAppId >= 0) {
18359                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18360                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18361                    null, null, broadcastUsers);
18362            }
18363        }
18364
18365        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18366            removedUsers = userIds;
18367            if (removedUsers == null) {
18368                broadcastUsers = null;
18369                return;
18370            }
18371
18372            broadcastUsers = EMPTY_INT_ARRAY;
18373            for (int i = userIds.length - 1; i >= 0; --i) {
18374                final int userId = userIds[i];
18375                if (deletedPackageSetting.getInstantApp(userId)) {
18376                    continue;
18377                }
18378                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18379            }
18380        }
18381    }
18382
18383    /*
18384     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18385     * flag is not set, the data directory is removed as well.
18386     * make sure this flag is set for partially installed apps. If not its meaningless to
18387     * delete a partially installed application.
18388     */
18389    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18390            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18391        String packageName = ps.name;
18392        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18393        // Retrieve object to delete permissions for shared user later on
18394        final PackageParser.Package deletedPkg;
18395        final PackageSetting deletedPs;
18396        // reader
18397        synchronized (mPackages) {
18398            deletedPkg = mPackages.get(packageName);
18399            deletedPs = mSettings.mPackages.get(packageName);
18400            if (outInfo != null) {
18401                outInfo.removedPackage = packageName;
18402                outInfo.installerPackageName = ps.installerPackageName;
18403                outInfo.isStaticSharedLib = deletedPkg != null
18404                        && deletedPkg.staticSharedLibName != null;
18405                outInfo.populateUsers(deletedPs == null ? null
18406                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18407            }
18408        }
18409
18410        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18411
18412        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18413            final PackageParser.Package resolvedPkg;
18414            if (deletedPkg != null) {
18415                resolvedPkg = deletedPkg;
18416            } else {
18417                // We don't have a parsed package when it lives on an ejected
18418                // adopted storage device, so fake something together
18419                resolvedPkg = new PackageParser.Package(ps.name);
18420                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18421            }
18422            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18423                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18424            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18425            if (outInfo != null) {
18426                outInfo.dataRemoved = true;
18427            }
18428            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18429        }
18430
18431        int removedAppId = -1;
18432
18433        // writer
18434        synchronized (mPackages) {
18435            boolean installedStateChanged = false;
18436            if (deletedPs != null) {
18437                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18438                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18439                    clearDefaultBrowserIfNeeded(packageName);
18440                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18441                    removedAppId = mSettings.removePackageLPw(packageName);
18442                    if (outInfo != null) {
18443                        outInfo.removedAppId = removedAppId;
18444                    }
18445                    updatePermissionsLPw(deletedPs.name, null, 0);
18446                    if (deletedPs.sharedUser != null) {
18447                        // Remove permissions associated with package. Since runtime
18448                        // permissions are per user we have to kill the removed package
18449                        // or packages running under the shared user of the removed
18450                        // package if revoking the permissions requested only by the removed
18451                        // package is successful and this causes a change in gids.
18452                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18453                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18454                                    userId);
18455                            if (userIdToKill == UserHandle.USER_ALL
18456                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18457                                // If gids changed for this user, kill all affected packages.
18458                                mHandler.post(new Runnable() {
18459                                    @Override
18460                                    public void run() {
18461                                        // This has to happen with no lock held.
18462                                        killApplication(deletedPs.name, deletedPs.appId,
18463                                                KILL_APP_REASON_GIDS_CHANGED);
18464                                    }
18465                                });
18466                                break;
18467                            }
18468                        }
18469                    }
18470                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18471                }
18472                // make sure to preserve per-user disabled state if this removal was just
18473                // a downgrade of a system app to the factory package
18474                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18475                    if (DEBUG_REMOVE) {
18476                        Slog.d(TAG, "Propagating install state across downgrade");
18477                    }
18478                    for (int userId : allUserHandles) {
18479                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18480                        if (DEBUG_REMOVE) {
18481                            Slog.d(TAG, "    user " + userId + " => " + installed);
18482                        }
18483                        if (installed != ps.getInstalled(userId)) {
18484                            installedStateChanged = true;
18485                        }
18486                        ps.setInstalled(installed, userId);
18487                    }
18488                }
18489            }
18490            // can downgrade to reader
18491            if (writeSettings) {
18492                // Save settings now
18493                mSettings.writeLPr();
18494            }
18495            if (installedStateChanged) {
18496                mSettings.writeKernelMappingLPr(ps);
18497            }
18498        }
18499        if (removedAppId != -1) {
18500            // A user ID was deleted here. Go through all users and remove it
18501            // from KeyStore.
18502            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18503        }
18504    }
18505
18506    static boolean locationIsPrivileged(File path) {
18507        try {
18508            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18509                    .getCanonicalPath();
18510            return path.getCanonicalPath().startsWith(privilegedAppDir);
18511        } catch (IOException e) {
18512            Slog.e(TAG, "Unable to access code path " + path);
18513        }
18514        return false;
18515    }
18516
18517    static boolean locationIsOem(File path) {
18518        try {
18519            return path.getCanonicalPath().startsWith(
18520                    Environment.getOemDirectory().getCanonicalPath());
18521        } catch (IOException e) {
18522            Slog.e(TAG, "Unable to access code path " + path);
18523        }
18524        return false;
18525    }
18526
18527    /*
18528     * Tries to delete system package.
18529     */
18530    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18531            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18532            boolean writeSettings) {
18533        if (deletedPs.parentPackageName != null) {
18534            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18535            return false;
18536        }
18537
18538        final boolean applyUserRestrictions
18539                = (allUserHandles != null) && (outInfo.origUsers != null);
18540        final PackageSetting disabledPs;
18541        // Confirm if the system package has been updated
18542        // An updated system app can be deleted. This will also have to restore
18543        // the system pkg from system partition
18544        // reader
18545        synchronized (mPackages) {
18546            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18547        }
18548
18549        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18550                + " disabledPs=" + disabledPs);
18551
18552        if (disabledPs == null) {
18553            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18554            return false;
18555        } else if (DEBUG_REMOVE) {
18556            Slog.d(TAG, "Deleting system pkg from data partition");
18557        }
18558
18559        if (DEBUG_REMOVE) {
18560            if (applyUserRestrictions) {
18561                Slog.d(TAG, "Remembering install states:");
18562                for (int userId : allUserHandles) {
18563                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18564                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18565                }
18566            }
18567        }
18568
18569        // Delete the updated package
18570        outInfo.isRemovedPackageSystemUpdate = true;
18571        if (outInfo.removedChildPackages != null) {
18572            final int childCount = (deletedPs.childPackageNames != null)
18573                    ? deletedPs.childPackageNames.size() : 0;
18574            for (int i = 0; i < childCount; i++) {
18575                String childPackageName = deletedPs.childPackageNames.get(i);
18576                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18577                        .contains(childPackageName)) {
18578                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18579                            childPackageName);
18580                    if (childInfo != null) {
18581                        childInfo.isRemovedPackageSystemUpdate = true;
18582                    }
18583                }
18584            }
18585        }
18586
18587        if (disabledPs.versionCode < deletedPs.versionCode) {
18588            // Delete data for downgrades
18589            flags &= ~PackageManager.DELETE_KEEP_DATA;
18590        } else {
18591            // Preserve data by setting flag
18592            flags |= PackageManager.DELETE_KEEP_DATA;
18593        }
18594
18595        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18596                outInfo, writeSettings, disabledPs.pkg);
18597        if (!ret) {
18598            return false;
18599        }
18600
18601        // writer
18602        synchronized (mPackages) {
18603            // NOTE: The system package always needs to be enabled; even if it's for
18604            // a compressed stub. If we don't, installing the system package fails
18605            // during scan [scanning checks the disabled packages]. We will reverse
18606            // this later, after we've "installed" the stub.
18607            // Reinstate the old system package
18608            enableSystemPackageLPw(disabledPs.pkg);
18609            // Remove any native libraries from the upgraded package.
18610            removeNativeBinariesLI(deletedPs);
18611        }
18612
18613        // Install the system package
18614        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18615        try {
18616            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
18617                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18618        } catch (PackageManagerException e) {
18619            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18620                    + e.getMessage());
18621            return false;
18622        } finally {
18623            if (disabledPs.pkg.isStub) {
18624                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18625            }
18626        }
18627        return true;
18628    }
18629
18630    /**
18631     * Installs a package that's already on the system partition.
18632     */
18633    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
18634            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18635            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18636                    throws PackageManagerException {
18637        int parseFlags = mDefParseFlags
18638                | PackageParser.PARSE_MUST_BE_APK
18639                | PackageParser.PARSE_IS_SYSTEM
18640                | PackageParser.PARSE_IS_SYSTEM_DIR;
18641        if (isPrivileged || locationIsPrivileged(codePath)) {
18642            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18643        }
18644        if (locationIsOem(codePath)) {
18645            parseFlags |= PackageParser.PARSE_IS_OEM;
18646        }
18647
18648        final PackageParser.Package newPkg =
18649                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
18650
18651        try {
18652            // update shared libraries for the newly re-installed system package
18653            updateSharedLibrariesLPr(newPkg, null);
18654        } catch (PackageManagerException e) {
18655            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18656        }
18657
18658        prepareAppDataAfterInstallLIF(newPkg);
18659
18660        // writer
18661        synchronized (mPackages) {
18662            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18663
18664            // Propagate the permissions state as we do not want to drop on the floor
18665            // runtime permissions. The update permissions method below will take
18666            // care of removing obsolete permissions and grant install permissions.
18667            if (origPermissionState != null) {
18668                ps.getPermissionsState().copyFrom(origPermissionState);
18669            }
18670            updatePermissionsLPw(newPkg.packageName, newPkg,
18671                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18672
18673            final boolean applyUserRestrictions
18674                    = (allUserHandles != null) && (origUserHandles != null);
18675            if (applyUserRestrictions) {
18676                boolean installedStateChanged = false;
18677                if (DEBUG_REMOVE) {
18678                    Slog.d(TAG, "Propagating install state across reinstall");
18679                }
18680                for (int userId : allUserHandles) {
18681                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18682                    if (DEBUG_REMOVE) {
18683                        Slog.d(TAG, "    user " + userId + " => " + installed);
18684                    }
18685                    if (installed != ps.getInstalled(userId)) {
18686                        installedStateChanged = true;
18687                    }
18688                    ps.setInstalled(installed, userId);
18689
18690                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18691                }
18692                // Regardless of writeSettings we need to ensure that this restriction
18693                // state propagation is persisted
18694                mSettings.writeAllUsersPackageRestrictionsLPr();
18695                if (installedStateChanged) {
18696                    mSettings.writeKernelMappingLPr(ps);
18697                }
18698            }
18699            // can downgrade to reader here
18700            if (writeSettings) {
18701                mSettings.writeLPr();
18702            }
18703        }
18704        return newPkg;
18705    }
18706
18707    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18708            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18709            PackageRemovedInfo outInfo, boolean writeSettings,
18710            PackageParser.Package replacingPackage) {
18711        synchronized (mPackages) {
18712            if (outInfo != null) {
18713                outInfo.uid = ps.appId;
18714            }
18715
18716            if (outInfo != null && outInfo.removedChildPackages != null) {
18717                final int childCount = (ps.childPackageNames != null)
18718                        ? ps.childPackageNames.size() : 0;
18719                for (int i = 0; i < childCount; i++) {
18720                    String childPackageName = ps.childPackageNames.get(i);
18721                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18722                    if (childPs == null) {
18723                        return false;
18724                    }
18725                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18726                            childPackageName);
18727                    if (childInfo != null) {
18728                        childInfo.uid = childPs.appId;
18729                    }
18730                }
18731            }
18732        }
18733
18734        // Delete package data from internal structures and also remove data if flag is set
18735        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18736
18737        // Delete the child packages data
18738        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18739        for (int i = 0; i < childCount; i++) {
18740            PackageSetting childPs;
18741            synchronized (mPackages) {
18742                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18743            }
18744            if (childPs != null) {
18745                PackageRemovedInfo childOutInfo = (outInfo != null
18746                        && outInfo.removedChildPackages != null)
18747                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18748                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18749                        && (replacingPackage != null
18750                        && !replacingPackage.hasChildPackage(childPs.name))
18751                        ? flags & ~DELETE_KEEP_DATA : flags;
18752                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18753                        deleteFlags, writeSettings);
18754            }
18755        }
18756
18757        // Delete application code and resources only for parent packages
18758        if (ps.parentPackageName == null) {
18759            if (deleteCodeAndResources && (outInfo != null)) {
18760                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18761                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18762                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18763            }
18764        }
18765
18766        return true;
18767    }
18768
18769    @Override
18770    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18771            int userId) {
18772        mContext.enforceCallingOrSelfPermission(
18773                android.Manifest.permission.DELETE_PACKAGES, null);
18774        synchronized (mPackages) {
18775            // Cannot block uninstall of static shared libs as they are
18776            // considered a part of the using app (emulating static linking).
18777            // Also static libs are installed always on internal storage.
18778            PackageParser.Package pkg = mPackages.get(packageName);
18779            if (pkg != null && pkg.staticSharedLibName != null) {
18780                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18781                        + " providing static shared library: " + pkg.staticSharedLibName);
18782                return false;
18783            }
18784            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18785            mSettings.writePackageRestrictionsLPr(userId);
18786        }
18787        return true;
18788    }
18789
18790    @Override
18791    public boolean getBlockUninstallForUser(String packageName, int userId) {
18792        synchronized (mPackages) {
18793            final PackageSetting ps = mSettings.mPackages.get(packageName);
18794            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18795                return false;
18796            }
18797            return mSettings.getBlockUninstallLPr(userId, packageName);
18798        }
18799    }
18800
18801    @Override
18802    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18803        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18804        synchronized (mPackages) {
18805            PackageSetting ps = mSettings.mPackages.get(packageName);
18806            if (ps == null) {
18807                Log.w(TAG, "Package doesn't exist: " + packageName);
18808                return false;
18809            }
18810            if (systemUserApp) {
18811                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18812            } else {
18813                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18814            }
18815            mSettings.writeLPr();
18816        }
18817        return true;
18818    }
18819
18820    /*
18821     * This method handles package deletion in general
18822     */
18823    private boolean deletePackageLIF(String packageName, UserHandle user,
18824            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18825            PackageRemovedInfo outInfo, boolean writeSettings,
18826            PackageParser.Package replacingPackage) {
18827        if (packageName == null) {
18828            Slog.w(TAG, "Attempt to delete null packageName.");
18829            return false;
18830        }
18831
18832        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18833
18834        PackageSetting ps;
18835        synchronized (mPackages) {
18836            ps = mSettings.mPackages.get(packageName);
18837            if (ps == null) {
18838                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18839                return false;
18840            }
18841
18842            if (ps.parentPackageName != null && (!isSystemApp(ps)
18843                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18844                if (DEBUG_REMOVE) {
18845                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18846                            + ((user == null) ? UserHandle.USER_ALL : user));
18847                }
18848                final int removedUserId = (user != null) ? user.getIdentifier()
18849                        : UserHandle.USER_ALL;
18850                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18851                    return false;
18852                }
18853                markPackageUninstalledForUserLPw(ps, user);
18854                scheduleWritePackageRestrictionsLocked(user);
18855                return true;
18856            }
18857        }
18858
18859        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18860                && user.getIdentifier() != UserHandle.USER_ALL)) {
18861            // The caller is asking that the package only be deleted for a single
18862            // user.  To do this, we just mark its uninstalled state and delete
18863            // its data. If this is a system app, we only allow this to happen if
18864            // they have set the special DELETE_SYSTEM_APP which requests different
18865            // semantics than normal for uninstalling system apps.
18866            markPackageUninstalledForUserLPw(ps, user);
18867
18868            if (!isSystemApp(ps)) {
18869                // Do not uninstall the APK if an app should be cached
18870                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18871                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18872                    // Other user still have this package installed, so all
18873                    // we need to do is clear this user's data and save that
18874                    // it is uninstalled.
18875                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18876                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18877                        return false;
18878                    }
18879                    scheduleWritePackageRestrictionsLocked(user);
18880                    return true;
18881                } else {
18882                    // We need to set it back to 'installed' so the uninstall
18883                    // broadcasts will be sent correctly.
18884                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18885                    ps.setInstalled(true, user.getIdentifier());
18886                    mSettings.writeKernelMappingLPr(ps);
18887                }
18888            } else {
18889                // This is a system app, so we assume that the
18890                // other users still have this package installed, so all
18891                // we need to do is clear this user's data and save that
18892                // it is uninstalled.
18893                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18894                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18895                    return false;
18896                }
18897                scheduleWritePackageRestrictionsLocked(user);
18898                return true;
18899            }
18900        }
18901
18902        // If we are deleting a composite package for all users, keep track
18903        // of result for each child.
18904        if (ps.childPackageNames != null && outInfo != null) {
18905            synchronized (mPackages) {
18906                final int childCount = ps.childPackageNames.size();
18907                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18908                for (int i = 0; i < childCount; i++) {
18909                    String childPackageName = ps.childPackageNames.get(i);
18910                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18911                    childInfo.removedPackage = childPackageName;
18912                    childInfo.installerPackageName = ps.installerPackageName;
18913                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18914                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18915                    if (childPs != null) {
18916                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18917                    }
18918                }
18919            }
18920        }
18921
18922        boolean ret = false;
18923        if (isSystemApp(ps)) {
18924            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18925            // When an updated system application is deleted we delete the existing resources
18926            // as well and fall back to existing code in system partition
18927            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18928        } else {
18929            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18930            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18931                    outInfo, writeSettings, replacingPackage);
18932        }
18933
18934        // Take a note whether we deleted the package for all users
18935        if (outInfo != null) {
18936            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18937            if (outInfo.removedChildPackages != null) {
18938                synchronized (mPackages) {
18939                    final int childCount = outInfo.removedChildPackages.size();
18940                    for (int i = 0; i < childCount; i++) {
18941                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18942                        if (childInfo != null) {
18943                            childInfo.removedForAllUsers = mPackages.get(
18944                                    childInfo.removedPackage) == null;
18945                        }
18946                    }
18947                }
18948            }
18949            // If we uninstalled an update to a system app there may be some
18950            // child packages that appeared as they are declared in the system
18951            // app but were not declared in the update.
18952            if (isSystemApp(ps)) {
18953                synchronized (mPackages) {
18954                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18955                    final int childCount = (updatedPs.childPackageNames != null)
18956                            ? updatedPs.childPackageNames.size() : 0;
18957                    for (int i = 0; i < childCount; i++) {
18958                        String childPackageName = updatedPs.childPackageNames.get(i);
18959                        if (outInfo.removedChildPackages == null
18960                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18961                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18962                            if (childPs == null) {
18963                                continue;
18964                            }
18965                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18966                            installRes.name = childPackageName;
18967                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18968                            installRes.pkg = mPackages.get(childPackageName);
18969                            installRes.uid = childPs.pkg.applicationInfo.uid;
18970                            if (outInfo.appearedChildPackages == null) {
18971                                outInfo.appearedChildPackages = new ArrayMap<>();
18972                            }
18973                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18974                        }
18975                    }
18976                }
18977            }
18978        }
18979
18980        return ret;
18981    }
18982
18983    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18984        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18985                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18986        for (int nextUserId : userIds) {
18987            if (DEBUG_REMOVE) {
18988                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18989            }
18990            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18991                    false /*installed*/,
18992                    true /*stopped*/,
18993                    true /*notLaunched*/,
18994                    false /*hidden*/,
18995                    false /*suspended*/,
18996                    false /*instantApp*/,
18997                    false /*virtualPreload*/,
18998                    null /*lastDisableAppCaller*/,
18999                    null /*enabledComponents*/,
19000                    null /*disabledComponents*/,
19001                    ps.readUserState(nextUserId).domainVerificationStatus,
19002                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19003        }
19004        mSettings.writeKernelMappingLPr(ps);
19005    }
19006
19007    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19008            PackageRemovedInfo outInfo) {
19009        final PackageParser.Package pkg;
19010        synchronized (mPackages) {
19011            pkg = mPackages.get(ps.name);
19012        }
19013
19014        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19015                : new int[] {userId};
19016        for (int nextUserId : userIds) {
19017            if (DEBUG_REMOVE) {
19018                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19019                        + nextUserId);
19020            }
19021
19022            destroyAppDataLIF(pkg, userId,
19023                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19024            destroyAppProfilesLIF(pkg, userId);
19025            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19026            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19027            schedulePackageCleaning(ps.name, nextUserId, false);
19028            synchronized (mPackages) {
19029                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19030                    scheduleWritePackageRestrictionsLocked(nextUserId);
19031                }
19032                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19033            }
19034        }
19035
19036        if (outInfo != null) {
19037            outInfo.removedPackage = ps.name;
19038            outInfo.installerPackageName = ps.installerPackageName;
19039            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19040            outInfo.removedAppId = ps.appId;
19041            outInfo.removedUsers = userIds;
19042            outInfo.broadcastUsers = userIds;
19043        }
19044
19045        return true;
19046    }
19047
19048    private final class ClearStorageConnection implements ServiceConnection {
19049        IMediaContainerService mContainerService;
19050
19051        @Override
19052        public void onServiceConnected(ComponentName name, IBinder service) {
19053            synchronized (this) {
19054                mContainerService = IMediaContainerService.Stub
19055                        .asInterface(Binder.allowBlocking(service));
19056                notifyAll();
19057            }
19058        }
19059
19060        @Override
19061        public void onServiceDisconnected(ComponentName name) {
19062        }
19063    }
19064
19065    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19066        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19067
19068        final boolean mounted;
19069        if (Environment.isExternalStorageEmulated()) {
19070            mounted = true;
19071        } else {
19072            final String status = Environment.getExternalStorageState();
19073
19074            mounted = status.equals(Environment.MEDIA_MOUNTED)
19075                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19076        }
19077
19078        if (!mounted) {
19079            return;
19080        }
19081
19082        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19083        int[] users;
19084        if (userId == UserHandle.USER_ALL) {
19085            users = sUserManager.getUserIds();
19086        } else {
19087            users = new int[] { userId };
19088        }
19089        final ClearStorageConnection conn = new ClearStorageConnection();
19090        if (mContext.bindServiceAsUser(
19091                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19092            try {
19093                for (int curUser : users) {
19094                    long timeout = SystemClock.uptimeMillis() + 5000;
19095                    synchronized (conn) {
19096                        long now;
19097                        while (conn.mContainerService == null &&
19098                                (now = SystemClock.uptimeMillis()) < timeout) {
19099                            try {
19100                                conn.wait(timeout - now);
19101                            } catch (InterruptedException e) {
19102                            }
19103                        }
19104                    }
19105                    if (conn.mContainerService == null) {
19106                        return;
19107                    }
19108
19109                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19110                    clearDirectory(conn.mContainerService,
19111                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19112                    if (allData) {
19113                        clearDirectory(conn.mContainerService,
19114                                userEnv.buildExternalStorageAppDataDirs(packageName));
19115                        clearDirectory(conn.mContainerService,
19116                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19117                    }
19118                }
19119            } finally {
19120                mContext.unbindService(conn);
19121            }
19122        }
19123    }
19124
19125    @Override
19126    public void clearApplicationProfileData(String packageName) {
19127        enforceSystemOrRoot("Only the system can clear all profile data");
19128
19129        final PackageParser.Package pkg;
19130        synchronized (mPackages) {
19131            pkg = mPackages.get(packageName);
19132        }
19133
19134        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19135            synchronized (mInstallLock) {
19136                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19137            }
19138        }
19139    }
19140
19141    @Override
19142    public void clearApplicationUserData(final String packageName,
19143            final IPackageDataObserver observer, final int userId) {
19144        mContext.enforceCallingOrSelfPermission(
19145                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19146
19147        final int callingUid = Binder.getCallingUid();
19148        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19149                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19150
19151        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19152        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19153        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19154            throw new SecurityException("Cannot clear data for a protected package: "
19155                    + packageName);
19156        }
19157        // Queue up an async operation since the package deletion may take a little while.
19158        mHandler.post(new Runnable() {
19159            public void run() {
19160                mHandler.removeCallbacks(this);
19161                final boolean succeeded;
19162                if (!filterApp) {
19163                    try (PackageFreezer freezer = freezePackage(packageName,
19164                            "clearApplicationUserData")) {
19165                        synchronized (mInstallLock) {
19166                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19167                        }
19168                        clearExternalStorageDataSync(packageName, userId, true);
19169                        synchronized (mPackages) {
19170                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19171                                    packageName, userId);
19172                        }
19173                    }
19174                    if (succeeded) {
19175                        // invoke DeviceStorageMonitor's update method to clear any notifications
19176                        DeviceStorageMonitorInternal dsm = LocalServices
19177                                .getService(DeviceStorageMonitorInternal.class);
19178                        if (dsm != null) {
19179                            dsm.checkMemory();
19180                        }
19181                    }
19182                } else {
19183                    succeeded = false;
19184                }
19185                if (observer != null) {
19186                    try {
19187                        observer.onRemoveCompleted(packageName, succeeded);
19188                    } catch (RemoteException e) {
19189                        Log.i(TAG, "Observer no longer exists.");
19190                    }
19191                } //end if observer
19192            } //end run
19193        });
19194    }
19195
19196    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19197        if (packageName == null) {
19198            Slog.w(TAG, "Attempt to delete null packageName.");
19199            return false;
19200        }
19201
19202        // Try finding details about the requested package
19203        PackageParser.Package pkg;
19204        synchronized (mPackages) {
19205            pkg = mPackages.get(packageName);
19206            if (pkg == null) {
19207                final PackageSetting ps = mSettings.mPackages.get(packageName);
19208                if (ps != null) {
19209                    pkg = ps.pkg;
19210                }
19211            }
19212
19213            if (pkg == null) {
19214                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19215                return false;
19216            }
19217
19218            PackageSetting ps = (PackageSetting) pkg.mExtras;
19219            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19220        }
19221
19222        clearAppDataLIF(pkg, userId,
19223                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19224
19225        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19226        removeKeystoreDataIfNeeded(userId, appId);
19227
19228        UserManagerInternal umInternal = getUserManagerInternal();
19229        final int flags;
19230        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19231            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19232        } else if (umInternal.isUserRunning(userId)) {
19233            flags = StorageManager.FLAG_STORAGE_DE;
19234        } else {
19235            flags = 0;
19236        }
19237        prepareAppDataContentsLIF(pkg, userId, flags);
19238
19239        return true;
19240    }
19241
19242    /**
19243     * Reverts user permission state changes (permissions and flags) in
19244     * all packages for a given user.
19245     *
19246     * @param userId The device user for which to do a reset.
19247     */
19248    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19249        final int packageCount = mPackages.size();
19250        for (int i = 0; i < packageCount; i++) {
19251            PackageParser.Package pkg = mPackages.valueAt(i);
19252            PackageSetting ps = (PackageSetting) pkg.mExtras;
19253            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19254        }
19255    }
19256
19257    private void resetNetworkPolicies(int userId) {
19258        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19259    }
19260
19261    /**
19262     * Reverts user permission state changes (permissions and flags).
19263     *
19264     * @param ps The package for which to reset.
19265     * @param userId The device user for which to do a reset.
19266     */
19267    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19268            final PackageSetting ps, final int userId) {
19269        if (ps.pkg == null) {
19270            return;
19271        }
19272
19273        // These are flags that can change base on user actions.
19274        final int userSettableMask = FLAG_PERMISSION_USER_SET
19275                | FLAG_PERMISSION_USER_FIXED
19276                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19277                | FLAG_PERMISSION_REVIEW_REQUIRED;
19278
19279        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19280                | FLAG_PERMISSION_POLICY_FIXED;
19281
19282        boolean writeInstallPermissions = false;
19283        boolean writeRuntimePermissions = false;
19284
19285        final int permissionCount = ps.pkg.requestedPermissions.size();
19286        for (int i = 0; i < permissionCount; i++) {
19287            final String permName = ps.pkg.requestedPermissions.get(i);
19288            final BasePermission bp =
19289                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19290            if (bp == null) {
19291                continue;
19292            }
19293
19294            // If shared user we just reset the state to which only this app contributed.
19295            if (ps.sharedUser != null) {
19296                boolean used = false;
19297                final int packageCount = ps.sharedUser.packages.size();
19298                for (int j = 0; j < packageCount; j++) {
19299                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19300                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19301                            && pkg.pkg.requestedPermissions.contains(permName)) {
19302                        used = true;
19303                        break;
19304                    }
19305                }
19306                if (used) {
19307                    continue;
19308                }
19309            }
19310
19311            final PermissionsState permissionsState = ps.getPermissionsState();
19312
19313            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19314
19315            // Always clear the user settable flags.
19316            final boolean hasInstallState =
19317                    permissionsState.getInstallPermissionState(permName) != null;
19318            // If permission review is enabled and this is a legacy app, mark the
19319            // permission as requiring a review as this is the initial state.
19320            int flags = 0;
19321            if (mPermissionReviewRequired
19322                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19323                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19324            }
19325            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19326                if (hasInstallState) {
19327                    writeInstallPermissions = true;
19328                } else {
19329                    writeRuntimePermissions = true;
19330                }
19331            }
19332
19333            // Below is only runtime permission handling.
19334            if (!bp.isRuntime()) {
19335                continue;
19336            }
19337
19338            // Never clobber system or policy.
19339            if ((oldFlags & policyOrSystemFlags) != 0) {
19340                continue;
19341            }
19342
19343            // If this permission was granted by default, make sure it is.
19344            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19345                if (permissionsState.grantRuntimePermission(bp, userId)
19346                        != PERMISSION_OPERATION_FAILURE) {
19347                    writeRuntimePermissions = true;
19348                }
19349            // If permission review is enabled the permissions for a legacy apps
19350            // are represented as constantly granted runtime ones, so don't revoke.
19351            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19352                // Otherwise, reset the permission.
19353                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19354                switch (revokeResult) {
19355                    case PERMISSION_OPERATION_SUCCESS:
19356                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19357                        writeRuntimePermissions = true;
19358                        final int appId = ps.appId;
19359                        mHandler.post(new Runnable() {
19360                            @Override
19361                            public void run() {
19362                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19363                            }
19364                        });
19365                    } break;
19366                }
19367            }
19368        }
19369
19370        // Synchronously write as we are taking permissions away.
19371        if (writeRuntimePermissions) {
19372            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19373        }
19374
19375        // Synchronously write as we are taking permissions away.
19376        if (writeInstallPermissions) {
19377            mSettings.writeLPr();
19378        }
19379    }
19380
19381    /**
19382     * Remove entries from the keystore daemon. Will only remove it if the
19383     * {@code appId} is valid.
19384     */
19385    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19386        if (appId < 0) {
19387            return;
19388        }
19389
19390        final KeyStore keyStore = KeyStore.getInstance();
19391        if (keyStore != null) {
19392            if (userId == UserHandle.USER_ALL) {
19393                for (final int individual : sUserManager.getUserIds()) {
19394                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19395                }
19396            } else {
19397                keyStore.clearUid(UserHandle.getUid(userId, appId));
19398            }
19399        } else {
19400            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19401        }
19402    }
19403
19404    @Override
19405    public void deleteApplicationCacheFiles(final String packageName,
19406            final IPackageDataObserver observer) {
19407        final int userId = UserHandle.getCallingUserId();
19408        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19409    }
19410
19411    @Override
19412    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19413            final IPackageDataObserver observer) {
19414        final int callingUid = Binder.getCallingUid();
19415        mContext.enforceCallingOrSelfPermission(
19416                android.Manifest.permission.DELETE_CACHE_FILES, null);
19417        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19418                /* requireFullPermission= */ true, /* checkShell= */ false,
19419                "delete application cache files");
19420        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19421                android.Manifest.permission.ACCESS_INSTANT_APPS);
19422
19423        final PackageParser.Package pkg;
19424        synchronized (mPackages) {
19425            pkg = mPackages.get(packageName);
19426        }
19427
19428        // Queue up an async operation since the package deletion may take a little while.
19429        mHandler.post(new Runnable() {
19430            public void run() {
19431                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19432                boolean doClearData = true;
19433                if (ps != null) {
19434                    final boolean targetIsInstantApp =
19435                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19436                    doClearData = !targetIsInstantApp
19437                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19438                }
19439                if (doClearData) {
19440                    synchronized (mInstallLock) {
19441                        final int flags = StorageManager.FLAG_STORAGE_DE
19442                                | StorageManager.FLAG_STORAGE_CE;
19443                        // We're only clearing cache files, so we don't care if the
19444                        // app is unfrozen and still able to run
19445                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19446                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19447                    }
19448                    clearExternalStorageDataSync(packageName, userId, false);
19449                }
19450                if (observer != null) {
19451                    try {
19452                        observer.onRemoveCompleted(packageName, true);
19453                    } catch (RemoteException e) {
19454                        Log.i(TAG, "Observer no longer exists.");
19455                    }
19456                }
19457            }
19458        });
19459    }
19460
19461    @Override
19462    public void getPackageSizeInfo(final String packageName, int userHandle,
19463            final IPackageStatsObserver observer) {
19464        throw new UnsupportedOperationException(
19465                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19466    }
19467
19468    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19469        final PackageSetting ps;
19470        synchronized (mPackages) {
19471            ps = mSettings.mPackages.get(packageName);
19472            if (ps == null) {
19473                Slog.w(TAG, "Failed to find settings for " + packageName);
19474                return false;
19475            }
19476        }
19477
19478        final String[] packageNames = { packageName };
19479        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19480        final String[] codePaths = { ps.codePathString };
19481
19482        try {
19483            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19484                    ps.appId, ceDataInodes, codePaths, stats);
19485
19486            // For now, ignore code size of packages on system partition
19487            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19488                stats.codeSize = 0;
19489            }
19490
19491            // External clients expect these to be tracked separately
19492            stats.dataSize -= stats.cacheSize;
19493
19494        } catch (InstallerException e) {
19495            Slog.w(TAG, String.valueOf(e));
19496            return false;
19497        }
19498
19499        return true;
19500    }
19501
19502    private int getUidTargetSdkVersionLockedLPr(int uid) {
19503        Object obj = mSettings.getUserIdLPr(uid);
19504        if (obj instanceof SharedUserSetting) {
19505            final SharedUserSetting sus = (SharedUserSetting) obj;
19506            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19507            final Iterator<PackageSetting> it = sus.packages.iterator();
19508            while (it.hasNext()) {
19509                final PackageSetting ps = it.next();
19510                if (ps.pkg != null) {
19511                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19512                    if (v < vers) vers = v;
19513                }
19514            }
19515            return vers;
19516        } else if (obj instanceof PackageSetting) {
19517            final PackageSetting ps = (PackageSetting) obj;
19518            if (ps.pkg != null) {
19519                return ps.pkg.applicationInfo.targetSdkVersion;
19520            }
19521        }
19522        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19523    }
19524
19525    @Override
19526    public void addPreferredActivity(IntentFilter filter, int match,
19527            ComponentName[] set, ComponentName activity, int userId) {
19528        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19529                "Adding preferred");
19530    }
19531
19532    private void addPreferredActivityInternal(IntentFilter filter, int match,
19533            ComponentName[] set, ComponentName activity, boolean always, int userId,
19534            String opname) {
19535        // writer
19536        int callingUid = Binder.getCallingUid();
19537        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19538                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19539        if (filter.countActions() == 0) {
19540            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19541            return;
19542        }
19543        synchronized (mPackages) {
19544            if (mContext.checkCallingOrSelfPermission(
19545                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19546                    != PackageManager.PERMISSION_GRANTED) {
19547                if (getUidTargetSdkVersionLockedLPr(callingUid)
19548                        < Build.VERSION_CODES.FROYO) {
19549                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19550                            + callingUid);
19551                    return;
19552                }
19553                mContext.enforceCallingOrSelfPermission(
19554                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19555            }
19556
19557            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19558            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19559                    + userId + ":");
19560            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19561            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19562            scheduleWritePackageRestrictionsLocked(userId);
19563            postPreferredActivityChangedBroadcast(userId);
19564        }
19565    }
19566
19567    private void postPreferredActivityChangedBroadcast(int userId) {
19568        mHandler.post(() -> {
19569            final IActivityManager am = ActivityManager.getService();
19570            if (am == null) {
19571                return;
19572            }
19573
19574            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19575            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19576            try {
19577                am.broadcastIntent(null, intent, null, null,
19578                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19579                        null, false, false, userId);
19580            } catch (RemoteException e) {
19581            }
19582        });
19583    }
19584
19585    @Override
19586    public void replacePreferredActivity(IntentFilter filter, int match,
19587            ComponentName[] set, ComponentName activity, int userId) {
19588        if (filter.countActions() != 1) {
19589            throw new IllegalArgumentException(
19590                    "replacePreferredActivity expects filter to have only 1 action.");
19591        }
19592        if (filter.countDataAuthorities() != 0
19593                || filter.countDataPaths() != 0
19594                || filter.countDataSchemes() > 1
19595                || filter.countDataTypes() != 0) {
19596            throw new IllegalArgumentException(
19597                    "replacePreferredActivity expects filter to have no data authorities, " +
19598                    "paths, or types; and at most one scheme.");
19599        }
19600
19601        final int callingUid = Binder.getCallingUid();
19602        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19603                true /* requireFullPermission */, false /* checkShell */,
19604                "replace preferred activity");
19605        synchronized (mPackages) {
19606            if (mContext.checkCallingOrSelfPermission(
19607                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19608                    != PackageManager.PERMISSION_GRANTED) {
19609                if (getUidTargetSdkVersionLockedLPr(callingUid)
19610                        < Build.VERSION_CODES.FROYO) {
19611                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19612                            + Binder.getCallingUid());
19613                    return;
19614                }
19615                mContext.enforceCallingOrSelfPermission(
19616                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19617            }
19618
19619            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19620            if (pir != null) {
19621                // Get all of the existing entries that exactly match this filter.
19622                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19623                if (existing != null && existing.size() == 1) {
19624                    PreferredActivity cur = existing.get(0);
19625                    if (DEBUG_PREFERRED) {
19626                        Slog.i(TAG, "Checking replace of preferred:");
19627                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19628                        if (!cur.mPref.mAlways) {
19629                            Slog.i(TAG, "  -- CUR; not mAlways!");
19630                        } else {
19631                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19632                            Slog.i(TAG, "  -- CUR: mSet="
19633                                    + Arrays.toString(cur.mPref.mSetComponents));
19634                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19635                            Slog.i(TAG, "  -- NEW: mMatch="
19636                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19637                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19638                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19639                        }
19640                    }
19641                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19642                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19643                            && cur.mPref.sameSet(set)) {
19644                        // Setting the preferred activity to what it happens to be already
19645                        if (DEBUG_PREFERRED) {
19646                            Slog.i(TAG, "Replacing with same preferred activity "
19647                                    + cur.mPref.mShortComponent + " for user "
19648                                    + userId + ":");
19649                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19650                        }
19651                        return;
19652                    }
19653                }
19654
19655                if (existing != null) {
19656                    if (DEBUG_PREFERRED) {
19657                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19658                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19659                    }
19660                    for (int i = 0; i < existing.size(); i++) {
19661                        PreferredActivity pa = existing.get(i);
19662                        if (DEBUG_PREFERRED) {
19663                            Slog.i(TAG, "Removing existing preferred activity "
19664                                    + pa.mPref.mComponent + ":");
19665                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19666                        }
19667                        pir.removeFilter(pa);
19668                    }
19669                }
19670            }
19671            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19672                    "Replacing preferred");
19673        }
19674    }
19675
19676    @Override
19677    public void clearPackagePreferredActivities(String packageName) {
19678        final int callingUid = Binder.getCallingUid();
19679        if (getInstantAppPackageName(callingUid) != null) {
19680            return;
19681        }
19682        // writer
19683        synchronized (mPackages) {
19684            PackageParser.Package pkg = mPackages.get(packageName);
19685            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19686                if (mContext.checkCallingOrSelfPermission(
19687                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19688                        != PackageManager.PERMISSION_GRANTED) {
19689                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19690                            < Build.VERSION_CODES.FROYO) {
19691                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19692                                + callingUid);
19693                        return;
19694                    }
19695                    mContext.enforceCallingOrSelfPermission(
19696                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19697                }
19698            }
19699            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19700            if (ps != null
19701                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19702                return;
19703            }
19704            int user = UserHandle.getCallingUserId();
19705            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19706                scheduleWritePackageRestrictionsLocked(user);
19707            }
19708        }
19709    }
19710
19711    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19712    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19713        ArrayList<PreferredActivity> removed = null;
19714        boolean changed = false;
19715        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19716            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19717            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19718            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19719                continue;
19720            }
19721            Iterator<PreferredActivity> it = pir.filterIterator();
19722            while (it.hasNext()) {
19723                PreferredActivity pa = it.next();
19724                // Mark entry for removal only if it matches the package name
19725                // and the entry is of type "always".
19726                if (packageName == null ||
19727                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19728                                && pa.mPref.mAlways)) {
19729                    if (removed == null) {
19730                        removed = new ArrayList<PreferredActivity>();
19731                    }
19732                    removed.add(pa);
19733                }
19734            }
19735            if (removed != null) {
19736                for (int j=0; j<removed.size(); j++) {
19737                    PreferredActivity pa = removed.get(j);
19738                    pir.removeFilter(pa);
19739                }
19740                changed = true;
19741            }
19742        }
19743        if (changed) {
19744            postPreferredActivityChangedBroadcast(userId);
19745        }
19746        return changed;
19747    }
19748
19749    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19750    private void clearIntentFilterVerificationsLPw(int userId) {
19751        final int packageCount = mPackages.size();
19752        for (int i = 0; i < packageCount; i++) {
19753            PackageParser.Package pkg = mPackages.valueAt(i);
19754            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19755        }
19756    }
19757
19758    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19759    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19760        if (userId == UserHandle.USER_ALL) {
19761            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19762                    sUserManager.getUserIds())) {
19763                for (int oneUserId : sUserManager.getUserIds()) {
19764                    scheduleWritePackageRestrictionsLocked(oneUserId);
19765                }
19766            }
19767        } else {
19768            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19769                scheduleWritePackageRestrictionsLocked(userId);
19770            }
19771        }
19772    }
19773
19774    /** Clears state for all users, and touches intent filter verification policy */
19775    void clearDefaultBrowserIfNeeded(String packageName) {
19776        for (int oneUserId : sUserManager.getUserIds()) {
19777            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19778        }
19779    }
19780
19781    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19782        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19783        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19784            if (packageName.equals(defaultBrowserPackageName)) {
19785                setDefaultBrowserPackageName(null, userId);
19786            }
19787        }
19788    }
19789
19790    @Override
19791    public void resetApplicationPreferences(int userId) {
19792        mContext.enforceCallingOrSelfPermission(
19793                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19794        final long identity = Binder.clearCallingIdentity();
19795        // writer
19796        try {
19797            synchronized (mPackages) {
19798                clearPackagePreferredActivitiesLPw(null, userId);
19799                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19800                // TODO: We have to reset the default SMS and Phone. This requires
19801                // significant refactoring to keep all default apps in the package
19802                // manager (cleaner but more work) or have the services provide
19803                // callbacks to the package manager to request a default app reset.
19804                applyFactoryDefaultBrowserLPw(userId);
19805                clearIntentFilterVerificationsLPw(userId);
19806                primeDomainVerificationsLPw(userId);
19807                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19808                scheduleWritePackageRestrictionsLocked(userId);
19809            }
19810            resetNetworkPolicies(userId);
19811        } finally {
19812            Binder.restoreCallingIdentity(identity);
19813        }
19814    }
19815
19816    @Override
19817    public int getPreferredActivities(List<IntentFilter> outFilters,
19818            List<ComponentName> outActivities, String packageName) {
19819        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19820            return 0;
19821        }
19822        int num = 0;
19823        final int userId = UserHandle.getCallingUserId();
19824        // reader
19825        synchronized (mPackages) {
19826            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19827            if (pir != null) {
19828                final Iterator<PreferredActivity> it = pir.filterIterator();
19829                while (it.hasNext()) {
19830                    final PreferredActivity pa = it.next();
19831                    if (packageName == null
19832                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19833                                    && pa.mPref.mAlways)) {
19834                        if (outFilters != null) {
19835                            outFilters.add(new IntentFilter(pa));
19836                        }
19837                        if (outActivities != null) {
19838                            outActivities.add(pa.mPref.mComponent);
19839                        }
19840                    }
19841                }
19842            }
19843        }
19844
19845        return num;
19846    }
19847
19848    @Override
19849    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19850            int userId) {
19851        int callingUid = Binder.getCallingUid();
19852        if (callingUid != Process.SYSTEM_UID) {
19853            throw new SecurityException(
19854                    "addPersistentPreferredActivity can only be run by the system");
19855        }
19856        if (filter.countActions() == 0) {
19857            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19858            return;
19859        }
19860        synchronized (mPackages) {
19861            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19862                    ":");
19863            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19864            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19865                    new PersistentPreferredActivity(filter, activity));
19866            scheduleWritePackageRestrictionsLocked(userId);
19867            postPreferredActivityChangedBroadcast(userId);
19868        }
19869    }
19870
19871    @Override
19872    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19873        int callingUid = Binder.getCallingUid();
19874        if (callingUid != Process.SYSTEM_UID) {
19875            throw new SecurityException(
19876                    "clearPackagePersistentPreferredActivities can only be run by the system");
19877        }
19878        ArrayList<PersistentPreferredActivity> removed = null;
19879        boolean changed = false;
19880        synchronized (mPackages) {
19881            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19882                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19883                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19884                        .valueAt(i);
19885                if (userId != thisUserId) {
19886                    continue;
19887                }
19888                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19889                while (it.hasNext()) {
19890                    PersistentPreferredActivity ppa = it.next();
19891                    // Mark entry for removal only if it matches the package name.
19892                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19893                        if (removed == null) {
19894                            removed = new ArrayList<PersistentPreferredActivity>();
19895                        }
19896                        removed.add(ppa);
19897                    }
19898                }
19899                if (removed != null) {
19900                    for (int j=0; j<removed.size(); j++) {
19901                        PersistentPreferredActivity ppa = removed.get(j);
19902                        ppir.removeFilter(ppa);
19903                    }
19904                    changed = true;
19905                }
19906            }
19907
19908            if (changed) {
19909                scheduleWritePackageRestrictionsLocked(userId);
19910                postPreferredActivityChangedBroadcast(userId);
19911            }
19912        }
19913    }
19914
19915    /**
19916     * Common machinery for picking apart a restored XML blob and passing
19917     * it to a caller-supplied functor to be applied to the running system.
19918     */
19919    private void restoreFromXml(XmlPullParser parser, int userId,
19920            String expectedStartTag, BlobXmlRestorer functor)
19921            throws IOException, XmlPullParserException {
19922        int type;
19923        while ((type = parser.next()) != XmlPullParser.START_TAG
19924                && type != XmlPullParser.END_DOCUMENT) {
19925        }
19926        if (type != XmlPullParser.START_TAG) {
19927            // oops didn't find a start tag?!
19928            if (DEBUG_BACKUP) {
19929                Slog.e(TAG, "Didn't find start tag during restore");
19930            }
19931            return;
19932        }
19933Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19934        // this is supposed to be TAG_PREFERRED_BACKUP
19935        if (!expectedStartTag.equals(parser.getName())) {
19936            if (DEBUG_BACKUP) {
19937                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19938            }
19939            return;
19940        }
19941
19942        // skip interfering stuff, then we're aligned with the backing implementation
19943        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19944Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19945        functor.apply(parser, userId);
19946    }
19947
19948    private interface BlobXmlRestorer {
19949        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19950    }
19951
19952    /**
19953     * Non-Binder method, support for the backup/restore mechanism: write the
19954     * full set of preferred activities in its canonical XML format.  Returns the
19955     * XML output as a byte array, or null if there is none.
19956     */
19957    @Override
19958    public byte[] getPreferredActivityBackup(int userId) {
19959        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19960            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19961        }
19962
19963        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19964        try {
19965            final XmlSerializer serializer = new FastXmlSerializer();
19966            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19967            serializer.startDocument(null, true);
19968            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19969
19970            synchronized (mPackages) {
19971                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19972            }
19973
19974            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19975            serializer.endDocument();
19976            serializer.flush();
19977        } catch (Exception e) {
19978            if (DEBUG_BACKUP) {
19979                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19980            }
19981            return null;
19982        }
19983
19984        return dataStream.toByteArray();
19985    }
19986
19987    @Override
19988    public void restorePreferredActivities(byte[] backup, int userId) {
19989        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19990            throw new SecurityException("Only the system may call restorePreferredActivities()");
19991        }
19992
19993        try {
19994            final XmlPullParser parser = Xml.newPullParser();
19995            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19996            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19997                    new BlobXmlRestorer() {
19998                        @Override
19999                        public void apply(XmlPullParser parser, int userId)
20000                                throws XmlPullParserException, IOException {
20001                            synchronized (mPackages) {
20002                                mSettings.readPreferredActivitiesLPw(parser, userId);
20003                            }
20004                        }
20005                    } );
20006        } catch (Exception e) {
20007            if (DEBUG_BACKUP) {
20008                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20009            }
20010        }
20011    }
20012
20013    /**
20014     * Non-Binder method, support for the backup/restore mechanism: write the
20015     * default browser (etc) settings in its canonical XML format.  Returns the default
20016     * browser XML representation as a byte array, or null if there is none.
20017     */
20018    @Override
20019    public byte[] getDefaultAppsBackup(int userId) {
20020        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20021            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20022        }
20023
20024        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20025        try {
20026            final XmlSerializer serializer = new FastXmlSerializer();
20027            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20028            serializer.startDocument(null, true);
20029            serializer.startTag(null, TAG_DEFAULT_APPS);
20030
20031            synchronized (mPackages) {
20032                mSettings.writeDefaultAppsLPr(serializer, userId);
20033            }
20034
20035            serializer.endTag(null, TAG_DEFAULT_APPS);
20036            serializer.endDocument();
20037            serializer.flush();
20038        } catch (Exception e) {
20039            if (DEBUG_BACKUP) {
20040                Slog.e(TAG, "Unable to write default apps for backup", e);
20041            }
20042            return null;
20043        }
20044
20045        return dataStream.toByteArray();
20046    }
20047
20048    @Override
20049    public void restoreDefaultApps(byte[] backup, int userId) {
20050        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20051            throw new SecurityException("Only the system may call restoreDefaultApps()");
20052        }
20053
20054        try {
20055            final XmlPullParser parser = Xml.newPullParser();
20056            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20057            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20058                    new BlobXmlRestorer() {
20059                        @Override
20060                        public void apply(XmlPullParser parser, int userId)
20061                                throws XmlPullParserException, IOException {
20062                            synchronized (mPackages) {
20063                                mSettings.readDefaultAppsLPw(parser, userId);
20064                            }
20065                        }
20066                    } );
20067        } catch (Exception e) {
20068            if (DEBUG_BACKUP) {
20069                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20070            }
20071        }
20072    }
20073
20074    @Override
20075    public byte[] getIntentFilterVerificationBackup(int userId) {
20076        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20077            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20078        }
20079
20080        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20081        try {
20082            final XmlSerializer serializer = new FastXmlSerializer();
20083            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20084            serializer.startDocument(null, true);
20085            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20086
20087            synchronized (mPackages) {
20088                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20089            }
20090
20091            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20092            serializer.endDocument();
20093            serializer.flush();
20094        } catch (Exception e) {
20095            if (DEBUG_BACKUP) {
20096                Slog.e(TAG, "Unable to write default apps for backup", e);
20097            }
20098            return null;
20099        }
20100
20101        return dataStream.toByteArray();
20102    }
20103
20104    @Override
20105    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20106        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20107            throw new SecurityException("Only the system may call restorePreferredActivities()");
20108        }
20109
20110        try {
20111            final XmlPullParser parser = Xml.newPullParser();
20112            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20113            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20114                    new BlobXmlRestorer() {
20115                        @Override
20116                        public void apply(XmlPullParser parser, int userId)
20117                                throws XmlPullParserException, IOException {
20118                            synchronized (mPackages) {
20119                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20120                                mSettings.writeLPr();
20121                            }
20122                        }
20123                    } );
20124        } catch (Exception e) {
20125            if (DEBUG_BACKUP) {
20126                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20127            }
20128        }
20129    }
20130
20131    @Override
20132    public byte[] getPermissionGrantBackup(int userId) {
20133        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20134            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20135        }
20136
20137        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20138        try {
20139            final XmlSerializer serializer = new FastXmlSerializer();
20140            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20141            serializer.startDocument(null, true);
20142            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20143
20144            synchronized (mPackages) {
20145                serializeRuntimePermissionGrantsLPr(serializer, userId);
20146            }
20147
20148            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20149            serializer.endDocument();
20150            serializer.flush();
20151        } catch (Exception e) {
20152            if (DEBUG_BACKUP) {
20153                Slog.e(TAG, "Unable to write default apps for backup", e);
20154            }
20155            return null;
20156        }
20157
20158        return dataStream.toByteArray();
20159    }
20160
20161    @Override
20162    public void restorePermissionGrants(byte[] backup, int userId) {
20163        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20164            throw new SecurityException("Only the system may call restorePermissionGrants()");
20165        }
20166
20167        try {
20168            final XmlPullParser parser = Xml.newPullParser();
20169            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20170            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20171                    new BlobXmlRestorer() {
20172                        @Override
20173                        public void apply(XmlPullParser parser, int userId)
20174                                throws XmlPullParserException, IOException {
20175                            synchronized (mPackages) {
20176                                processRestoredPermissionGrantsLPr(parser, userId);
20177                            }
20178                        }
20179                    } );
20180        } catch (Exception e) {
20181            if (DEBUG_BACKUP) {
20182                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20183            }
20184        }
20185    }
20186
20187    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20188            throws IOException {
20189        serializer.startTag(null, TAG_ALL_GRANTS);
20190
20191        final int N = mSettings.mPackages.size();
20192        for (int i = 0; i < N; i++) {
20193            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20194            boolean pkgGrantsKnown = false;
20195
20196            PermissionsState packagePerms = ps.getPermissionsState();
20197
20198            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20199                final int grantFlags = state.getFlags();
20200                // only look at grants that are not system/policy fixed
20201                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20202                    final boolean isGranted = state.isGranted();
20203                    // And only back up the user-twiddled state bits
20204                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20205                        final String packageName = mSettings.mPackages.keyAt(i);
20206                        if (!pkgGrantsKnown) {
20207                            serializer.startTag(null, TAG_GRANT);
20208                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20209                            pkgGrantsKnown = true;
20210                        }
20211
20212                        final boolean userSet =
20213                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20214                        final boolean userFixed =
20215                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20216                        final boolean revoke =
20217                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20218
20219                        serializer.startTag(null, TAG_PERMISSION);
20220                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20221                        if (isGranted) {
20222                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20223                        }
20224                        if (userSet) {
20225                            serializer.attribute(null, ATTR_USER_SET, "true");
20226                        }
20227                        if (userFixed) {
20228                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20229                        }
20230                        if (revoke) {
20231                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20232                        }
20233                        serializer.endTag(null, TAG_PERMISSION);
20234                    }
20235                }
20236            }
20237
20238            if (pkgGrantsKnown) {
20239                serializer.endTag(null, TAG_GRANT);
20240            }
20241        }
20242
20243        serializer.endTag(null, TAG_ALL_GRANTS);
20244    }
20245
20246    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20247            throws XmlPullParserException, IOException {
20248        String pkgName = null;
20249        int outerDepth = parser.getDepth();
20250        int type;
20251        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20252                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20253            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20254                continue;
20255            }
20256
20257            final String tagName = parser.getName();
20258            if (tagName.equals(TAG_GRANT)) {
20259                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20260                if (DEBUG_BACKUP) {
20261                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20262                }
20263            } else if (tagName.equals(TAG_PERMISSION)) {
20264
20265                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20266                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20267
20268                int newFlagSet = 0;
20269                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20270                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20271                }
20272                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20273                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20274                }
20275                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20276                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20277                }
20278                if (DEBUG_BACKUP) {
20279                    Slog.v(TAG, "  + Restoring grant:"
20280                            + " pkg=" + pkgName
20281                            + " perm=" + permName
20282                            + " granted=" + isGranted
20283                            + " bits=0x" + Integer.toHexString(newFlagSet));
20284                }
20285                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20286                if (ps != null) {
20287                    // Already installed so we apply the grant immediately
20288                    if (DEBUG_BACKUP) {
20289                        Slog.v(TAG, "        + already installed; applying");
20290                    }
20291                    PermissionsState perms = ps.getPermissionsState();
20292                    BasePermission bp =
20293                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20294                    if (bp != null) {
20295                        if (isGranted) {
20296                            perms.grantRuntimePermission(bp, userId);
20297                        }
20298                        if (newFlagSet != 0) {
20299                            perms.updatePermissionFlags(
20300                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20301                        }
20302                    }
20303                } else {
20304                    // Need to wait for post-restore install to apply the grant
20305                    if (DEBUG_BACKUP) {
20306                        Slog.v(TAG, "        - not yet installed; saving for later");
20307                    }
20308                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20309                            isGranted, newFlagSet, userId);
20310                }
20311            } else {
20312                PackageManagerService.reportSettingsProblem(Log.WARN,
20313                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20314                XmlUtils.skipCurrentTag(parser);
20315            }
20316        }
20317
20318        scheduleWriteSettingsLocked();
20319        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20320    }
20321
20322    @Override
20323    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20324            int sourceUserId, int targetUserId, int flags) {
20325        mContext.enforceCallingOrSelfPermission(
20326                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20327        int callingUid = Binder.getCallingUid();
20328        enforceOwnerRights(ownerPackage, callingUid);
20329        PackageManagerServiceUtils.enforceShellRestriction(
20330                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20331        if (intentFilter.countActions() == 0) {
20332            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20333            return;
20334        }
20335        synchronized (mPackages) {
20336            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20337                    ownerPackage, targetUserId, flags);
20338            CrossProfileIntentResolver resolver =
20339                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20340            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20341            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20342            if (existing != null) {
20343                int size = existing.size();
20344                for (int i = 0; i < size; i++) {
20345                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20346                        return;
20347                    }
20348                }
20349            }
20350            resolver.addFilter(newFilter);
20351            scheduleWritePackageRestrictionsLocked(sourceUserId);
20352        }
20353    }
20354
20355    @Override
20356    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20357        mContext.enforceCallingOrSelfPermission(
20358                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20359        final int callingUid = Binder.getCallingUid();
20360        enforceOwnerRights(ownerPackage, callingUid);
20361        PackageManagerServiceUtils.enforceShellRestriction(
20362                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20363        synchronized (mPackages) {
20364            CrossProfileIntentResolver resolver =
20365                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20366            ArraySet<CrossProfileIntentFilter> set =
20367                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20368            for (CrossProfileIntentFilter filter : set) {
20369                if (filter.getOwnerPackage().equals(ownerPackage)) {
20370                    resolver.removeFilter(filter);
20371                }
20372            }
20373            scheduleWritePackageRestrictionsLocked(sourceUserId);
20374        }
20375    }
20376
20377    // Enforcing that callingUid is owning pkg on userId
20378    private void enforceOwnerRights(String pkg, int callingUid) {
20379        // The system owns everything.
20380        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20381            return;
20382        }
20383        final int callingUserId = UserHandle.getUserId(callingUid);
20384        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20385        if (pi == null) {
20386            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20387                    + callingUserId);
20388        }
20389        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20390            throw new SecurityException("Calling uid " + callingUid
20391                    + " does not own package " + pkg);
20392        }
20393    }
20394
20395    @Override
20396    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20397        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20398            return null;
20399        }
20400        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20401    }
20402
20403    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20404        UserManagerService ums = UserManagerService.getInstance();
20405        if (ums != null) {
20406            final UserInfo parent = ums.getProfileParent(userId);
20407            final int launcherUid = (parent != null) ? parent.id : userId;
20408            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20409            if (launcherComponent != null) {
20410                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20411                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20412                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20413                        .setPackage(launcherComponent.getPackageName());
20414                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20415            }
20416        }
20417    }
20418
20419    /**
20420     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20421     * then reports the most likely home activity or null if there are more than one.
20422     */
20423    private ComponentName getDefaultHomeActivity(int userId) {
20424        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20425        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20426        if (cn != null) {
20427            return cn;
20428        }
20429
20430        // Find the launcher with the highest priority and return that component if there are no
20431        // other home activity with the same priority.
20432        int lastPriority = Integer.MIN_VALUE;
20433        ComponentName lastComponent = null;
20434        final int size = allHomeCandidates.size();
20435        for (int i = 0; i < size; i++) {
20436            final ResolveInfo ri = allHomeCandidates.get(i);
20437            if (ri.priority > lastPriority) {
20438                lastComponent = ri.activityInfo.getComponentName();
20439                lastPriority = ri.priority;
20440            } else if (ri.priority == lastPriority) {
20441                // Two components found with same priority.
20442                lastComponent = null;
20443            }
20444        }
20445        return lastComponent;
20446    }
20447
20448    private Intent getHomeIntent() {
20449        Intent intent = new Intent(Intent.ACTION_MAIN);
20450        intent.addCategory(Intent.CATEGORY_HOME);
20451        intent.addCategory(Intent.CATEGORY_DEFAULT);
20452        return intent;
20453    }
20454
20455    private IntentFilter getHomeFilter() {
20456        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20457        filter.addCategory(Intent.CATEGORY_HOME);
20458        filter.addCategory(Intent.CATEGORY_DEFAULT);
20459        return filter;
20460    }
20461
20462    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20463            int userId) {
20464        Intent intent  = getHomeIntent();
20465        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20466                PackageManager.GET_META_DATA, userId);
20467        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20468                true, false, false, userId);
20469
20470        allHomeCandidates.clear();
20471        if (list != null) {
20472            for (ResolveInfo ri : list) {
20473                allHomeCandidates.add(ri);
20474            }
20475        }
20476        return (preferred == null || preferred.activityInfo == null)
20477                ? null
20478                : new ComponentName(preferred.activityInfo.packageName,
20479                        preferred.activityInfo.name);
20480    }
20481
20482    @Override
20483    public void setHomeActivity(ComponentName comp, int userId) {
20484        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20485            return;
20486        }
20487        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20488        getHomeActivitiesAsUser(homeActivities, userId);
20489
20490        boolean found = false;
20491
20492        final int size = homeActivities.size();
20493        final ComponentName[] set = new ComponentName[size];
20494        for (int i = 0; i < size; i++) {
20495            final ResolveInfo candidate = homeActivities.get(i);
20496            final ActivityInfo info = candidate.activityInfo;
20497            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20498            set[i] = activityName;
20499            if (!found && activityName.equals(comp)) {
20500                found = true;
20501            }
20502        }
20503        if (!found) {
20504            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20505                    + userId);
20506        }
20507        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20508                set, comp, userId);
20509    }
20510
20511    private @Nullable String getSetupWizardPackageName() {
20512        final Intent intent = new Intent(Intent.ACTION_MAIN);
20513        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20514
20515        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20516                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20517                        | MATCH_DISABLED_COMPONENTS,
20518                UserHandle.myUserId());
20519        if (matches.size() == 1) {
20520            return matches.get(0).getComponentInfo().packageName;
20521        } else {
20522            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20523                    + ": matches=" + matches);
20524            return null;
20525        }
20526    }
20527
20528    private @Nullable String getStorageManagerPackageName() {
20529        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20530
20531        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20532                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20533                        | MATCH_DISABLED_COMPONENTS,
20534                UserHandle.myUserId());
20535        if (matches.size() == 1) {
20536            return matches.get(0).getComponentInfo().packageName;
20537        } else {
20538            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20539                    + matches.size() + ": matches=" + matches);
20540            return null;
20541        }
20542    }
20543
20544    @Override
20545    public void setApplicationEnabledSetting(String appPackageName,
20546            int newState, int flags, int userId, String callingPackage) {
20547        if (!sUserManager.exists(userId)) return;
20548        if (callingPackage == null) {
20549            callingPackage = Integer.toString(Binder.getCallingUid());
20550        }
20551        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20552    }
20553
20554    @Override
20555    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20556        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20557        synchronized (mPackages) {
20558            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20559            if (pkgSetting != null) {
20560                pkgSetting.setUpdateAvailable(updateAvailable);
20561            }
20562        }
20563    }
20564
20565    @Override
20566    public void setComponentEnabledSetting(ComponentName componentName,
20567            int newState, int flags, int userId) {
20568        if (!sUserManager.exists(userId)) return;
20569        setEnabledSetting(componentName.getPackageName(),
20570                componentName.getClassName(), newState, flags, userId, null);
20571    }
20572
20573    private void setEnabledSetting(final String packageName, String className, int newState,
20574            final int flags, int userId, String callingPackage) {
20575        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20576              || newState == COMPONENT_ENABLED_STATE_ENABLED
20577              || newState == COMPONENT_ENABLED_STATE_DISABLED
20578              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20579              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20580            throw new IllegalArgumentException("Invalid new component state: "
20581                    + newState);
20582        }
20583        PackageSetting pkgSetting;
20584        final int callingUid = Binder.getCallingUid();
20585        final int permission;
20586        if (callingUid == Process.SYSTEM_UID) {
20587            permission = PackageManager.PERMISSION_GRANTED;
20588        } else {
20589            permission = mContext.checkCallingOrSelfPermission(
20590                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20591        }
20592        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20593                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20594        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20595        boolean sendNow = false;
20596        boolean isApp = (className == null);
20597        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20598        String componentName = isApp ? packageName : className;
20599        int packageUid = -1;
20600        ArrayList<String> components;
20601
20602        // reader
20603        synchronized (mPackages) {
20604            pkgSetting = mSettings.mPackages.get(packageName);
20605            if (pkgSetting == null) {
20606                if (!isCallerInstantApp) {
20607                    if (className == null) {
20608                        throw new IllegalArgumentException("Unknown package: " + packageName);
20609                    }
20610                    throw new IllegalArgumentException(
20611                            "Unknown component: " + packageName + "/" + className);
20612                } else {
20613                    // throw SecurityException to prevent leaking package information
20614                    throw new SecurityException(
20615                            "Attempt to change component state; "
20616                            + "pid=" + Binder.getCallingPid()
20617                            + ", uid=" + callingUid
20618                            + (className == null
20619                                    ? ", package=" + packageName
20620                                    : ", component=" + packageName + "/" + className));
20621                }
20622            }
20623        }
20624
20625        // Limit who can change which apps
20626        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20627            // Don't allow apps that don't have permission to modify other apps
20628            if (!allowedByPermission
20629                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20630                throw new SecurityException(
20631                        "Attempt to change component state; "
20632                        + "pid=" + Binder.getCallingPid()
20633                        + ", uid=" + callingUid
20634                        + (className == null
20635                                ? ", package=" + packageName
20636                                : ", component=" + packageName + "/" + className));
20637            }
20638            // Don't allow changing protected packages.
20639            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20640                throw new SecurityException("Cannot disable a protected package: " + packageName);
20641            }
20642        }
20643
20644        synchronized (mPackages) {
20645            if (callingUid == Process.SHELL_UID
20646                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20647                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20648                // unless it is a test package.
20649                int oldState = pkgSetting.getEnabled(userId);
20650                if (className == null
20651                        &&
20652                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20653                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20654                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20655                        &&
20656                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20657                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20658                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20659                    // ok
20660                } else {
20661                    throw new SecurityException(
20662                            "Shell cannot change component state for " + packageName + "/"
20663                                    + className + " to " + newState);
20664                }
20665            }
20666        }
20667        if (className == null) {
20668            // We're dealing with an application/package level state change
20669            synchronized (mPackages) {
20670                if (pkgSetting.getEnabled(userId) == newState) {
20671                    // Nothing to do
20672                    return;
20673                }
20674            }
20675            // If we're enabling a system stub, there's a little more work to do.
20676            // Prior to enabling the package, we need to decompress the APK(s) to the
20677            // data partition and then replace the version on the system partition.
20678            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20679            final boolean isSystemStub = deletedPkg.isStub
20680                    && deletedPkg.isSystemApp();
20681            if (isSystemStub
20682                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20683                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20684                final File codePath = decompressPackage(deletedPkg);
20685                if (codePath == null) {
20686                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20687                    return;
20688                }
20689                // TODO remove direct parsing of the package object during internal cleanup
20690                // of scan package
20691                // We need to call parse directly here for no other reason than we need
20692                // the new package in order to disable the old one [we use the information
20693                // for some internal optimization to optionally create a new package setting
20694                // object on replace]. However, we can't get the package from the scan
20695                // because the scan modifies live structures and we need to remove the
20696                // old [system] package from the system before a scan can be attempted.
20697                // Once scan is indempotent we can remove this parse and use the package
20698                // object we scanned, prior to adding it to package settings.
20699                final PackageParser pp = new PackageParser();
20700                pp.setSeparateProcesses(mSeparateProcesses);
20701                pp.setDisplayMetrics(mMetrics);
20702                pp.setCallback(mPackageParserCallback);
20703                final PackageParser.Package tmpPkg;
20704                try {
20705                    final int parseFlags = mDefParseFlags
20706                            | PackageParser.PARSE_MUST_BE_APK
20707                            | PackageParser.PARSE_IS_SYSTEM
20708                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20709                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20710                } catch (PackageParserException e) {
20711                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20712                    return;
20713                }
20714                synchronized (mInstallLock) {
20715                    // Disable the stub and remove any package entries
20716                    removePackageLI(deletedPkg, true);
20717                    synchronized (mPackages) {
20718                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20719                    }
20720                    final PackageParser.Package newPkg;
20721                    try (PackageFreezer freezer =
20722                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20723                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20724                                | PackageParser.PARSE_ENFORCE_CODE;
20725                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20726                                0 /*currentTime*/, null /*user*/);
20727                        prepareAppDataAfterInstallLIF(newPkg);
20728                        synchronized (mPackages) {
20729                            try {
20730                                updateSharedLibrariesLPr(newPkg, null);
20731                            } catch (PackageManagerException e) {
20732                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20733                            }
20734                            updatePermissionsLPw(newPkg.packageName, newPkg,
20735                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
20736                            mSettings.writeLPr();
20737                        }
20738                    } catch (PackageManagerException e) {
20739                        // Whoops! Something went wrong; try to roll back to the stub
20740                        Slog.w(TAG, "Failed to install compressed system package:"
20741                                + pkgSetting.name, e);
20742                        // Remove the failed install
20743                        removeCodePathLI(codePath);
20744
20745                        // Install the system package
20746                        try (PackageFreezer freezer =
20747                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20748                            synchronized (mPackages) {
20749                                // NOTE: The system package always needs to be enabled; even
20750                                // if it's for a compressed stub. If we don't, installing the
20751                                // system package fails during scan [scanning checks the disabled
20752                                // packages]. We will reverse this later, after we've "installed"
20753                                // the stub.
20754                                // This leaves us in a fragile state; the stub should never be
20755                                // enabled, so, cross your fingers and hope nothing goes wrong
20756                                // until we can disable the package later.
20757                                enableSystemPackageLPw(deletedPkg);
20758                            }
20759                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
20760                                    false /*isPrivileged*/, null /*allUserHandles*/,
20761                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20762                                    true /*writeSettings*/);
20763                        } catch (PackageManagerException pme) {
20764                            Slog.w(TAG, "Failed to restore system package:"
20765                                    + deletedPkg.packageName, pme);
20766                        } finally {
20767                            synchronized (mPackages) {
20768                                mSettings.disableSystemPackageLPw(
20769                                        deletedPkg.packageName, true /*replaced*/);
20770                                mSettings.writeLPr();
20771                            }
20772                        }
20773                        return;
20774                    }
20775                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20776                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20777                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
20778                    mDexManager.notifyPackageUpdated(newPkg.packageName,
20779                            newPkg.baseCodePath, newPkg.splitCodePaths);
20780                }
20781            }
20782            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20783                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20784                // Don't care about who enables an app.
20785                callingPackage = null;
20786            }
20787            synchronized (mPackages) {
20788                pkgSetting.setEnabled(newState, userId, callingPackage);
20789            }
20790        } else {
20791            synchronized (mPackages) {
20792                // We're dealing with a component level state change
20793                // First, verify that this is a valid class name.
20794                PackageParser.Package pkg = pkgSetting.pkg;
20795                if (pkg == null || !pkg.hasComponentClassName(className)) {
20796                    if (pkg != null &&
20797                            pkg.applicationInfo.targetSdkVersion >=
20798                                    Build.VERSION_CODES.JELLY_BEAN) {
20799                        throw new IllegalArgumentException("Component class " + className
20800                                + " does not exist in " + packageName);
20801                    } else {
20802                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20803                                + className + " does not exist in " + packageName);
20804                    }
20805                }
20806                switch (newState) {
20807                    case COMPONENT_ENABLED_STATE_ENABLED:
20808                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20809                            return;
20810                        }
20811                        break;
20812                    case COMPONENT_ENABLED_STATE_DISABLED:
20813                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20814                            return;
20815                        }
20816                        break;
20817                    case COMPONENT_ENABLED_STATE_DEFAULT:
20818                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20819                            return;
20820                        }
20821                        break;
20822                    default:
20823                        Slog.e(TAG, "Invalid new component state: " + newState);
20824                        return;
20825                }
20826            }
20827        }
20828        synchronized (mPackages) {
20829            scheduleWritePackageRestrictionsLocked(userId);
20830            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20831            final long callingId = Binder.clearCallingIdentity();
20832            try {
20833                updateInstantAppInstallerLocked(packageName);
20834            } finally {
20835                Binder.restoreCallingIdentity(callingId);
20836            }
20837            components = mPendingBroadcasts.get(userId, packageName);
20838            final boolean newPackage = components == null;
20839            if (newPackage) {
20840                components = new ArrayList<String>();
20841            }
20842            if (!components.contains(componentName)) {
20843                components.add(componentName);
20844            }
20845            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20846                sendNow = true;
20847                // Purge entry from pending broadcast list if another one exists already
20848                // since we are sending one right away.
20849                mPendingBroadcasts.remove(userId, packageName);
20850            } else {
20851                if (newPackage) {
20852                    mPendingBroadcasts.put(userId, packageName, components);
20853                }
20854                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20855                    // Schedule a message
20856                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20857                }
20858            }
20859        }
20860
20861        long callingId = Binder.clearCallingIdentity();
20862        try {
20863            if (sendNow) {
20864                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20865                sendPackageChangedBroadcast(packageName,
20866                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20867            }
20868        } finally {
20869            Binder.restoreCallingIdentity(callingId);
20870        }
20871    }
20872
20873    @Override
20874    public void flushPackageRestrictionsAsUser(int userId) {
20875        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20876            return;
20877        }
20878        if (!sUserManager.exists(userId)) {
20879            return;
20880        }
20881        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20882                false /* checkShell */, "flushPackageRestrictions");
20883        synchronized (mPackages) {
20884            mSettings.writePackageRestrictionsLPr(userId);
20885            mDirtyUsers.remove(userId);
20886            if (mDirtyUsers.isEmpty()) {
20887                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20888            }
20889        }
20890    }
20891
20892    private void sendPackageChangedBroadcast(String packageName,
20893            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20894        if (DEBUG_INSTALL)
20895            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20896                    + componentNames);
20897        Bundle extras = new Bundle(4);
20898        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20899        String nameList[] = new String[componentNames.size()];
20900        componentNames.toArray(nameList);
20901        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20902        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20903        extras.putInt(Intent.EXTRA_UID, packageUid);
20904        // If this is not reporting a change of the overall package, then only send it
20905        // to registered receivers.  We don't want to launch a swath of apps for every
20906        // little component state change.
20907        final int flags = !componentNames.contains(packageName)
20908                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20909        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20910                new int[] {UserHandle.getUserId(packageUid)});
20911    }
20912
20913    @Override
20914    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20915        if (!sUserManager.exists(userId)) return;
20916        final int callingUid = Binder.getCallingUid();
20917        if (getInstantAppPackageName(callingUid) != null) {
20918            return;
20919        }
20920        final int permission = mContext.checkCallingOrSelfPermission(
20921                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20922        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20923        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20924                true /* requireFullPermission */, true /* checkShell */, "stop package");
20925        // writer
20926        synchronized (mPackages) {
20927            final PackageSetting ps = mSettings.mPackages.get(packageName);
20928            if (!filterAppAccessLPr(ps, callingUid, userId)
20929                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20930                            allowedByPermission, callingUid, userId)) {
20931                scheduleWritePackageRestrictionsLocked(userId);
20932            }
20933        }
20934    }
20935
20936    @Override
20937    public String getInstallerPackageName(String packageName) {
20938        final int callingUid = Binder.getCallingUid();
20939        if (getInstantAppPackageName(callingUid) != null) {
20940            return null;
20941        }
20942        // reader
20943        synchronized (mPackages) {
20944            final PackageSetting ps = mSettings.mPackages.get(packageName);
20945            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20946                return null;
20947            }
20948            return mSettings.getInstallerPackageNameLPr(packageName);
20949        }
20950    }
20951
20952    public boolean isOrphaned(String packageName) {
20953        // reader
20954        synchronized (mPackages) {
20955            return mSettings.isOrphaned(packageName);
20956        }
20957    }
20958
20959    @Override
20960    public int getApplicationEnabledSetting(String packageName, int userId) {
20961        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20962        int callingUid = Binder.getCallingUid();
20963        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20964                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20965        // reader
20966        synchronized (mPackages) {
20967            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20968                return COMPONENT_ENABLED_STATE_DISABLED;
20969            }
20970            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20971        }
20972    }
20973
20974    @Override
20975    public int getComponentEnabledSetting(ComponentName component, int userId) {
20976        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20977        int callingUid = Binder.getCallingUid();
20978        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20979                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20980        synchronized (mPackages) {
20981            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20982                    component, TYPE_UNKNOWN, userId)) {
20983                return COMPONENT_ENABLED_STATE_DISABLED;
20984            }
20985            return mSettings.getComponentEnabledSettingLPr(component, userId);
20986        }
20987    }
20988
20989    @Override
20990    public void enterSafeMode() {
20991        enforceSystemOrRoot("Only the system can request entering safe mode");
20992
20993        if (!mSystemReady) {
20994            mSafeMode = true;
20995        }
20996    }
20997
20998    @Override
20999    public void systemReady() {
21000        enforceSystemOrRoot("Only the system can claim the system is ready");
21001
21002        mSystemReady = true;
21003        final ContentResolver resolver = mContext.getContentResolver();
21004        ContentObserver co = new ContentObserver(mHandler) {
21005            @Override
21006            public void onChange(boolean selfChange) {
21007                mEphemeralAppsDisabled =
21008                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21009                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21010            }
21011        };
21012        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21013                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21014                false, co, UserHandle.USER_SYSTEM);
21015        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21016                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21017        co.onChange(true);
21018
21019        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21020        // disabled after already being started.
21021        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21022                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21023
21024        // Read the compatibilty setting when the system is ready.
21025        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21026                mContext.getContentResolver(),
21027                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21028        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21029        if (DEBUG_SETTINGS) {
21030            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21031        }
21032
21033        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21034
21035        synchronized (mPackages) {
21036            // Verify that all of the preferred activity components actually
21037            // exist.  It is possible for applications to be updated and at
21038            // that point remove a previously declared activity component that
21039            // had been set as a preferred activity.  We try to clean this up
21040            // the next time we encounter that preferred activity, but it is
21041            // possible for the user flow to never be able to return to that
21042            // situation so here we do a sanity check to make sure we haven't
21043            // left any junk around.
21044            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21045            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21046                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21047                removed.clear();
21048                for (PreferredActivity pa : pir.filterSet()) {
21049                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21050                        removed.add(pa);
21051                    }
21052                }
21053                if (removed.size() > 0) {
21054                    for (int r=0; r<removed.size(); r++) {
21055                        PreferredActivity pa = removed.get(r);
21056                        Slog.w(TAG, "Removing dangling preferred activity: "
21057                                + pa.mPref.mComponent);
21058                        pir.removeFilter(pa);
21059                    }
21060                    mSettings.writePackageRestrictionsLPr(
21061                            mSettings.mPreferredActivities.keyAt(i));
21062                }
21063            }
21064
21065            for (int userId : UserManagerService.getInstance().getUserIds()) {
21066                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21067                    grantPermissionsUserIds = ArrayUtils.appendInt(
21068                            grantPermissionsUserIds, userId);
21069                }
21070            }
21071        }
21072        sUserManager.systemReady();
21073
21074        // If we upgraded grant all default permissions before kicking off.
21075        for (int userId : grantPermissionsUserIds) {
21076            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
21077        }
21078
21079        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21080            // If we did not grant default permissions, we preload from this the
21081            // default permission exceptions lazily to ensure we don't hit the
21082            // disk on a new user creation.
21083            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21084        }
21085
21086        // Now that we've scanned all packages, and granted any default
21087        // permissions, ensure permissions are updated. Beware of dragons if you
21088        // try optimizing this.
21089        synchronized (mPackages) {
21090            updatePermissionsLocked(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
21091                    UPDATE_PERMISSIONS_ALL);
21092        }
21093
21094        // Kick off any messages waiting for system ready
21095        if (mPostSystemReadyMessages != null) {
21096            for (Message msg : mPostSystemReadyMessages) {
21097                msg.sendToTarget();
21098            }
21099            mPostSystemReadyMessages = null;
21100        }
21101
21102        // Watch for external volumes that come and go over time
21103        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21104        storage.registerListener(mStorageListener);
21105
21106        mInstallerService.systemReady();
21107        mPackageDexOptimizer.systemReady();
21108
21109        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21110                StorageManagerInternal.class);
21111        StorageManagerInternal.addExternalStoragePolicy(
21112                new StorageManagerInternal.ExternalStorageMountPolicy() {
21113            @Override
21114            public int getMountMode(int uid, String packageName) {
21115                if (Process.isIsolated(uid)) {
21116                    return Zygote.MOUNT_EXTERNAL_NONE;
21117                }
21118                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21119                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21120                }
21121                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21122                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21123                }
21124                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21125                    return Zygote.MOUNT_EXTERNAL_READ;
21126                }
21127                return Zygote.MOUNT_EXTERNAL_WRITE;
21128            }
21129
21130            @Override
21131            public boolean hasExternalStorage(int uid, String packageName) {
21132                return true;
21133            }
21134        });
21135
21136        // Now that we're mostly running, clean up stale users and apps
21137        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21138        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21139
21140        if (mPrivappPermissionsViolations != null) {
21141            throw new IllegalStateException("Signature|privileged permissions not in "
21142                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21143        }
21144    }
21145
21146    public void waitForAppDataPrepared() {
21147        if (mPrepareAppDataFuture == null) {
21148            return;
21149        }
21150        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21151        mPrepareAppDataFuture = null;
21152    }
21153
21154    @Override
21155    public boolean isSafeMode() {
21156        // allow instant applications
21157        return mSafeMode;
21158    }
21159
21160    @Override
21161    public boolean hasSystemUidErrors() {
21162        // allow instant applications
21163        return mHasSystemUidErrors;
21164    }
21165
21166    static String arrayToString(int[] array) {
21167        StringBuffer buf = new StringBuffer(128);
21168        buf.append('[');
21169        if (array != null) {
21170            for (int i=0; i<array.length; i++) {
21171                if (i > 0) buf.append(", ");
21172                buf.append(array[i]);
21173            }
21174        }
21175        buf.append(']');
21176        return buf.toString();
21177    }
21178
21179    @Override
21180    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21181            FileDescriptor err, String[] args, ShellCallback callback,
21182            ResultReceiver resultReceiver) {
21183        (new PackageManagerShellCommand(this)).exec(
21184                this, in, out, err, args, callback, resultReceiver);
21185    }
21186
21187    @Override
21188    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21189        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21190
21191        DumpState dumpState = new DumpState();
21192        boolean fullPreferred = false;
21193        boolean checkin = false;
21194
21195        String packageName = null;
21196        ArraySet<String> permissionNames = null;
21197
21198        int opti = 0;
21199        while (opti < args.length) {
21200            String opt = args[opti];
21201            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21202                break;
21203            }
21204            opti++;
21205
21206            if ("-a".equals(opt)) {
21207                // Right now we only know how to print all.
21208            } else if ("-h".equals(opt)) {
21209                pw.println("Package manager dump options:");
21210                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21211                pw.println("    --checkin: dump for a checkin");
21212                pw.println("    -f: print details of intent filters");
21213                pw.println("    -h: print this help");
21214                pw.println("  cmd may be one of:");
21215                pw.println("    l[ibraries]: list known shared libraries");
21216                pw.println("    f[eatures]: list device features");
21217                pw.println("    k[eysets]: print known keysets");
21218                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21219                pw.println("    perm[issions]: dump permissions");
21220                pw.println("    permission [name ...]: dump declaration and use of given permission");
21221                pw.println("    pref[erred]: print preferred package settings");
21222                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21223                pw.println("    prov[iders]: dump content providers");
21224                pw.println("    p[ackages]: dump installed packages");
21225                pw.println("    s[hared-users]: dump shared user IDs");
21226                pw.println("    m[essages]: print collected runtime messages");
21227                pw.println("    v[erifiers]: print package verifier info");
21228                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21229                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21230                pw.println("    version: print database version info");
21231                pw.println("    write: write current settings now");
21232                pw.println("    installs: details about install sessions");
21233                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21234                pw.println("    dexopt: dump dexopt state");
21235                pw.println("    compiler-stats: dump compiler statistics");
21236                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21237                pw.println("    <package.name>: info about given package");
21238                return;
21239            } else if ("--checkin".equals(opt)) {
21240                checkin = true;
21241            } else if ("-f".equals(opt)) {
21242                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21243            } else if ("--proto".equals(opt)) {
21244                dumpProto(fd);
21245                return;
21246            } else {
21247                pw.println("Unknown argument: " + opt + "; use -h for help");
21248            }
21249        }
21250
21251        // Is the caller requesting to dump a particular piece of data?
21252        if (opti < args.length) {
21253            String cmd = args[opti];
21254            opti++;
21255            // Is this a package name?
21256            if ("android".equals(cmd) || cmd.contains(".")) {
21257                packageName = cmd;
21258                // When dumping a single package, we always dump all of its
21259                // filter information since the amount of data will be reasonable.
21260                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21261            } else if ("check-permission".equals(cmd)) {
21262                if (opti >= args.length) {
21263                    pw.println("Error: check-permission missing permission argument");
21264                    return;
21265                }
21266                String perm = args[opti];
21267                opti++;
21268                if (opti >= args.length) {
21269                    pw.println("Error: check-permission missing package argument");
21270                    return;
21271                }
21272
21273                String pkg = args[opti];
21274                opti++;
21275                int user = UserHandle.getUserId(Binder.getCallingUid());
21276                if (opti < args.length) {
21277                    try {
21278                        user = Integer.parseInt(args[opti]);
21279                    } catch (NumberFormatException e) {
21280                        pw.println("Error: check-permission user argument is not a number: "
21281                                + args[opti]);
21282                        return;
21283                    }
21284                }
21285
21286                // Normalize package name to handle renamed packages and static libs
21287                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21288
21289                pw.println(checkPermission(perm, pkg, user));
21290                return;
21291            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21292                dumpState.setDump(DumpState.DUMP_LIBS);
21293            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21294                dumpState.setDump(DumpState.DUMP_FEATURES);
21295            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21296                if (opti >= args.length) {
21297                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21298                            | DumpState.DUMP_SERVICE_RESOLVERS
21299                            | DumpState.DUMP_RECEIVER_RESOLVERS
21300                            | DumpState.DUMP_CONTENT_RESOLVERS);
21301                } else {
21302                    while (opti < args.length) {
21303                        String name = args[opti];
21304                        if ("a".equals(name) || "activity".equals(name)) {
21305                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21306                        } else if ("s".equals(name) || "service".equals(name)) {
21307                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21308                        } else if ("r".equals(name) || "receiver".equals(name)) {
21309                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21310                        } else if ("c".equals(name) || "content".equals(name)) {
21311                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21312                        } else {
21313                            pw.println("Error: unknown resolver table type: " + name);
21314                            return;
21315                        }
21316                        opti++;
21317                    }
21318                }
21319            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21320                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21321            } else if ("permission".equals(cmd)) {
21322                if (opti >= args.length) {
21323                    pw.println("Error: permission requires permission name");
21324                    return;
21325                }
21326                permissionNames = new ArraySet<>();
21327                while (opti < args.length) {
21328                    permissionNames.add(args[opti]);
21329                    opti++;
21330                }
21331                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21332                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21333            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21334                dumpState.setDump(DumpState.DUMP_PREFERRED);
21335            } else if ("preferred-xml".equals(cmd)) {
21336                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21337                if (opti < args.length && "--full".equals(args[opti])) {
21338                    fullPreferred = true;
21339                    opti++;
21340                }
21341            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21342                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21343            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21344                dumpState.setDump(DumpState.DUMP_PACKAGES);
21345            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21346                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21347            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21348                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21349            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21350                dumpState.setDump(DumpState.DUMP_MESSAGES);
21351            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21352                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21353            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21354                    || "intent-filter-verifiers".equals(cmd)) {
21355                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21356            } else if ("version".equals(cmd)) {
21357                dumpState.setDump(DumpState.DUMP_VERSION);
21358            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21359                dumpState.setDump(DumpState.DUMP_KEYSETS);
21360            } else if ("installs".equals(cmd)) {
21361                dumpState.setDump(DumpState.DUMP_INSTALLS);
21362            } else if ("frozen".equals(cmd)) {
21363                dumpState.setDump(DumpState.DUMP_FROZEN);
21364            } else if ("volumes".equals(cmd)) {
21365                dumpState.setDump(DumpState.DUMP_VOLUMES);
21366            } else if ("dexopt".equals(cmd)) {
21367                dumpState.setDump(DumpState.DUMP_DEXOPT);
21368            } else if ("compiler-stats".equals(cmd)) {
21369                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21370            } else if ("changes".equals(cmd)) {
21371                dumpState.setDump(DumpState.DUMP_CHANGES);
21372            } else if ("write".equals(cmd)) {
21373                synchronized (mPackages) {
21374                    mSettings.writeLPr();
21375                    pw.println("Settings written.");
21376                    return;
21377                }
21378            }
21379        }
21380
21381        if (checkin) {
21382            pw.println("vers,1");
21383        }
21384
21385        // reader
21386        synchronized (mPackages) {
21387            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21388                if (!checkin) {
21389                    if (dumpState.onTitlePrinted())
21390                        pw.println();
21391                    pw.println("Database versions:");
21392                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21393                }
21394            }
21395
21396            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21397                if (!checkin) {
21398                    if (dumpState.onTitlePrinted())
21399                        pw.println();
21400                    pw.println("Verifiers:");
21401                    pw.print("  Required: ");
21402                    pw.print(mRequiredVerifierPackage);
21403                    pw.print(" (uid=");
21404                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21405                            UserHandle.USER_SYSTEM));
21406                    pw.println(")");
21407                } else if (mRequiredVerifierPackage != null) {
21408                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21409                    pw.print(",");
21410                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21411                            UserHandle.USER_SYSTEM));
21412                }
21413            }
21414
21415            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21416                    packageName == null) {
21417                if (mIntentFilterVerifierComponent != null) {
21418                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21419                    if (!checkin) {
21420                        if (dumpState.onTitlePrinted())
21421                            pw.println();
21422                        pw.println("Intent Filter Verifier:");
21423                        pw.print("  Using: ");
21424                        pw.print(verifierPackageName);
21425                        pw.print(" (uid=");
21426                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21427                                UserHandle.USER_SYSTEM));
21428                        pw.println(")");
21429                    } else if (verifierPackageName != null) {
21430                        pw.print("ifv,"); pw.print(verifierPackageName);
21431                        pw.print(",");
21432                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21433                                UserHandle.USER_SYSTEM));
21434                    }
21435                } else {
21436                    pw.println();
21437                    pw.println("No Intent Filter Verifier available!");
21438                }
21439            }
21440
21441            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21442                boolean printedHeader = false;
21443                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21444                while (it.hasNext()) {
21445                    String libName = it.next();
21446                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21447                    if (versionedLib == null) {
21448                        continue;
21449                    }
21450                    final int versionCount = versionedLib.size();
21451                    for (int i = 0; i < versionCount; i++) {
21452                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21453                        if (!checkin) {
21454                            if (!printedHeader) {
21455                                if (dumpState.onTitlePrinted())
21456                                    pw.println();
21457                                pw.println("Libraries:");
21458                                printedHeader = true;
21459                            }
21460                            pw.print("  ");
21461                        } else {
21462                            pw.print("lib,");
21463                        }
21464                        pw.print(libEntry.info.getName());
21465                        if (libEntry.info.isStatic()) {
21466                            pw.print(" version=" + libEntry.info.getVersion());
21467                        }
21468                        if (!checkin) {
21469                            pw.print(" -> ");
21470                        }
21471                        if (libEntry.path != null) {
21472                            pw.print(" (jar) ");
21473                            pw.print(libEntry.path);
21474                        } else {
21475                            pw.print(" (apk) ");
21476                            pw.print(libEntry.apk);
21477                        }
21478                        pw.println();
21479                    }
21480                }
21481            }
21482
21483            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21484                if (dumpState.onTitlePrinted())
21485                    pw.println();
21486                if (!checkin) {
21487                    pw.println("Features:");
21488                }
21489
21490                synchronized (mAvailableFeatures) {
21491                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21492                        if (checkin) {
21493                            pw.print("feat,");
21494                            pw.print(feat.name);
21495                            pw.print(",");
21496                            pw.println(feat.version);
21497                        } else {
21498                            pw.print("  ");
21499                            pw.print(feat.name);
21500                            if (feat.version > 0) {
21501                                pw.print(" version=");
21502                                pw.print(feat.version);
21503                            }
21504                            pw.println();
21505                        }
21506                    }
21507                }
21508            }
21509
21510            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21511                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21512                        : "Activity Resolver Table:", "  ", packageName,
21513                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21514                    dumpState.setTitlePrinted(true);
21515                }
21516            }
21517            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21518                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21519                        : "Receiver Resolver Table:", "  ", packageName,
21520                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21521                    dumpState.setTitlePrinted(true);
21522                }
21523            }
21524            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21525                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21526                        : "Service Resolver Table:", "  ", packageName,
21527                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21528                    dumpState.setTitlePrinted(true);
21529                }
21530            }
21531            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21532                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21533                        : "Provider Resolver Table:", "  ", packageName,
21534                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21535                    dumpState.setTitlePrinted(true);
21536                }
21537            }
21538
21539            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21540                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21541                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21542                    int user = mSettings.mPreferredActivities.keyAt(i);
21543                    if (pir.dump(pw,
21544                            dumpState.getTitlePrinted()
21545                                ? "\nPreferred Activities User " + user + ":"
21546                                : "Preferred Activities User " + user + ":", "  ",
21547                            packageName, true, false)) {
21548                        dumpState.setTitlePrinted(true);
21549                    }
21550                }
21551            }
21552
21553            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21554                pw.flush();
21555                FileOutputStream fout = new FileOutputStream(fd);
21556                BufferedOutputStream str = new BufferedOutputStream(fout);
21557                XmlSerializer serializer = new FastXmlSerializer();
21558                try {
21559                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21560                    serializer.startDocument(null, true);
21561                    serializer.setFeature(
21562                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21563                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21564                    serializer.endDocument();
21565                    serializer.flush();
21566                } catch (IllegalArgumentException e) {
21567                    pw.println("Failed writing: " + e);
21568                } catch (IllegalStateException e) {
21569                    pw.println("Failed writing: " + e);
21570                } catch (IOException e) {
21571                    pw.println("Failed writing: " + e);
21572                }
21573            }
21574
21575            if (!checkin
21576                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21577                    && packageName == null) {
21578                pw.println();
21579                int count = mSettings.mPackages.size();
21580                if (count == 0) {
21581                    pw.println("No applications!");
21582                    pw.println();
21583                } else {
21584                    final String prefix = "  ";
21585                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21586                    if (allPackageSettings.size() == 0) {
21587                        pw.println("No domain preferred apps!");
21588                        pw.println();
21589                    } else {
21590                        pw.println("App verification status:");
21591                        pw.println();
21592                        count = 0;
21593                        for (PackageSetting ps : allPackageSettings) {
21594                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21595                            if (ivi == null || ivi.getPackageName() == null) continue;
21596                            pw.println(prefix + "Package: " + ivi.getPackageName());
21597                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21598                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21599                            pw.println();
21600                            count++;
21601                        }
21602                        if (count == 0) {
21603                            pw.println(prefix + "No app verification established.");
21604                            pw.println();
21605                        }
21606                        for (int userId : sUserManager.getUserIds()) {
21607                            pw.println("App linkages for user " + userId + ":");
21608                            pw.println();
21609                            count = 0;
21610                            for (PackageSetting ps : allPackageSettings) {
21611                                final long status = ps.getDomainVerificationStatusForUser(userId);
21612                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21613                                        && !DEBUG_DOMAIN_VERIFICATION) {
21614                                    continue;
21615                                }
21616                                pw.println(prefix + "Package: " + ps.name);
21617                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21618                                String statusStr = IntentFilterVerificationInfo.
21619                                        getStatusStringFromValue(status);
21620                                pw.println(prefix + "Status:  " + statusStr);
21621                                pw.println();
21622                                count++;
21623                            }
21624                            if (count == 0) {
21625                                pw.println(prefix + "No configured app linkages.");
21626                                pw.println();
21627                            }
21628                        }
21629                    }
21630                }
21631            }
21632
21633            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21634                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21635            }
21636
21637            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21638                boolean printedSomething = false;
21639                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21640                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21641                        continue;
21642                    }
21643                    if (!printedSomething) {
21644                        if (dumpState.onTitlePrinted())
21645                            pw.println();
21646                        pw.println("Registered ContentProviders:");
21647                        printedSomething = true;
21648                    }
21649                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21650                    pw.print("    "); pw.println(p.toString());
21651                }
21652                printedSomething = false;
21653                for (Map.Entry<String, PackageParser.Provider> entry :
21654                        mProvidersByAuthority.entrySet()) {
21655                    PackageParser.Provider p = entry.getValue();
21656                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21657                        continue;
21658                    }
21659                    if (!printedSomething) {
21660                        if (dumpState.onTitlePrinted())
21661                            pw.println();
21662                        pw.println("ContentProvider Authorities:");
21663                        printedSomething = true;
21664                    }
21665                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21666                    pw.print("    "); pw.println(p.toString());
21667                    if (p.info != null && p.info.applicationInfo != null) {
21668                        final String appInfo = p.info.applicationInfo.toString();
21669                        pw.print("      applicationInfo="); pw.println(appInfo);
21670                    }
21671                }
21672            }
21673
21674            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21675                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21676            }
21677
21678            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21679                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21680            }
21681
21682            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21683                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21684            }
21685
21686            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21687                if (dumpState.onTitlePrinted()) pw.println();
21688                pw.println("Package Changes:");
21689                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21690                final int K = mChangedPackages.size();
21691                for (int i = 0; i < K; i++) {
21692                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21693                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21694                    final int N = changes.size();
21695                    if (N == 0) {
21696                        pw.print("    "); pw.println("No packages changed");
21697                    } else {
21698                        for (int j = 0; j < N; j++) {
21699                            final String pkgName = changes.valueAt(j);
21700                            final int sequenceNumber = changes.keyAt(j);
21701                            pw.print("    ");
21702                            pw.print("seq=");
21703                            pw.print(sequenceNumber);
21704                            pw.print(", package=");
21705                            pw.println(pkgName);
21706                        }
21707                    }
21708                }
21709            }
21710
21711            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21712                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21713            }
21714
21715            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21716                // XXX should handle packageName != null by dumping only install data that
21717                // the given package is involved with.
21718                if (dumpState.onTitlePrinted()) pw.println();
21719
21720                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21721                ipw.println();
21722                ipw.println("Frozen packages:");
21723                ipw.increaseIndent();
21724                if (mFrozenPackages.size() == 0) {
21725                    ipw.println("(none)");
21726                } else {
21727                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21728                        ipw.println(mFrozenPackages.valueAt(i));
21729                    }
21730                }
21731                ipw.decreaseIndent();
21732            }
21733
21734            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21735                if (dumpState.onTitlePrinted()) pw.println();
21736
21737                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21738                ipw.println();
21739                ipw.println("Loaded volumes:");
21740                ipw.increaseIndent();
21741                if (mLoadedVolumes.size() == 0) {
21742                    ipw.println("(none)");
21743                } else {
21744                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21745                        ipw.println(mLoadedVolumes.valueAt(i));
21746                    }
21747                }
21748                ipw.decreaseIndent();
21749            }
21750
21751            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21752                if (dumpState.onTitlePrinted()) pw.println();
21753                dumpDexoptStateLPr(pw, packageName);
21754            }
21755
21756            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21757                if (dumpState.onTitlePrinted()) pw.println();
21758                dumpCompilerStatsLPr(pw, packageName);
21759            }
21760
21761            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21762                if (dumpState.onTitlePrinted()) pw.println();
21763                mSettings.dumpReadMessagesLPr(pw, dumpState);
21764
21765                pw.println();
21766                pw.println("Package warning messages:");
21767                BufferedReader in = null;
21768                String line = null;
21769                try {
21770                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21771                    while ((line = in.readLine()) != null) {
21772                        if (line.contains("ignored: updated version")) continue;
21773                        pw.println(line);
21774                    }
21775                } catch (IOException ignored) {
21776                } finally {
21777                    IoUtils.closeQuietly(in);
21778                }
21779            }
21780
21781            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21782                BufferedReader in = null;
21783                String line = null;
21784                try {
21785                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21786                    while ((line = in.readLine()) != null) {
21787                        if (line.contains("ignored: updated version")) continue;
21788                        pw.print("msg,");
21789                        pw.println(line);
21790                    }
21791                } catch (IOException ignored) {
21792                } finally {
21793                    IoUtils.closeQuietly(in);
21794                }
21795            }
21796        }
21797
21798        // PackageInstaller should be called outside of mPackages lock
21799        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21800            // XXX should handle packageName != null by dumping only install data that
21801            // the given package is involved with.
21802            if (dumpState.onTitlePrinted()) pw.println();
21803            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21804        }
21805    }
21806
21807    private void dumpProto(FileDescriptor fd) {
21808        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21809
21810        synchronized (mPackages) {
21811            final long requiredVerifierPackageToken =
21812                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21813            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21814            proto.write(
21815                    PackageServiceDumpProto.PackageShortProto.UID,
21816                    getPackageUid(
21817                            mRequiredVerifierPackage,
21818                            MATCH_DEBUG_TRIAGED_MISSING,
21819                            UserHandle.USER_SYSTEM));
21820            proto.end(requiredVerifierPackageToken);
21821
21822            if (mIntentFilterVerifierComponent != null) {
21823                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21824                final long verifierPackageToken =
21825                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21826                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21827                proto.write(
21828                        PackageServiceDumpProto.PackageShortProto.UID,
21829                        getPackageUid(
21830                                verifierPackageName,
21831                                MATCH_DEBUG_TRIAGED_MISSING,
21832                                UserHandle.USER_SYSTEM));
21833                proto.end(verifierPackageToken);
21834            }
21835
21836            dumpSharedLibrariesProto(proto);
21837            dumpFeaturesProto(proto);
21838            mSettings.dumpPackagesProto(proto);
21839            mSettings.dumpSharedUsersProto(proto);
21840            dumpMessagesProto(proto);
21841        }
21842        proto.flush();
21843    }
21844
21845    private void dumpMessagesProto(ProtoOutputStream proto) {
21846        BufferedReader in = null;
21847        String line = null;
21848        try {
21849            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21850            while ((line = in.readLine()) != null) {
21851                if (line.contains("ignored: updated version")) continue;
21852                proto.write(PackageServiceDumpProto.MESSAGES, line);
21853            }
21854        } catch (IOException ignored) {
21855        } finally {
21856            IoUtils.closeQuietly(in);
21857        }
21858    }
21859
21860    private void dumpFeaturesProto(ProtoOutputStream proto) {
21861        synchronized (mAvailableFeatures) {
21862            final int count = mAvailableFeatures.size();
21863            for (int i = 0; i < count; i++) {
21864                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21865            }
21866        }
21867    }
21868
21869    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21870        final int count = mSharedLibraries.size();
21871        for (int i = 0; i < count; i++) {
21872            final String libName = mSharedLibraries.keyAt(i);
21873            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21874            if (versionedLib == null) {
21875                continue;
21876            }
21877            final int versionCount = versionedLib.size();
21878            for (int j = 0; j < versionCount; j++) {
21879                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21880                final long sharedLibraryToken =
21881                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21882                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21883                final boolean isJar = (libEntry.path != null);
21884                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21885                if (isJar) {
21886                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21887                } else {
21888                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21889                }
21890                proto.end(sharedLibraryToken);
21891            }
21892        }
21893    }
21894
21895    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21896        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21897        ipw.println();
21898        ipw.println("Dexopt state:");
21899        ipw.increaseIndent();
21900        Collection<PackageParser.Package> packages = null;
21901        if (packageName != null) {
21902            PackageParser.Package targetPackage = mPackages.get(packageName);
21903            if (targetPackage != null) {
21904                packages = Collections.singletonList(targetPackage);
21905            } else {
21906                ipw.println("Unable to find package: " + packageName);
21907                return;
21908            }
21909        } else {
21910            packages = mPackages.values();
21911        }
21912
21913        for (PackageParser.Package pkg : packages) {
21914            ipw.println("[" + pkg.packageName + "]");
21915            ipw.increaseIndent();
21916            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21917                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21918            ipw.decreaseIndent();
21919        }
21920    }
21921
21922    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21923        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21924        ipw.println();
21925        ipw.println("Compiler stats:");
21926        ipw.increaseIndent();
21927        Collection<PackageParser.Package> packages = null;
21928        if (packageName != null) {
21929            PackageParser.Package targetPackage = mPackages.get(packageName);
21930            if (targetPackage != null) {
21931                packages = Collections.singletonList(targetPackage);
21932            } else {
21933                ipw.println("Unable to find package: " + packageName);
21934                return;
21935            }
21936        } else {
21937            packages = mPackages.values();
21938        }
21939
21940        for (PackageParser.Package pkg : packages) {
21941            ipw.println("[" + pkg.packageName + "]");
21942            ipw.increaseIndent();
21943
21944            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21945            if (stats == null) {
21946                ipw.println("(No recorded stats)");
21947            } else {
21948                stats.dump(ipw);
21949            }
21950            ipw.decreaseIndent();
21951        }
21952    }
21953
21954    private String dumpDomainString(String packageName) {
21955        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21956                .getList();
21957        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21958
21959        ArraySet<String> result = new ArraySet<>();
21960        if (iviList.size() > 0) {
21961            for (IntentFilterVerificationInfo ivi : iviList) {
21962                for (String host : ivi.getDomains()) {
21963                    result.add(host);
21964                }
21965            }
21966        }
21967        if (filters != null && filters.size() > 0) {
21968            for (IntentFilter filter : filters) {
21969                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21970                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21971                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21972                    result.addAll(filter.getHostsList());
21973                }
21974            }
21975        }
21976
21977        StringBuilder sb = new StringBuilder(result.size() * 16);
21978        for (String domain : result) {
21979            if (sb.length() > 0) sb.append(" ");
21980            sb.append(domain);
21981        }
21982        return sb.toString();
21983    }
21984
21985    // ------- apps on sdcard specific code -------
21986    static final boolean DEBUG_SD_INSTALL = false;
21987
21988    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21989
21990    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21991
21992    private boolean mMediaMounted = false;
21993
21994    static String getEncryptKey() {
21995        try {
21996            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21997                    SD_ENCRYPTION_KEYSTORE_NAME);
21998            if (sdEncKey == null) {
21999                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22000                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22001                if (sdEncKey == null) {
22002                    Slog.e(TAG, "Failed to create encryption keys");
22003                    return null;
22004                }
22005            }
22006            return sdEncKey;
22007        } catch (NoSuchAlgorithmException nsae) {
22008            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22009            return null;
22010        } catch (IOException ioe) {
22011            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22012            return null;
22013        }
22014    }
22015
22016    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22017            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22018        final int size = infos.size();
22019        final String[] packageNames = new String[size];
22020        final int[] packageUids = new int[size];
22021        for (int i = 0; i < size; i++) {
22022            final ApplicationInfo info = infos.get(i);
22023            packageNames[i] = info.packageName;
22024            packageUids[i] = info.uid;
22025        }
22026        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22027                finishedReceiver);
22028    }
22029
22030    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22031            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22032        sendResourcesChangedBroadcast(mediaStatus, replacing,
22033                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22034    }
22035
22036    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22037            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22038        int size = pkgList.length;
22039        if (size > 0) {
22040            // Send broadcasts here
22041            Bundle extras = new Bundle();
22042            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22043            if (uidArr != null) {
22044                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22045            }
22046            if (replacing) {
22047                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22048            }
22049            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22050                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22051            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22052        }
22053    }
22054
22055    private void loadPrivatePackages(final VolumeInfo vol) {
22056        mHandler.post(new Runnable() {
22057            @Override
22058            public void run() {
22059                loadPrivatePackagesInner(vol);
22060            }
22061        });
22062    }
22063
22064    private void loadPrivatePackagesInner(VolumeInfo vol) {
22065        final String volumeUuid = vol.fsUuid;
22066        if (TextUtils.isEmpty(volumeUuid)) {
22067            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22068            return;
22069        }
22070
22071        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22072        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22073        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22074
22075        final VersionInfo ver;
22076        final List<PackageSetting> packages;
22077        synchronized (mPackages) {
22078            ver = mSettings.findOrCreateVersion(volumeUuid);
22079            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22080        }
22081
22082        for (PackageSetting ps : packages) {
22083            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22084            synchronized (mInstallLock) {
22085                final PackageParser.Package pkg;
22086                try {
22087                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22088                    loaded.add(pkg.applicationInfo);
22089
22090                } catch (PackageManagerException e) {
22091                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22092                }
22093
22094                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22095                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22096                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22097                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22098                }
22099            }
22100        }
22101
22102        // Reconcile app data for all started/unlocked users
22103        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22104        final UserManager um = mContext.getSystemService(UserManager.class);
22105        UserManagerInternal umInternal = getUserManagerInternal();
22106        for (UserInfo user : um.getUsers()) {
22107            final int flags;
22108            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22109                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22110            } else if (umInternal.isUserRunning(user.id)) {
22111                flags = StorageManager.FLAG_STORAGE_DE;
22112            } else {
22113                continue;
22114            }
22115
22116            try {
22117                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22118                synchronized (mInstallLock) {
22119                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22120                }
22121            } catch (IllegalStateException e) {
22122                // Device was probably ejected, and we'll process that event momentarily
22123                Slog.w(TAG, "Failed to prepare storage: " + e);
22124            }
22125        }
22126
22127        synchronized (mPackages) {
22128            int updateFlags = UPDATE_PERMISSIONS_ALL;
22129            if (ver.sdkVersion != mSdkVersion) {
22130                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22131                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22132                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22133            }
22134            updatePermissionsLocked(null, null, volumeUuid, updateFlags);
22135
22136            // Yay, everything is now upgraded
22137            ver.forceCurrent();
22138
22139            mSettings.writeLPr();
22140        }
22141
22142        for (PackageFreezer freezer : freezers) {
22143            freezer.close();
22144        }
22145
22146        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22147        sendResourcesChangedBroadcast(true, false, loaded, null);
22148        mLoadedVolumes.add(vol.getId());
22149    }
22150
22151    private void unloadPrivatePackages(final VolumeInfo vol) {
22152        mHandler.post(new Runnable() {
22153            @Override
22154            public void run() {
22155                unloadPrivatePackagesInner(vol);
22156            }
22157        });
22158    }
22159
22160    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22161        final String volumeUuid = vol.fsUuid;
22162        if (TextUtils.isEmpty(volumeUuid)) {
22163            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22164            return;
22165        }
22166
22167        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22168        synchronized (mInstallLock) {
22169        synchronized (mPackages) {
22170            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22171            for (PackageSetting ps : packages) {
22172                if (ps.pkg == null) continue;
22173
22174                final ApplicationInfo info = ps.pkg.applicationInfo;
22175                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22176                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22177
22178                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22179                        "unloadPrivatePackagesInner")) {
22180                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22181                            false, null)) {
22182                        unloaded.add(info);
22183                    } else {
22184                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22185                    }
22186                }
22187
22188                // Try very hard to release any references to this package
22189                // so we don't risk the system server being killed due to
22190                // open FDs
22191                AttributeCache.instance().removePackage(ps.name);
22192            }
22193
22194            mSettings.writeLPr();
22195        }
22196        }
22197
22198        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22199        sendResourcesChangedBroadcast(false, false, unloaded, null);
22200        mLoadedVolumes.remove(vol.getId());
22201
22202        // Try very hard to release any references to this path so we don't risk
22203        // the system server being killed due to open FDs
22204        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22205
22206        for (int i = 0; i < 3; i++) {
22207            System.gc();
22208            System.runFinalization();
22209        }
22210    }
22211
22212    private void assertPackageKnown(String volumeUuid, String packageName)
22213            throws PackageManagerException {
22214        synchronized (mPackages) {
22215            // Normalize package name to handle renamed packages
22216            packageName = normalizePackageNameLPr(packageName);
22217
22218            final PackageSetting ps = mSettings.mPackages.get(packageName);
22219            if (ps == null) {
22220                throw new PackageManagerException("Package " + packageName + " is unknown");
22221            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22222                throw new PackageManagerException(
22223                        "Package " + packageName + " found on unknown volume " + volumeUuid
22224                                + "; expected volume " + ps.volumeUuid);
22225            }
22226        }
22227    }
22228
22229    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22230            throws PackageManagerException {
22231        synchronized (mPackages) {
22232            // Normalize package name to handle renamed packages
22233            packageName = normalizePackageNameLPr(packageName);
22234
22235            final PackageSetting ps = mSettings.mPackages.get(packageName);
22236            if (ps == null) {
22237                throw new PackageManagerException("Package " + packageName + " is unknown");
22238            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22239                throw new PackageManagerException(
22240                        "Package " + packageName + " found on unknown volume " + volumeUuid
22241                                + "; expected volume " + ps.volumeUuid);
22242            } else if (!ps.getInstalled(userId)) {
22243                throw new PackageManagerException(
22244                        "Package " + packageName + " not installed for user " + userId);
22245            }
22246        }
22247    }
22248
22249    private List<String> collectAbsoluteCodePaths() {
22250        synchronized (mPackages) {
22251            List<String> codePaths = new ArrayList<>();
22252            final int packageCount = mSettings.mPackages.size();
22253            for (int i = 0; i < packageCount; i++) {
22254                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22255                codePaths.add(ps.codePath.getAbsolutePath());
22256            }
22257            return codePaths;
22258        }
22259    }
22260
22261    /**
22262     * Examine all apps present on given mounted volume, and destroy apps that
22263     * aren't expected, either due to uninstallation or reinstallation on
22264     * another volume.
22265     */
22266    private void reconcileApps(String volumeUuid) {
22267        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22268        List<File> filesToDelete = null;
22269
22270        final File[] files = FileUtils.listFilesOrEmpty(
22271                Environment.getDataAppDirectory(volumeUuid));
22272        for (File file : files) {
22273            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22274                    && !PackageInstallerService.isStageName(file.getName());
22275            if (!isPackage) {
22276                // Ignore entries which are not packages
22277                continue;
22278            }
22279
22280            String absolutePath = file.getAbsolutePath();
22281
22282            boolean pathValid = false;
22283            final int absoluteCodePathCount = absoluteCodePaths.size();
22284            for (int i = 0; i < absoluteCodePathCount; i++) {
22285                String absoluteCodePath = absoluteCodePaths.get(i);
22286                if (absolutePath.startsWith(absoluteCodePath)) {
22287                    pathValid = true;
22288                    break;
22289                }
22290            }
22291
22292            if (!pathValid) {
22293                if (filesToDelete == null) {
22294                    filesToDelete = new ArrayList<>();
22295                }
22296                filesToDelete.add(file);
22297            }
22298        }
22299
22300        if (filesToDelete != null) {
22301            final int fileToDeleteCount = filesToDelete.size();
22302            for (int i = 0; i < fileToDeleteCount; i++) {
22303                File fileToDelete = filesToDelete.get(i);
22304                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22305                synchronized (mInstallLock) {
22306                    removeCodePathLI(fileToDelete);
22307                }
22308            }
22309        }
22310    }
22311
22312    /**
22313     * Reconcile all app data for the given user.
22314     * <p>
22315     * Verifies that directories exist and that ownership and labeling is
22316     * correct for all installed apps on all mounted volumes.
22317     */
22318    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22319        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22320        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22321            final String volumeUuid = vol.getFsUuid();
22322            synchronized (mInstallLock) {
22323                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22324            }
22325        }
22326    }
22327
22328    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22329            boolean migrateAppData) {
22330        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22331    }
22332
22333    /**
22334     * Reconcile all app data on given mounted volume.
22335     * <p>
22336     * Destroys app data that isn't expected, either due to uninstallation or
22337     * reinstallation on another volume.
22338     * <p>
22339     * Verifies that directories exist and that ownership and labeling is
22340     * correct for all installed apps.
22341     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22342     */
22343    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22344            boolean migrateAppData, boolean onlyCoreApps) {
22345        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22346                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22347        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22348
22349        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22350        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22351
22352        // First look for stale data that doesn't belong, and check if things
22353        // have changed since we did our last restorecon
22354        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22355            if (StorageManager.isFileEncryptedNativeOrEmulated()
22356                    && !StorageManager.isUserKeyUnlocked(userId)) {
22357                throw new RuntimeException(
22358                        "Yikes, someone asked us to reconcile CE storage while " + userId
22359                                + " was still locked; this would have caused massive data loss!");
22360            }
22361
22362            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22363            for (File file : files) {
22364                final String packageName = file.getName();
22365                try {
22366                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22367                } catch (PackageManagerException e) {
22368                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22369                    try {
22370                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22371                                StorageManager.FLAG_STORAGE_CE, 0);
22372                    } catch (InstallerException e2) {
22373                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22374                    }
22375                }
22376            }
22377        }
22378        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22379            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22380            for (File file : files) {
22381                final String packageName = file.getName();
22382                try {
22383                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22384                } catch (PackageManagerException e) {
22385                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22386                    try {
22387                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22388                                StorageManager.FLAG_STORAGE_DE, 0);
22389                    } catch (InstallerException e2) {
22390                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22391                    }
22392                }
22393            }
22394        }
22395
22396        // Ensure that data directories are ready to roll for all packages
22397        // installed for this volume and user
22398        final List<PackageSetting> packages;
22399        synchronized (mPackages) {
22400            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22401        }
22402        int preparedCount = 0;
22403        for (PackageSetting ps : packages) {
22404            final String packageName = ps.name;
22405            if (ps.pkg == null) {
22406                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22407                // TODO: might be due to legacy ASEC apps; we should circle back
22408                // and reconcile again once they're scanned
22409                continue;
22410            }
22411            // Skip non-core apps if requested
22412            if (onlyCoreApps && !ps.pkg.coreApp) {
22413                result.add(packageName);
22414                continue;
22415            }
22416
22417            if (ps.getInstalled(userId)) {
22418                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22419                preparedCount++;
22420            }
22421        }
22422
22423        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22424        return result;
22425    }
22426
22427    /**
22428     * Prepare app data for the given app just after it was installed or
22429     * upgraded. This method carefully only touches users that it's installed
22430     * for, and it forces a restorecon to handle any seinfo changes.
22431     * <p>
22432     * Verifies that directories exist and that ownership and labeling is
22433     * correct for all installed apps. If there is an ownership mismatch, it
22434     * will try recovering system apps by wiping data; third-party app data is
22435     * left intact.
22436     * <p>
22437     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22438     */
22439    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22440        final PackageSetting ps;
22441        synchronized (mPackages) {
22442            ps = mSettings.mPackages.get(pkg.packageName);
22443            mSettings.writeKernelMappingLPr(ps);
22444        }
22445
22446        final UserManager um = mContext.getSystemService(UserManager.class);
22447        UserManagerInternal umInternal = getUserManagerInternal();
22448        for (UserInfo user : um.getUsers()) {
22449            final int flags;
22450            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22451                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22452            } else if (umInternal.isUserRunning(user.id)) {
22453                flags = StorageManager.FLAG_STORAGE_DE;
22454            } else {
22455                continue;
22456            }
22457
22458            if (ps.getInstalled(user.id)) {
22459                // TODO: when user data is locked, mark that we're still dirty
22460                prepareAppDataLIF(pkg, user.id, flags);
22461            }
22462        }
22463    }
22464
22465    /**
22466     * Prepare app data for the given app.
22467     * <p>
22468     * Verifies that directories exist and that ownership and labeling is
22469     * correct for all installed apps. If there is an ownership mismatch, this
22470     * will try recovering system apps by wiping data; third-party app data is
22471     * left intact.
22472     */
22473    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22474        if (pkg == null) {
22475            Slog.wtf(TAG, "Package was null!", new Throwable());
22476            return;
22477        }
22478        prepareAppDataLeafLIF(pkg, userId, flags);
22479        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22480        for (int i = 0; i < childCount; i++) {
22481            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22482        }
22483    }
22484
22485    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22486            boolean maybeMigrateAppData) {
22487        prepareAppDataLIF(pkg, userId, flags);
22488
22489        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22490            // We may have just shuffled around app data directories, so
22491            // prepare them one more time
22492            prepareAppDataLIF(pkg, userId, flags);
22493        }
22494    }
22495
22496    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22497        if (DEBUG_APP_DATA) {
22498            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22499                    + Integer.toHexString(flags));
22500        }
22501
22502        final String volumeUuid = pkg.volumeUuid;
22503        final String packageName = pkg.packageName;
22504        final ApplicationInfo app = pkg.applicationInfo;
22505        final int appId = UserHandle.getAppId(app.uid);
22506
22507        Preconditions.checkNotNull(app.seInfo);
22508
22509        long ceDataInode = -1;
22510        try {
22511            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22512                    appId, app.seInfo, app.targetSdkVersion);
22513        } catch (InstallerException e) {
22514            if (app.isSystemApp()) {
22515                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22516                        + ", but trying to recover: " + e);
22517                destroyAppDataLeafLIF(pkg, userId, flags);
22518                try {
22519                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22520                            appId, app.seInfo, app.targetSdkVersion);
22521                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22522                } catch (InstallerException e2) {
22523                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22524                }
22525            } else {
22526                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22527            }
22528        }
22529
22530        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22531            // TODO: mark this structure as dirty so we persist it!
22532            synchronized (mPackages) {
22533                final PackageSetting ps = mSettings.mPackages.get(packageName);
22534                if (ps != null) {
22535                    ps.setCeDataInode(ceDataInode, userId);
22536                }
22537            }
22538        }
22539
22540        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22541    }
22542
22543    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22544        if (pkg == null) {
22545            Slog.wtf(TAG, "Package was null!", new Throwable());
22546            return;
22547        }
22548        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22549        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22550        for (int i = 0; i < childCount; i++) {
22551            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22552        }
22553    }
22554
22555    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22556        final String volumeUuid = pkg.volumeUuid;
22557        final String packageName = pkg.packageName;
22558        final ApplicationInfo app = pkg.applicationInfo;
22559
22560        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22561            // Create a native library symlink only if we have native libraries
22562            // and if the native libraries are 32 bit libraries. We do not provide
22563            // this symlink for 64 bit libraries.
22564            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22565                final String nativeLibPath = app.nativeLibraryDir;
22566                try {
22567                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22568                            nativeLibPath, userId);
22569                } catch (InstallerException e) {
22570                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22571                }
22572            }
22573        }
22574    }
22575
22576    /**
22577     * For system apps on non-FBE devices, this method migrates any existing
22578     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22579     * requested by the app.
22580     */
22581    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22582        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22583                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22584            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22585                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22586            try {
22587                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22588                        storageTarget);
22589            } catch (InstallerException e) {
22590                logCriticalInfo(Log.WARN,
22591                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22592            }
22593            return true;
22594        } else {
22595            return false;
22596        }
22597    }
22598
22599    public PackageFreezer freezePackage(String packageName, String killReason) {
22600        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22601    }
22602
22603    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22604        return new PackageFreezer(packageName, userId, killReason);
22605    }
22606
22607    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22608            String killReason) {
22609        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22610    }
22611
22612    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22613            String killReason) {
22614        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22615            return new PackageFreezer();
22616        } else {
22617            return freezePackage(packageName, userId, killReason);
22618        }
22619    }
22620
22621    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22622            String killReason) {
22623        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22624    }
22625
22626    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22627            String killReason) {
22628        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22629            return new PackageFreezer();
22630        } else {
22631            return freezePackage(packageName, userId, killReason);
22632        }
22633    }
22634
22635    /**
22636     * Class that freezes and kills the given package upon creation, and
22637     * unfreezes it upon closing. This is typically used when doing surgery on
22638     * app code/data to prevent the app from running while you're working.
22639     */
22640    private class PackageFreezer implements AutoCloseable {
22641        private final String mPackageName;
22642        private final PackageFreezer[] mChildren;
22643
22644        private final boolean mWeFroze;
22645
22646        private final AtomicBoolean mClosed = new AtomicBoolean();
22647        private final CloseGuard mCloseGuard = CloseGuard.get();
22648
22649        /**
22650         * Create and return a stub freezer that doesn't actually do anything,
22651         * typically used when someone requested
22652         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22653         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22654         */
22655        public PackageFreezer() {
22656            mPackageName = null;
22657            mChildren = null;
22658            mWeFroze = false;
22659            mCloseGuard.open("close");
22660        }
22661
22662        public PackageFreezer(String packageName, int userId, String killReason) {
22663            synchronized (mPackages) {
22664                mPackageName = packageName;
22665                mWeFroze = mFrozenPackages.add(mPackageName);
22666
22667                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22668                if (ps != null) {
22669                    killApplication(ps.name, ps.appId, userId, killReason);
22670                }
22671
22672                final PackageParser.Package p = mPackages.get(packageName);
22673                if (p != null && p.childPackages != null) {
22674                    final int N = p.childPackages.size();
22675                    mChildren = new PackageFreezer[N];
22676                    for (int i = 0; i < N; i++) {
22677                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22678                                userId, killReason);
22679                    }
22680                } else {
22681                    mChildren = null;
22682                }
22683            }
22684            mCloseGuard.open("close");
22685        }
22686
22687        @Override
22688        protected void finalize() throws Throwable {
22689            try {
22690                if (mCloseGuard != null) {
22691                    mCloseGuard.warnIfOpen();
22692                }
22693
22694                close();
22695            } finally {
22696                super.finalize();
22697            }
22698        }
22699
22700        @Override
22701        public void close() {
22702            mCloseGuard.close();
22703            if (mClosed.compareAndSet(false, true)) {
22704                synchronized (mPackages) {
22705                    if (mWeFroze) {
22706                        mFrozenPackages.remove(mPackageName);
22707                    }
22708
22709                    if (mChildren != null) {
22710                        for (PackageFreezer freezer : mChildren) {
22711                            freezer.close();
22712                        }
22713                    }
22714                }
22715            }
22716        }
22717    }
22718
22719    /**
22720     * Verify that given package is currently frozen.
22721     */
22722    private void checkPackageFrozen(String packageName) {
22723        synchronized (mPackages) {
22724            if (!mFrozenPackages.contains(packageName)) {
22725                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22726            }
22727        }
22728    }
22729
22730    @Override
22731    public int movePackage(final String packageName, final String volumeUuid) {
22732        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22733
22734        final int callingUid = Binder.getCallingUid();
22735        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22736        final int moveId = mNextMoveId.getAndIncrement();
22737        mHandler.post(new Runnable() {
22738            @Override
22739            public void run() {
22740                try {
22741                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22742                } catch (PackageManagerException e) {
22743                    Slog.w(TAG, "Failed to move " + packageName, e);
22744                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22745                }
22746            }
22747        });
22748        return moveId;
22749    }
22750
22751    private void movePackageInternal(final String packageName, final String volumeUuid,
22752            final int moveId, final int callingUid, UserHandle user)
22753                    throws PackageManagerException {
22754        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22755        final PackageManager pm = mContext.getPackageManager();
22756
22757        final boolean currentAsec;
22758        final String currentVolumeUuid;
22759        final File codeFile;
22760        final String installerPackageName;
22761        final String packageAbiOverride;
22762        final int appId;
22763        final String seinfo;
22764        final String label;
22765        final int targetSdkVersion;
22766        final PackageFreezer freezer;
22767        final int[] installedUserIds;
22768
22769        // reader
22770        synchronized (mPackages) {
22771            final PackageParser.Package pkg = mPackages.get(packageName);
22772            final PackageSetting ps = mSettings.mPackages.get(packageName);
22773            if (pkg == null
22774                    || ps == null
22775                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22776                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22777            }
22778            if (pkg.applicationInfo.isSystemApp()) {
22779                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22780                        "Cannot move system application");
22781            }
22782
22783            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22784            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22785                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22786            if (isInternalStorage && !allow3rdPartyOnInternal) {
22787                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22788                        "3rd party apps are not allowed on internal storage");
22789            }
22790
22791            if (pkg.applicationInfo.isExternalAsec()) {
22792                currentAsec = true;
22793                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22794            } else if (pkg.applicationInfo.isForwardLocked()) {
22795                currentAsec = true;
22796                currentVolumeUuid = "forward_locked";
22797            } else {
22798                currentAsec = false;
22799                currentVolumeUuid = ps.volumeUuid;
22800
22801                final File probe = new File(pkg.codePath);
22802                final File probeOat = new File(probe, "oat");
22803                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22804                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22805                            "Move only supported for modern cluster style installs");
22806                }
22807            }
22808
22809            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22810                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22811                        "Package already moved to " + volumeUuid);
22812            }
22813            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22814                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22815                        "Device admin cannot be moved");
22816            }
22817
22818            if (mFrozenPackages.contains(packageName)) {
22819                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22820                        "Failed to move already frozen package");
22821            }
22822
22823            codeFile = new File(pkg.codePath);
22824            installerPackageName = ps.installerPackageName;
22825            packageAbiOverride = ps.cpuAbiOverrideString;
22826            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22827            seinfo = pkg.applicationInfo.seInfo;
22828            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22829            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22830            freezer = freezePackage(packageName, "movePackageInternal");
22831            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22832        }
22833
22834        final Bundle extras = new Bundle();
22835        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22836        extras.putString(Intent.EXTRA_TITLE, label);
22837        mMoveCallbacks.notifyCreated(moveId, extras);
22838
22839        int installFlags;
22840        final boolean moveCompleteApp;
22841        final File measurePath;
22842
22843        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22844            installFlags = INSTALL_INTERNAL;
22845            moveCompleteApp = !currentAsec;
22846            measurePath = Environment.getDataAppDirectory(volumeUuid);
22847        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22848            installFlags = INSTALL_EXTERNAL;
22849            moveCompleteApp = false;
22850            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22851        } else {
22852            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22853            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22854                    || !volume.isMountedWritable()) {
22855                freezer.close();
22856                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22857                        "Move location not mounted private volume");
22858            }
22859
22860            Preconditions.checkState(!currentAsec);
22861
22862            installFlags = INSTALL_INTERNAL;
22863            moveCompleteApp = true;
22864            measurePath = Environment.getDataAppDirectory(volumeUuid);
22865        }
22866
22867        // If we're moving app data around, we need all the users unlocked
22868        if (moveCompleteApp) {
22869            for (int userId : installedUserIds) {
22870                if (StorageManager.isFileEncryptedNativeOrEmulated()
22871                        && !StorageManager.isUserKeyUnlocked(userId)) {
22872                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22873                            "User " + userId + " must be unlocked");
22874                }
22875            }
22876        }
22877
22878        final PackageStats stats = new PackageStats(null, -1);
22879        synchronized (mInstaller) {
22880            for (int userId : installedUserIds) {
22881                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22882                    freezer.close();
22883                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22884                            "Failed to measure package size");
22885                }
22886            }
22887        }
22888
22889        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22890                + stats.dataSize);
22891
22892        final long startFreeBytes = measurePath.getUsableSpace();
22893        final long sizeBytes;
22894        if (moveCompleteApp) {
22895            sizeBytes = stats.codeSize + stats.dataSize;
22896        } else {
22897            sizeBytes = stats.codeSize;
22898        }
22899
22900        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22901            freezer.close();
22902            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22903                    "Not enough free space to move");
22904        }
22905
22906        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22907
22908        final CountDownLatch installedLatch = new CountDownLatch(1);
22909        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22910            @Override
22911            public void onUserActionRequired(Intent intent) throws RemoteException {
22912                throw new IllegalStateException();
22913            }
22914
22915            @Override
22916            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22917                    Bundle extras) throws RemoteException {
22918                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22919                        + PackageManager.installStatusToString(returnCode, msg));
22920
22921                installedLatch.countDown();
22922                freezer.close();
22923
22924                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22925                switch (status) {
22926                    case PackageInstaller.STATUS_SUCCESS:
22927                        mMoveCallbacks.notifyStatusChanged(moveId,
22928                                PackageManager.MOVE_SUCCEEDED);
22929                        break;
22930                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22931                        mMoveCallbacks.notifyStatusChanged(moveId,
22932                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22933                        break;
22934                    default:
22935                        mMoveCallbacks.notifyStatusChanged(moveId,
22936                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22937                        break;
22938                }
22939            }
22940        };
22941
22942        final MoveInfo move;
22943        if (moveCompleteApp) {
22944            // Kick off a thread to report progress estimates
22945            new Thread() {
22946                @Override
22947                public void run() {
22948                    while (true) {
22949                        try {
22950                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22951                                break;
22952                            }
22953                        } catch (InterruptedException ignored) {
22954                        }
22955
22956                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22957                        final int progress = 10 + (int) MathUtils.constrain(
22958                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22959                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22960                    }
22961                }
22962            }.start();
22963
22964            final String dataAppName = codeFile.getName();
22965            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22966                    dataAppName, appId, seinfo, targetSdkVersion);
22967        } else {
22968            move = null;
22969        }
22970
22971        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22972
22973        final Message msg = mHandler.obtainMessage(INIT_COPY);
22974        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22975        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22976                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22977                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22978                PackageManager.INSTALL_REASON_UNKNOWN);
22979        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22980        msg.obj = params;
22981
22982        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22983                System.identityHashCode(msg.obj));
22984        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22985                System.identityHashCode(msg.obj));
22986
22987        mHandler.sendMessage(msg);
22988    }
22989
22990    @Override
22991    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22992        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22993
22994        final int realMoveId = mNextMoveId.getAndIncrement();
22995        final Bundle extras = new Bundle();
22996        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22997        mMoveCallbacks.notifyCreated(realMoveId, extras);
22998
22999        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23000            @Override
23001            public void onCreated(int moveId, Bundle extras) {
23002                // Ignored
23003            }
23004
23005            @Override
23006            public void onStatusChanged(int moveId, int status, long estMillis) {
23007                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23008            }
23009        };
23010
23011        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23012        storage.setPrimaryStorageUuid(volumeUuid, callback);
23013        return realMoveId;
23014    }
23015
23016    @Override
23017    public int getMoveStatus(int moveId) {
23018        mContext.enforceCallingOrSelfPermission(
23019                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23020        return mMoveCallbacks.mLastStatus.get(moveId);
23021    }
23022
23023    @Override
23024    public void registerMoveCallback(IPackageMoveObserver callback) {
23025        mContext.enforceCallingOrSelfPermission(
23026                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23027        mMoveCallbacks.register(callback);
23028    }
23029
23030    @Override
23031    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23032        mContext.enforceCallingOrSelfPermission(
23033                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23034        mMoveCallbacks.unregister(callback);
23035    }
23036
23037    @Override
23038    public boolean setInstallLocation(int loc) {
23039        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23040                null);
23041        if (getInstallLocation() == loc) {
23042            return true;
23043        }
23044        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23045                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23046            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23047                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23048            return true;
23049        }
23050        return false;
23051   }
23052
23053    @Override
23054    public int getInstallLocation() {
23055        // allow instant app access
23056        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23057                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23058                PackageHelper.APP_INSTALL_AUTO);
23059    }
23060
23061    /** Called by UserManagerService */
23062    void cleanUpUser(UserManagerService userManager, int userHandle) {
23063        synchronized (mPackages) {
23064            mDirtyUsers.remove(userHandle);
23065            mUserNeedsBadging.delete(userHandle);
23066            mSettings.removeUserLPw(userHandle);
23067            mPendingBroadcasts.remove(userHandle);
23068            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23069            removeUnusedPackagesLPw(userManager, userHandle);
23070        }
23071    }
23072
23073    /**
23074     * We're removing userHandle and would like to remove any downloaded packages
23075     * that are no longer in use by any other user.
23076     * @param userHandle the user being removed
23077     */
23078    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23079        final boolean DEBUG_CLEAN_APKS = false;
23080        int [] users = userManager.getUserIds();
23081        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23082        while (psit.hasNext()) {
23083            PackageSetting ps = psit.next();
23084            if (ps.pkg == null) {
23085                continue;
23086            }
23087            final String packageName = ps.pkg.packageName;
23088            // Skip over if system app
23089            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23090                continue;
23091            }
23092            if (DEBUG_CLEAN_APKS) {
23093                Slog.i(TAG, "Checking package " + packageName);
23094            }
23095            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23096            if (keep) {
23097                if (DEBUG_CLEAN_APKS) {
23098                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23099                }
23100            } else {
23101                for (int i = 0; i < users.length; i++) {
23102                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23103                        keep = true;
23104                        if (DEBUG_CLEAN_APKS) {
23105                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23106                                    + users[i]);
23107                        }
23108                        break;
23109                    }
23110                }
23111            }
23112            if (!keep) {
23113                if (DEBUG_CLEAN_APKS) {
23114                    Slog.i(TAG, "  Removing package " + packageName);
23115                }
23116                mHandler.post(new Runnable() {
23117                    public void run() {
23118                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23119                                userHandle, 0);
23120                    } //end run
23121                });
23122            }
23123        }
23124    }
23125
23126    /** Called by UserManagerService */
23127    void createNewUser(int userId, String[] disallowedPackages) {
23128        synchronized (mInstallLock) {
23129            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23130        }
23131        synchronized (mPackages) {
23132            scheduleWritePackageRestrictionsLocked(userId);
23133            scheduleWritePackageListLocked(userId);
23134            applyFactoryDefaultBrowserLPw(userId);
23135            primeDomainVerificationsLPw(userId);
23136        }
23137    }
23138
23139    void onNewUserCreated(final int userId) {
23140        synchronized(mPackages) {
23141            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
23142            // If permission review for legacy apps is required, we represent
23143            // dagerous permissions for such apps as always granted runtime
23144            // permissions to keep per user flag state whether review is needed.
23145            // Hence, if a new user is added we have to propagate dangerous
23146            // permission grants for these legacy apps.
23147            if (mPermissionReviewRequired) {
23148                updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23149                        | UPDATE_PERMISSIONS_REPLACE_ALL);
23150            }
23151        }
23152    }
23153
23154    @Override
23155    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23156        mContext.enforceCallingOrSelfPermission(
23157                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23158                "Only package verification agents can read the verifier device identity");
23159
23160        synchronized (mPackages) {
23161            return mSettings.getVerifierDeviceIdentityLPw();
23162        }
23163    }
23164
23165    @Override
23166    public void setPermissionEnforced(String permission, boolean enforced) {
23167        // TODO: Now that we no longer change GID for storage, this should to away.
23168        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23169                "setPermissionEnforced");
23170        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23171            synchronized (mPackages) {
23172                if (mSettings.mReadExternalStorageEnforced == null
23173                        || mSettings.mReadExternalStorageEnforced != enforced) {
23174                    mSettings.mReadExternalStorageEnforced =
23175                            enforced ? Boolean.TRUE : Boolean.FALSE;
23176                    mSettings.writeLPr();
23177                }
23178            }
23179            // kill any non-foreground processes so we restart them and
23180            // grant/revoke the GID.
23181            final IActivityManager am = ActivityManager.getService();
23182            if (am != null) {
23183                final long token = Binder.clearCallingIdentity();
23184                try {
23185                    am.killProcessesBelowForeground("setPermissionEnforcement");
23186                } catch (RemoteException e) {
23187                } finally {
23188                    Binder.restoreCallingIdentity(token);
23189                }
23190            }
23191        } else {
23192            throw new IllegalArgumentException("No selective enforcement for " + permission);
23193        }
23194    }
23195
23196    @Override
23197    @Deprecated
23198    public boolean isPermissionEnforced(String permission) {
23199        // allow instant applications
23200        return true;
23201    }
23202
23203    @Override
23204    public boolean isStorageLow() {
23205        // allow instant applications
23206        final long token = Binder.clearCallingIdentity();
23207        try {
23208            final DeviceStorageMonitorInternal
23209                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23210            if (dsm != null) {
23211                return dsm.isMemoryLow();
23212            } else {
23213                return false;
23214            }
23215        } finally {
23216            Binder.restoreCallingIdentity(token);
23217        }
23218    }
23219
23220    @Override
23221    public IPackageInstaller getPackageInstaller() {
23222        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23223            return null;
23224        }
23225        return mInstallerService;
23226    }
23227
23228    private boolean userNeedsBadging(int userId) {
23229        int index = mUserNeedsBadging.indexOfKey(userId);
23230        if (index < 0) {
23231            final UserInfo userInfo;
23232            final long token = Binder.clearCallingIdentity();
23233            try {
23234                userInfo = sUserManager.getUserInfo(userId);
23235            } finally {
23236                Binder.restoreCallingIdentity(token);
23237            }
23238            final boolean b;
23239            if (userInfo != null && userInfo.isManagedProfile()) {
23240                b = true;
23241            } else {
23242                b = false;
23243            }
23244            mUserNeedsBadging.put(userId, b);
23245            return b;
23246        }
23247        return mUserNeedsBadging.valueAt(index);
23248    }
23249
23250    @Override
23251    public KeySet getKeySetByAlias(String packageName, String alias) {
23252        if (packageName == null || alias == null) {
23253            return null;
23254        }
23255        synchronized(mPackages) {
23256            final PackageParser.Package pkg = mPackages.get(packageName);
23257            if (pkg == null) {
23258                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23259                throw new IllegalArgumentException("Unknown package: " + packageName);
23260            }
23261            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23262            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23263                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23264                throw new IllegalArgumentException("Unknown package: " + packageName);
23265            }
23266            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23267            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23268        }
23269    }
23270
23271    @Override
23272    public KeySet getSigningKeySet(String packageName) {
23273        if (packageName == null) {
23274            return null;
23275        }
23276        synchronized(mPackages) {
23277            final int callingUid = Binder.getCallingUid();
23278            final int callingUserId = UserHandle.getUserId(callingUid);
23279            final PackageParser.Package pkg = mPackages.get(packageName);
23280            if (pkg == null) {
23281                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23282                throw new IllegalArgumentException("Unknown package: " + packageName);
23283            }
23284            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23285            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23286                // filter and pretend the package doesn't exist
23287                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23288                        + ", uid:" + callingUid);
23289                throw new IllegalArgumentException("Unknown package: " + packageName);
23290            }
23291            if (pkg.applicationInfo.uid != callingUid
23292                    && Process.SYSTEM_UID != callingUid) {
23293                throw new SecurityException("May not access signing KeySet of other apps.");
23294            }
23295            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23296            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23297        }
23298    }
23299
23300    @Override
23301    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23302        final int callingUid = Binder.getCallingUid();
23303        if (getInstantAppPackageName(callingUid) != null) {
23304            return false;
23305        }
23306        if (packageName == null || ks == null) {
23307            return false;
23308        }
23309        synchronized(mPackages) {
23310            final PackageParser.Package pkg = mPackages.get(packageName);
23311            if (pkg == null
23312                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23313                            UserHandle.getUserId(callingUid))) {
23314                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23315                throw new IllegalArgumentException("Unknown package: " + packageName);
23316            }
23317            IBinder ksh = ks.getToken();
23318            if (ksh instanceof KeySetHandle) {
23319                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23320                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23321            }
23322            return false;
23323        }
23324    }
23325
23326    @Override
23327    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23328        final int callingUid = Binder.getCallingUid();
23329        if (getInstantAppPackageName(callingUid) != null) {
23330            return false;
23331        }
23332        if (packageName == null || ks == null) {
23333            return false;
23334        }
23335        synchronized(mPackages) {
23336            final PackageParser.Package pkg = mPackages.get(packageName);
23337            if (pkg == null
23338                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23339                            UserHandle.getUserId(callingUid))) {
23340                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23341                throw new IllegalArgumentException("Unknown package: " + packageName);
23342            }
23343            IBinder ksh = ks.getToken();
23344            if (ksh instanceof KeySetHandle) {
23345                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23346                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23347            }
23348            return false;
23349        }
23350    }
23351
23352    private void deletePackageIfUnusedLPr(final String packageName) {
23353        PackageSetting ps = mSettings.mPackages.get(packageName);
23354        if (ps == null) {
23355            return;
23356        }
23357        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23358            // TODO Implement atomic delete if package is unused
23359            // It is currently possible that the package will be deleted even if it is installed
23360            // after this method returns.
23361            mHandler.post(new Runnable() {
23362                public void run() {
23363                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23364                            0, PackageManager.DELETE_ALL_USERS);
23365                }
23366            });
23367        }
23368    }
23369
23370    /**
23371     * Check and throw if the given before/after packages would be considered a
23372     * downgrade.
23373     */
23374    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23375            throws PackageManagerException {
23376        if (after.versionCode < before.mVersionCode) {
23377            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23378                    "Update version code " + after.versionCode + " is older than current "
23379                    + before.mVersionCode);
23380        } else if (after.versionCode == before.mVersionCode) {
23381            if (after.baseRevisionCode < before.baseRevisionCode) {
23382                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23383                        "Update base revision code " + after.baseRevisionCode
23384                        + " is older than current " + before.baseRevisionCode);
23385            }
23386
23387            if (!ArrayUtils.isEmpty(after.splitNames)) {
23388                for (int i = 0; i < after.splitNames.length; i++) {
23389                    final String splitName = after.splitNames[i];
23390                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23391                    if (j != -1) {
23392                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23393                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23394                                    "Update split " + splitName + " revision code "
23395                                    + after.splitRevisionCodes[i] + " is older than current "
23396                                    + before.splitRevisionCodes[j]);
23397                        }
23398                    }
23399                }
23400            }
23401        }
23402    }
23403
23404    private static class MoveCallbacks extends Handler {
23405        private static final int MSG_CREATED = 1;
23406        private static final int MSG_STATUS_CHANGED = 2;
23407
23408        private final RemoteCallbackList<IPackageMoveObserver>
23409                mCallbacks = new RemoteCallbackList<>();
23410
23411        private final SparseIntArray mLastStatus = new SparseIntArray();
23412
23413        public MoveCallbacks(Looper looper) {
23414            super(looper);
23415        }
23416
23417        public void register(IPackageMoveObserver callback) {
23418            mCallbacks.register(callback);
23419        }
23420
23421        public void unregister(IPackageMoveObserver callback) {
23422            mCallbacks.unregister(callback);
23423        }
23424
23425        @Override
23426        public void handleMessage(Message msg) {
23427            final SomeArgs args = (SomeArgs) msg.obj;
23428            final int n = mCallbacks.beginBroadcast();
23429            for (int i = 0; i < n; i++) {
23430                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23431                try {
23432                    invokeCallback(callback, msg.what, args);
23433                } catch (RemoteException ignored) {
23434                }
23435            }
23436            mCallbacks.finishBroadcast();
23437            args.recycle();
23438        }
23439
23440        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23441                throws RemoteException {
23442            switch (what) {
23443                case MSG_CREATED: {
23444                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23445                    break;
23446                }
23447                case MSG_STATUS_CHANGED: {
23448                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23449                    break;
23450                }
23451            }
23452        }
23453
23454        private void notifyCreated(int moveId, Bundle extras) {
23455            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23456
23457            final SomeArgs args = SomeArgs.obtain();
23458            args.argi1 = moveId;
23459            args.arg2 = extras;
23460            obtainMessage(MSG_CREATED, args).sendToTarget();
23461        }
23462
23463        private void notifyStatusChanged(int moveId, int status) {
23464            notifyStatusChanged(moveId, status, -1);
23465        }
23466
23467        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23468            Slog.v(TAG, "Move " + moveId + " status " + status);
23469
23470            final SomeArgs args = SomeArgs.obtain();
23471            args.argi1 = moveId;
23472            args.argi2 = status;
23473            args.arg3 = estMillis;
23474            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23475
23476            synchronized (mLastStatus) {
23477                mLastStatus.put(moveId, status);
23478            }
23479        }
23480    }
23481
23482    private final static class OnPermissionChangeListeners extends Handler {
23483        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23484
23485        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23486                new RemoteCallbackList<>();
23487
23488        public OnPermissionChangeListeners(Looper looper) {
23489            super(looper);
23490        }
23491
23492        @Override
23493        public void handleMessage(Message msg) {
23494            switch (msg.what) {
23495                case MSG_ON_PERMISSIONS_CHANGED: {
23496                    final int uid = msg.arg1;
23497                    handleOnPermissionsChanged(uid);
23498                } break;
23499            }
23500        }
23501
23502        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23503            mPermissionListeners.register(listener);
23504
23505        }
23506
23507        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23508            mPermissionListeners.unregister(listener);
23509        }
23510
23511        public void onPermissionsChanged(int uid) {
23512            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23513                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23514            }
23515        }
23516
23517        private void handleOnPermissionsChanged(int uid) {
23518            final int count = mPermissionListeners.beginBroadcast();
23519            try {
23520                for (int i = 0; i < count; i++) {
23521                    IOnPermissionsChangeListener callback = mPermissionListeners
23522                            .getBroadcastItem(i);
23523                    try {
23524                        callback.onPermissionsChanged(uid);
23525                    } catch (RemoteException e) {
23526                        Log.e(TAG, "Permission listener is dead", e);
23527                    }
23528                }
23529            } finally {
23530                mPermissionListeners.finishBroadcast();
23531            }
23532        }
23533    }
23534
23535    private class PackageManagerNative extends IPackageManagerNative.Stub {
23536        @Override
23537        public String[] getNamesForUids(int[] uids) throws RemoteException {
23538            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23539            // massage results so they can be parsed by the native binder
23540            for (int i = results.length - 1; i >= 0; --i) {
23541                if (results[i] == null) {
23542                    results[i] = "";
23543                }
23544            }
23545            return results;
23546        }
23547
23548        // NB: this differentiates between preloads and sideloads
23549        @Override
23550        public String getInstallerForPackage(String packageName) throws RemoteException {
23551            final String installerName = getInstallerPackageName(packageName);
23552            if (!TextUtils.isEmpty(installerName)) {
23553                return installerName;
23554            }
23555            // differentiate between preload and sideload
23556            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23557            ApplicationInfo appInfo = getApplicationInfo(packageName,
23558                                    /*flags*/ 0,
23559                                    /*userId*/ callingUser);
23560            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23561                return "preload";
23562            }
23563            return "";
23564        }
23565
23566        @Override
23567        public int getVersionCodeForPackage(String packageName) throws RemoteException {
23568            try {
23569                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23570                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23571                if (pInfo != null) {
23572                    return pInfo.versionCode;
23573                }
23574            } catch (Exception e) {
23575            }
23576            return 0;
23577        }
23578    }
23579
23580    private class PackageManagerInternalImpl extends PackageManagerInternal {
23581        @Override
23582        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23583                int flagValues, int userId) {
23584            PackageManagerService.this.updatePermissionFlags(
23585                    permName, packageName, flagMask, flagValues, userId);
23586        }
23587
23588        @Override
23589        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23590            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23591        }
23592
23593        @Override
23594        public PackageParser.PermissionGroup getPermissionGroupTEMP(String groupName) {
23595            synchronized (mPackages) {
23596                return mPermissionGroups.get(groupName);
23597            }
23598        }
23599
23600        @Override
23601        public boolean isInstantApp(String packageName, int userId) {
23602            return PackageManagerService.this.isInstantApp(packageName, userId);
23603        }
23604
23605        @Override
23606        public String getInstantAppPackageName(int uid) {
23607            return PackageManagerService.this.getInstantAppPackageName(uid);
23608        }
23609
23610        @Override
23611        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23612            synchronized (mPackages) {
23613                return PackageManagerService.this.filterAppAccessLPr(
23614                        (PackageSetting) pkg.mExtras, callingUid, userId);
23615            }
23616        }
23617
23618        @Override
23619        public PackageParser.Package getPackage(String packageName) {
23620            synchronized (mPackages) {
23621                packageName = resolveInternalPackageNameLPr(
23622                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23623                return mPackages.get(packageName);
23624            }
23625        }
23626
23627        @Override
23628        public PackageParser.Package getDisabledPackage(String packageName) {
23629            synchronized (mPackages) {
23630                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23631                return (ps != null) ? ps.pkg : null;
23632            }
23633        }
23634
23635        @Override
23636        public String getKnownPackageName(int knownPackage, int userId) {
23637            switch(knownPackage) {
23638                case PackageManagerInternal.PACKAGE_BROWSER:
23639                    return getDefaultBrowserPackageName(userId);
23640                case PackageManagerInternal.PACKAGE_INSTALLER:
23641                    return mRequiredInstallerPackage;
23642                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23643                    return mSetupWizardPackage;
23644                case PackageManagerInternal.PACKAGE_SYSTEM:
23645                    return "android";
23646                case PackageManagerInternal.PACKAGE_VERIFIER:
23647                    return mRequiredVerifierPackage;
23648            }
23649            return null;
23650        }
23651
23652        @Override
23653        public boolean isResolveActivityComponent(ComponentInfo component) {
23654            return mResolveActivity.packageName.equals(component.packageName)
23655                    && mResolveActivity.name.equals(component.name);
23656        }
23657
23658        @Override
23659        public void setLocationPackagesProvider(PackagesProvider provider) {
23660            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23661        }
23662
23663        @Override
23664        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23665            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23666        }
23667
23668        @Override
23669        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23670            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23671        }
23672
23673        @Override
23674        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23675            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23676        }
23677
23678        @Override
23679        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23680            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23681        }
23682
23683        @Override
23684        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23685            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23686        }
23687
23688        @Override
23689        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23690            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23691        }
23692
23693        @Override
23694        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23695            synchronized (mPackages) {
23696                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23697            }
23698            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23699        }
23700
23701        @Override
23702        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23703            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23704                    packageName, userId);
23705        }
23706
23707        @Override
23708        public void setKeepUninstalledPackages(final List<String> packageList) {
23709            Preconditions.checkNotNull(packageList);
23710            List<String> removedFromList = null;
23711            synchronized (mPackages) {
23712                if (mKeepUninstalledPackages != null) {
23713                    final int packagesCount = mKeepUninstalledPackages.size();
23714                    for (int i = 0; i < packagesCount; i++) {
23715                        String oldPackage = mKeepUninstalledPackages.get(i);
23716                        if (packageList != null && packageList.contains(oldPackage)) {
23717                            continue;
23718                        }
23719                        if (removedFromList == null) {
23720                            removedFromList = new ArrayList<>();
23721                        }
23722                        removedFromList.add(oldPackage);
23723                    }
23724                }
23725                mKeepUninstalledPackages = new ArrayList<>(packageList);
23726                if (removedFromList != null) {
23727                    final int removedCount = removedFromList.size();
23728                    for (int i = 0; i < removedCount; i++) {
23729                        deletePackageIfUnusedLPr(removedFromList.get(i));
23730                    }
23731                }
23732            }
23733        }
23734
23735        @Override
23736        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23737            synchronized (mPackages) {
23738                // If we do not support permission review, done.
23739                if (!mPermissionReviewRequired) {
23740                    return false;
23741                }
23742
23743                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23744                if (packageSetting == null) {
23745                    return false;
23746                }
23747
23748                // Permission review applies only to apps not supporting the new permission model.
23749                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23750                    return false;
23751                }
23752
23753                // Legacy apps have the permission and get user consent on launch.
23754                PermissionsState permissionsState = packageSetting.getPermissionsState();
23755                return permissionsState.isPermissionReviewRequired(userId);
23756            }
23757        }
23758
23759        @Override
23760        public PackageInfo getPackageInfo(
23761                String packageName, int flags, int filterCallingUid, int userId) {
23762            return PackageManagerService.this
23763                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23764                            flags, filterCallingUid, userId);
23765        }
23766
23767        @Override
23768        public ApplicationInfo getApplicationInfo(
23769                String packageName, int flags, int filterCallingUid, int userId) {
23770            return PackageManagerService.this
23771                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23772        }
23773
23774        @Override
23775        public ActivityInfo getActivityInfo(
23776                ComponentName component, int flags, int filterCallingUid, int userId) {
23777            return PackageManagerService.this
23778                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23779        }
23780
23781        @Override
23782        public List<ResolveInfo> queryIntentActivities(
23783                Intent intent, int flags, int filterCallingUid, int userId) {
23784            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23785            return PackageManagerService.this
23786                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23787                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23788        }
23789
23790        @Override
23791        public List<ResolveInfo> queryIntentServices(
23792                Intent intent, int flags, int callingUid, int userId) {
23793            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23794            return PackageManagerService.this
23795                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23796                            false);
23797        }
23798
23799        @Override
23800        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23801                int userId) {
23802            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23803        }
23804
23805        @Override
23806        public void setDeviceAndProfileOwnerPackages(
23807                int deviceOwnerUserId, String deviceOwnerPackage,
23808                SparseArray<String> profileOwnerPackages) {
23809            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23810                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23811        }
23812
23813        @Override
23814        public boolean isPackageDataProtected(int userId, String packageName) {
23815            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23816        }
23817
23818        @Override
23819        public boolean isPackageEphemeral(int userId, String packageName) {
23820            synchronized (mPackages) {
23821                final PackageSetting ps = mSettings.mPackages.get(packageName);
23822                return ps != null ? ps.getInstantApp(userId) : false;
23823            }
23824        }
23825
23826        @Override
23827        public boolean wasPackageEverLaunched(String packageName, int userId) {
23828            synchronized (mPackages) {
23829                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23830            }
23831        }
23832
23833        @Override
23834        public void grantRuntimePermission(String packageName, String permName, int userId,
23835                boolean overridePolicy) {
23836            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23837                    permName, packageName, overridePolicy, getCallingUid(), userId,
23838                    mPermissionCallback);
23839        }
23840
23841        @Override
23842        public void revokeRuntimePermission(String packageName, String permName, int userId,
23843                boolean overridePolicy) {
23844            mPermissionManager.revokeRuntimePermission(
23845                    permName, packageName, overridePolicy, getCallingUid(), userId,
23846                    mPermissionCallback);
23847        }
23848
23849        @Override
23850        public String getNameForUid(int uid) {
23851            return PackageManagerService.this.getNameForUid(uid);
23852        }
23853
23854        @Override
23855        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23856                Intent origIntent, String resolvedType, String callingPackage,
23857                Bundle verificationBundle, int userId) {
23858            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23859                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23860                    userId);
23861        }
23862
23863        @Override
23864        public void grantEphemeralAccess(int userId, Intent intent,
23865                int targetAppId, int ephemeralAppId) {
23866            synchronized (mPackages) {
23867                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23868                        targetAppId, ephemeralAppId);
23869            }
23870        }
23871
23872        @Override
23873        public boolean isInstantAppInstallerComponent(ComponentName component) {
23874            synchronized (mPackages) {
23875                return mInstantAppInstallerActivity != null
23876                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23877            }
23878        }
23879
23880        @Override
23881        public void pruneInstantApps() {
23882            mInstantAppRegistry.pruneInstantApps();
23883        }
23884
23885        @Override
23886        public String getSetupWizardPackageName() {
23887            return mSetupWizardPackage;
23888        }
23889
23890        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23891            if (policy != null) {
23892                mExternalSourcesPolicy = policy;
23893            }
23894        }
23895
23896        @Override
23897        public boolean isPackagePersistent(String packageName) {
23898            synchronized (mPackages) {
23899                PackageParser.Package pkg = mPackages.get(packageName);
23900                return pkg != null
23901                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23902                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23903                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23904                        : false;
23905            }
23906        }
23907
23908        @Override
23909        public List<PackageInfo> getOverlayPackages(int userId) {
23910            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23911            synchronized (mPackages) {
23912                for (PackageParser.Package p : mPackages.values()) {
23913                    if (p.mOverlayTarget != null) {
23914                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23915                        if (pkg != null) {
23916                            overlayPackages.add(pkg);
23917                        }
23918                    }
23919                }
23920            }
23921            return overlayPackages;
23922        }
23923
23924        @Override
23925        public List<String> getTargetPackageNames(int userId) {
23926            List<String> targetPackages = new ArrayList<>();
23927            synchronized (mPackages) {
23928                for (PackageParser.Package p : mPackages.values()) {
23929                    if (p.mOverlayTarget == null) {
23930                        targetPackages.add(p.packageName);
23931                    }
23932                }
23933            }
23934            return targetPackages;
23935        }
23936
23937        @Override
23938        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23939                @Nullable List<String> overlayPackageNames) {
23940            synchronized (mPackages) {
23941                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23942                    Slog.e(TAG, "failed to find package " + targetPackageName);
23943                    return false;
23944                }
23945                ArrayList<String> overlayPaths = null;
23946                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23947                    final int N = overlayPackageNames.size();
23948                    overlayPaths = new ArrayList<>(N);
23949                    for (int i = 0; i < N; i++) {
23950                        final String packageName = overlayPackageNames.get(i);
23951                        final PackageParser.Package pkg = mPackages.get(packageName);
23952                        if (pkg == null) {
23953                            Slog.e(TAG, "failed to find package " + packageName);
23954                            return false;
23955                        }
23956                        overlayPaths.add(pkg.baseCodePath);
23957                    }
23958                }
23959
23960                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23961                ps.setOverlayPaths(overlayPaths, userId);
23962                return true;
23963            }
23964        }
23965
23966        @Override
23967        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23968                int flags, int userId, boolean resolveForStart) {
23969            return resolveIntentInternal(
23970                    intent, resolvedType, flags, userId, resolveForStart);
23971        }
23972
23973        @Override
23974        public ResolveInfo resolveService(Intent intent, String resolvedType,
23975                int flags, int userId, int callingUid) {
23976            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23977        }
23978
23979        @Override
23980        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23981            return PackageManagerService.this.resolveContentProviderInternal(
23982                    name, flags, userId);
23983        }
23984
23985        @Override
23986        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23987            synchronized (mPackages) {
23988                mIsolatedOwners.put(isolatedUid, ownerUid);
23989            }
23990        }
23991
23992        @Override
23993        public void removeIsolatedUid(int isolatedUid) {
23994            synchronized (mPackages) {
23995                mIsolatedOwners.delete(isolatedUid);
23996            }
23997        }
23998
23999        @Override
24000        public int getUidTargetSdkVersion(int uid) {
24001            synchronized (mPackages) {
24002                return getUidTargetSdkVersionLockedLPr(uid);
24003            }
24004        }
24005
24006        @Override
24007        public boolean canAccessInstantApps(int callingUid, int userId) {
24008            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24009        }
24010
24011        @Override
24012        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24013            synchronized (mPackages) {
24014                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24015            }
24016        }
24017
24018        @Override
24019        public void notifyPackageUse(String packageName, int reason) {
24020            synchronized (mPackages) {
24021                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24022            }
24023        }
24024    }
24025
24026    @Override
24027    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24028        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24029        synchronized (mPackages) {
24030            final long identity = Binder.clearCallingIdentity();
24031            try {
24032                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24033                        packageNames, userId);
24034            } finally {
24035                Binder.restoreCallingIdentity(identity);
24036            }
24037        }
24038    }
24039
24040    @Override
24041    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24042        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24043        synchronized (mPackages) {
24044            final long identity = Binder.clearCallingIdentity();
24045            try {
24046                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24047                        packageNames, userId);
24048            } finally {
24049                Binder.restoreCallingIdentity(identity);
24050            }
24051        }
24052    }
24053
24054    private static void enforceSystemOrPhoneCaller(String tag) {
24055        int callingUid = Binder.getCallingUid();
24056        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24057            throw new SecurityException(
24058                    "Cannot call " + tag + " from UID " + callingUid);
24059        }
24060    }
24061
24062    boolean isHistoricalPackageUsageAvailable() {
24063        return mPackageUsage.isHistoricalPackageUsageAvailable();
24064    }
24065
24066    /**
24067     * Return a <b>copy</b> of the collection of packages known to the package manager.
24068     * @return A copy of the values of mPackages.
24069     */
24070    Collection<PackageParser.Package> getPackages() {
24071        synchronized (mPackages) {
24072            return new ArrayList<>(mPackages.values());
24073        }
24074    }
24075
24076    /**
24077     * Logs process start information (including base APK hash) to the security log.
24078     * @hide
24079     */
24080    @Override
24081    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24082            String apkFile, int pid) {
24083        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24084            return;
24085        }
24086        if (!SecurityLog.isLoggingEnabled()) {
24087            return;
24088        }
24089        Bundle data = new Bundle();
24090        data.putLong("startTimestamp", System.currentTimeMillis());
24091        data.putString("processName", processName);
24092        data.putInt("uid", uid);
24093        data.putString("seinfo", seinfo);
24094        data.putString("apkFile", apkFile);
24095        data.putInt("pid", pid);
24096        Message msg = mProcessLoggingHandler.obtainMessage(
24097                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24098        msg.setData(data);
24099        mProcessLoggingHandler.sendMessage(msg);
24100    }
24101
24102    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24103        return mCompilerStats.getPackageStats(pkgName);
24104    }
24105
24106    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24107        return getOrCreateCompilerPackageStats(pkg.packageName);
24108    }
24109
24110    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24111        return mCompilerStats.getOrCreatePackageStats(pkgName);
24112    }
24113
24114    public void deleteCompilerPackageStats(String pkgName) {
24115        mCompilerStats.deletePackageStats(pkgName);
24116    }
24117
24118    @Override
24119    public int getInstallReason(String packageName, int userId) {
24120        final int callingUid = Binder.getCallingUid();
24121        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24122                true /* requireFullPermission */, false /* checkShell */,
24123                "get install reason");
24124        synchronized (mPackages) {
24125            final PackageSetting ps = mSettings.mPackages.get(packageName);
24126            if (filterAppAccessLPr(ps, callingUid, userId)) {
24127                return PackageManager.INSTALL_REASON_UNKNOWN;
24128            }
24129            if (ps != null) {
24130                return ps.getInstallReason(userId);
24131            }
24132        }
24133        return PackageManager.INSTALL_REASON_UNKNOWN;
24134    }
24135
24136    @Override
24137    public boolean canRequestPackageInstalls(String packageName, int userId) {
24138        return canRequestPackageInstallsInternal(packageName, 0, userId,
24139                true /* throwIfPermNotDeclared*/);
24140    }
24141
24142    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24143            boolean throwIfPermNotDeclared) {
24144        int callingUid = Binder.getCallingUid();
24145        int uid = getPackageUid(packageName, 0, userId);
24146        if (callingUid != uid && callingUid != Process.ROOT_UID
24147                && callingUid != Process.SYSTEM_UID) {
24148            throw new SecurityException(
24149                    "Caller uid " + callingUid + " does not own package " + packageName);
24150        }
24151        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24152        if (info == null) {
24153            return false;
24154        }
24155        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24156            return false;
24157        }
24158        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24159        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24160        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24161            if (throwIfPermNotDeclared) {
24162                throw new SecurityException("Need to declare " + appOpPermission
24163                        + " to call this api");
24164            } else {
24165                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24166                return false;
24167            }
24168        }
24169        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24170            return false;
24171        }
24172        if (mExternalSourcesPolicy != null) {
24173            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24174            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24175                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24176            }
24177        }
24178        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24179    }
24180
24181    @Override
24182    public ComponentName getInstantAppResolverSettingsComponent() {
24183        return mInstantAppResolverSettingsComponent;
24184    }
24185
24186    @Override
24187    public ComponentName getInstantAppInstallerComponent() {
24188        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24189            return null;
24190        }
24191        return mInstantAppInstallerActivity == null
24192                ? null : mInstantAppInstallerActivity.getComponentName();
24193    }
24194
24195    @Override
24196    public String getInstantAppAndroidId(String packageName, int userId) {
24197        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24198                "getInstantAppAndroidId");
24199        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24200                true /* requireFullPermission */, false /* checkShell */,
24201                "getInstantAppAndroidId");
24202        // Make sure the target is an Instant App.
24203        if (!isInstantApp(packageName, userId)) {
24204            return null;
24205        }
24206        synchronized (mPackages) {
24207            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24208        }
24209    }
24210
24211    boolean canHaveOatDir(String packageName) {
24212        synchronized (mPackages) {
24213            PackageParser.Package p = mPackages.get(packageName);
24214            if (p == null) {
24215                return false;
24216            }
24217            return p.canHaveOatDir();
24218        }
24219    }
24220
24221    private String getOatDir(PackageParser.Package pkg) {
24222        if (!pkg.canHaveOatDir()) {
24223            return null;
24224        }
24225        File codePath = new File(pkg.codePath);
24226        if (codePath.isDirectory()) {
24227            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24228        }
24229        return null;
24230    }
24231
24232    void deleteOatArtifactsOfPackage(String packageName) {
24233        final String[] instructionSets;
24234        final List<String> codePaths;
24235        final String oatDir;
24236        final PackageParser.Package pkg;
24237        synchronized (mPackages) {
24238            pkg = mPackages.get(packageName);
24239        }
24240        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24241        codePaths = pkg.getAllCodePaths();
24242        oatDir = getOatDir(pkg);
24243
24244        for (String codePath : codePaths) {
24245            for (String isa : instructionSets) {
24246                try {
24247                    mInstaller.deleteOdex(codePath, isa, oatDir);
24248                } catch (InstallerException e) {
24249                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24250                }
24251            }
24252        }
24253    }
24254
24255    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24256        Set<String> unusedPackages = new HashSet<>();
24257        long currentTimeInMillis = System.currentTimeMillis();
24258        synchronized (mPackages) {
24259            for (PackageParser.Package pkg : mPackages.values()) {
24260                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24261                if (ps == null) {
24262                    continue;
24263                }
24264                PackageDexUsage.PackageUseInfo packageUseInfo =
24265                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24266                if (PackageManagerServiceUtils
24267                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24268                                downgradeTimeThresholdMillis, packageUseInfo,
24269                                pkg.getLatestPackageUseTimeInMills(),
24270                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24271                    unusedPackages.add(pkg.packageName);
24272                }
24273            }
24274        }
24275        return unusedPackages;
24276    }
24277}
24278
24279interface PackageSender {
24280    void sendPackageBroadcast(final String action, final String pkg,
24281        final Bundle extras, final int flags, final String targetPkg,
24282        final IIntentReceiver finishedReceiver, final int[] userIds);
24283    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24284        boolean includeStopped, int appId, int... userIds);
24285}
24286