PackageManagerService.java revision dccef33d901398b1f39a8fea4dd919d57c5643f2
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.SET_HARMFUL_APP_WARNINGS;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
26import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.app.ActivityManager;
121import android.app.ActivityManagerInternal;
122import android.app.AppOpsManager;
123import android.app.IActivityManager;
124import android.app.ResourcesManager;
125import android.app.admin.IDevicePolicyManager;
126import android.app.admin.SecurityLog;
127import android.app.backup.IBackupManager;
128import android.content.BroadcastReceiver;
129import android.content.ComponentName;
130import android.content.ContentResolver;
131import android.content.Context;
132import android.content.IIntentReceiver;
133import android.content.Intent;
134import android.content.IntentFilter;
135import android.content.IntentSender;
136import android.content.IntentSender.SendIntentException;
137import android.content.ServiceConnection;
138import android.content.pm.ActivityInfo;
139import android.content.pm.ApplicationInfo;
140import android.content.pm.AppsQueryHelper;
141import android.content.pm.AuxiliaryResolveInfo;
142import android.content.pm.ChangedPackages;
143import android.content.pm.ComponentInfo;
144import android.content.pm.FallbackCategoryProvider;
145import android.content.pm.FeatureInfo;
146import android.content.pm.IDexModuleRegisterCallback;
147import android.content.pm.IOnPermissionsChangeListener;
148import android.content.pm.IPackageDataObserver;
149import android.content.pm.IPackageDeleteObserver;
150import android.content.pm.IPackageDeleteObserver2;
151import android.content.pm.IPackageInstallObserver2;
152import android.content.pm.IPackageInstaller;
153import android.content.pm.IPackageManager;
154import android.content.pm.IPackageManagerNative;
155import android.content.pm.IPackageMoveObserver;
156import android.content.pm.IPackageStatsObserver;
157import android.content.pm.InstantAppInfo;
158import android.content.pm.InstantAppRequest;
159import android.content.pm.InstantAppResolveInfo;
160import android.content.pm.InstrumentationInfo;
161import android.content.pm.IntentFilterVerificationInfo;
162import android.content.pm.KeySet;
163import android.content.pm.PackageCleanItem;
164import android.content.pm.PackageInfo;
165import android.content.pm.PackageInfoLite;
166import android.content.pm.PackageInstaller;
167import android.content.pm.PackageList;
168import android.content.pm.PackageManager;
169import android.content.pm.PackageManagerInternal;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal.PackageListObserver;
172import android.content.pm.PackageParser;
173import android.content.pm.PackageParser.ActivityIntentInfo;
174import android.content.pm.PackageParser.Package;
175import android.content.pm.PackageParser.PackageLite;
176import android.content.pm.PackageParser.PackageParserException;
177import android.content.pm.PackageParser.ParseFlags;
178import android.content.pm.PackageParser.ServiceIntentInfo;
179import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
180import android.content.pm.PackageStats;
181import android.content.pm.PackageUserState;
182import android.content.pm.ParceledListSlice;
183import android.content.pm.PermissionGroupInfo;
184import android.content.pm.PermissionInfo;
185import android.content.pm.ProviderInfo;
186import android.content.pm.ResolveInfo;
187import android.content.pm.ServiceInfo;
188import android.content.pm.SharedLibraryInfo;
189import android.content.pm.Signature;
190import android.content.pm.UserInfo;
191import android.content.pm.VerifierDeviceIdentity;
192import android.content.pm.VerifierInfo;
193import android.content.pm.VersionedPackage;
194import android.content.pm.dex.ArtManager;
195import android.content.pm.dex.DexMetadataHelper;
196import android.content.pm.dex.IArtManager;
197import android.content.res.Resources;
198import android.database.ContentObserver;
199import android.graphics.Bitmap;
200import android.hardware.display.DisplayManager;
201import android.net.Uri;
202import android.os.Binder;
203import android.os.Build;
204import android.os.Bundle;
205import android.os.Debug;
206import android.os.Environment;
207import android.os.Environment.UserEnvironment;
208import android.os.FileUtils;
209import android.os.Handler;
210import android.os.IBinder;
211import android.os.Looper;
212import android.os.Message;
213import android.os.Parcel;
214import android.os.ParcelFileDescriptor;
215import android.os.PatternMatcher;
216import android.os.Process;
217import android.os.RemoteCallbackList;
218import android.os.RemoteException;
219import android.os.ResultReceiver;
220import android.os.SELinux;
221import android.os.ServiceManager;
222import android.os.ShellCallback;
223import android.os.SystemClock;
224import android.os.SystemProperties;
225import android.os.Trace;
226import android.os.UserHandle;
227import android.os.UserManager;
228import android.os.UserManagerInternal;
229import android.os.storage.IStorageManager;
230import android.os.storage.StorageEventListener;
231import android.os.storage.StorageManager;
232import android.os.storage.StorageManagerInternal;
233import android.os.storage.VolumeInfo;
234import android.os.storage.VolumeRecord;
235import android.provider.Settings.Global;
236import android.provider.Settings.Secure;
237import android.security.KeyStore;
238import android.security.SystemKeyStore;
239import android.service.pm.PackageServiceDumpProto;
240import android.system.ErrnoException;
241import android.system.Os;
242import android.text.TextUtils;
243import android.text.format.DateUtils;
244import android.util.ArrayMap;
245import android.util.ArraySet;
246import android.util.Base64;
247import android.util.ByteStringUtils;
248import android.util.DisplayMetrics;
249import android.util.EventLog;
250import android.util.ExceptionUtils;
251import android.util.Log;
252import android.util.LogPrinter;
253import android.util.LongSparseArray;
254import android.util.LongSparseLongArray;
255import android.util.MathUtils;
256import android.util.PackageUtils;
257import android.util.Pair;
258import android.util.PrintStreamPrinter;
259import android.util.Slog;
260import android.util.SparseArray;
261import android.util.SparseBooleanArray;
262import android.util.SparseIntArray;
263import android.util.TimingsTraceLog;
264import android.util.Xml;
265import android.util.jar.StrictJarFile;
266import android.util.proto.ProtoOutputStream;
267import android.view.Display;
268
269import com.android.internal.R;
270import com.android.internal.annotations.GuardedBy;
271import com.android.internal.app.IMediaContainerService;
272import com.android.internal.app.ResolverActivity;
273import com.android.internal.content.NativeLibraryHelper;
274import com.android.internal.content.PackageHelper;
275import com.android.internal.logging.MetricsLogger;
276import com.android.internal.os.IParcelFileDescriptorFactory;
277import com.android.internal.os.SomeArgs;
278import com.android.internal.os.Zygote;
279import com.android.internal.telephony.CarrierAppUtils;
280import com.android.internal.util.ArrayUtils;
281import com.android.internal.util.ConcurrentUtils;
282import com.android.internal.util.DumpUtils;
283import com.android.internal.util.FastXmlSerializer;
284import com.android.internal.util.IndentingPrintWriter;
285import com.android.internal.util.Preconditions;
286import com.android.internal.util.XmlUtils;
287import com.android.server.AttributeCache;
288import com.android.server.DeviceIdleController;
289import com.android.server.EventLogTags;
290import com.android.server.FgThread;
291import com.android.server.IntentResolver;
292import com.android.server.LocalServices;
293import com.android.server.LockGuard;
294import com.android.server.ServiceThread;
295import com.android.server.SystemConfig;
296import com.android.server.SystemServerInitThreadPool;
297import com.android.server.Watchdog;
298import com.android.server.net.NetworkPolicyManagerInternal;
299import com.android.server.pm.Installer.InstallerException;
300import com.android.server.pm.Settings.DatabaseVersion;
301import com.android.server.pm.Settings.VersionInfo;
302import com.android.server.pm.dex.ArtManagerService;
303import com.android.server.pm.dex.DexLogger;
304import com.android.server.pm.dex.DexManager;
305import com.android.server.pm.dex.DexoptOptions;
306import com.android.server.pm.dex.PackageDexUsage;
307import com.android.server.pm.permission.BasePermission;
308import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
309import com.android.server.pm.permission.PermissionManagerService;
310import com.android.server.pm.permission.PermissionManagerInternal;
311import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
312import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
313import com.android.server.pm.permission.PermissionsState;
314import com.android.server.pm.permission.PermissionsState.PermissionState;
315import com.android.server.security.VerityUtils;
316import com.android.server.storage.DeviceStorageMonitorInternal;
317
318import dalvik.system.CloseGuard;
319import dalvik.system.VMRuntime;
320
321import libcore.io.IoUtils;
322
323import org.xmlpull.v1.XmlPullParser;
324import org.xmlpull.v1.XmlPullParserException;
325import org.xmlpull.v1.XmlSerializer;
326
327import java.io.BufferedOutputStream;
328import java.io.ByteArrayInputStream;
329import java.io.ByteArrayOutputStream;
330import java.io.File;
331import java.io.FileDescriptor;
332import java.io.FileInputStream;
333import java.io.FileOutputStream;
334import java.io.FilenameFilter;
335import java.io.IOException;
336import java.io.PrintWriter;
337import java.lang.annotation.Retention;
338import java.lang.annotation.RetentionPolicy;
339import java.nio.charset.StandardCharsets;
340import java.security.DigestException;
341import java.security.DigestInputStream;
342import java.security.MessageDigest;
343import java.security.NoSuchAlgorithmException;
344import java.security.PublicKey;
345import java.security.SecureRandom;
346import java.security.cert.CertificateException;
347import java.util.ArrayList;
348import java.util.Arrays;
349import java.util.Collection;
350import java.util.Collections;
351import java.util.Comparator;
352import java.util.HashMap;
353import java.util.HashSet;
354import java.util.Iterator;
355import java.util.LinkedHashSet;
356import java.util.List;
357import java.util.Map;
358import java.util.Objects;
359import java.util.Set;
360import java.util.concurrent.CountDownLatch;
361import java.util.concurrent.Future;
362import java.util.concurrent.TimeUnit;
363import java.util.concurrent.atomic.AtomicBoolean;
364import java.util.concurrent.atomic.AtomicInteger;
365
366/**
367 * Keep track of all those APKs everywhere.
368 * <p>
369 * Internally there are two important locks:
370 * <ul>
371 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
372 * and other related state. It is a fine-grained lock that should only be held
373 * momentarily, as it's one of the most contended locks in the system.
374 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
375 * operations typically involve heavy lifting of application data on disk. Since
376 * {@code installd} is single-threaded, and it's operations can often be slow,
377 * this lock should never be acquired while already holding {@link #mPackages}.
378 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
379 * holding {@link #mInstallLock}.
380 * </ul>
381 * Many internal methods rely on the caller to hold the appropriate locks, and
382 * this contract is expressed through method name suffixes:
383 * <ul>
384 * <li>fooLI(): the caller must hold {@link #mInstallLock}
385 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
386 * being modified must be frozen
387 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
388 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
389 * </ul>
390 * <p>
391 * Because this class is very central to the platform's security; please run all
392 * CTS and unit tests whenever making modifications:
393 *
394 * <pre>
395 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
396 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
397 * </pre>
398 */
399public class PackageManagerService extends IPackageManager.Stub
400        implements PackageSender {
401    static final String TAG = "PackageManager";
402    public static final boolean DEBUG_SETTINGS = false;
403    static final boolean DEBUG_PREFERRED = false;
404    static final boolean DEBUG_UPGRADE = false;
405    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
406    private static final boolean DEBUG_BACKUP = false;
407    public static final boolean DEBUG_INSTALL = false;
408    public static final boolean DEBUG_REMOVE = false;
409    private static final boolean DEBUG_BROADCASTS = false;
410    private static final boolean DEBUG_SHOW_INFO = false;
411    private static final boolean DEBUG_PACKAGE_INFO = false;
412    private static final boolean DEBUG_INTENT_MATCHING = false;
413    public static final boolean DEBUG_PACKAGE_SCANNING = false;
414    private static final boolean DEBUG_VERIFY = false;
415    private static final boolean DEBUG_FILTERS = false;
416    public static final boolean DEBUG_PERMISSIONS = false;
417    private static final boolean DEBUG_SHARED_LIBRARIES = false;
418    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
419
420    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
421    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
422    // user, but by default initialize to this.
423    public static final boolean DEBUG_DEXOPT = false;
424
425    private static final boolean DEBUG_ABI_SELECTION = false;
426    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
427    private static final boolean DEBUG_TRIAGED_MISSING = false;
428    private static final boolean DEBUG_APP_DATA = false;
429
430    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
431    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
432
433    private static final boolean HIDE_EPHEMERAL_APIS = false;
434
435    private static final boolean ENABLE_FREE_CACHE_V2 =
436            SystemProperties.getBoolean("fw.free_cache_v2", true);
437
438    private static final int RADIO_UID = Process.PHONE_UID;
439    private static final int LOG_UID = Process.LOG_UID;
440    private static final int NFC_UID = Process.NFC_UID;
441    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
442    private static final int SHELL_UID = Process.SHELL_UID;
443    private static final int SE_UID = Process.SE_UID;
444
445    // Suffix used during package installation when copying/moving
446    // package apks to install directory.
447    private static final String INSTALL_PACKAGE_SUFFIX = "-";
448
449    static final int SCAN_NO_DEX = 1<<0;
450    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
451    static final int SCAN_NEW_INSTALL = 1<<2;
452    static final int SCAN_UPDATE_TIME = 1<<3;
453    static final int SCAN_BOOTING = 1<<4;
454    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
455    static final int SCAN_REQUIRE_KNOWN = 1<<7;
456    static final int SCAN_MOVE = 1<<8;
457    static final int SCAN_INITIAL = 1<<9;
458    static final int SCAN_CHECK_ONLY = 1<<10;
459    static final int SCAN_DONT_KILL_APP = 1<<11;
460    static final int SCAN_IGNORE_FROZEN = 1<<12;
461    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
462    static final int SCAN_AS_INSTANT_APP = 1<<14;
463    static final int SCAN_AS_FULL_APP = 1<<15;
464    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
465    static final int SCAN_AS_SYSTEM = 1<<17;
466    static final int SCAN_AS_PRIVILEGED = 1<<18;
467    static final int SCAN_AS_OEM = 1<<19;
468    static final int SCAN_AS_VENDOR = 1<<20;
469    static final int SCAN_AS_PRODUCT = 1<<21;
470
471    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
472            SCAN_NO_DEX,
473            SCAN_UPDATE_SIGNATURE,
474            SCAN_NEW_INSTALL,
475            SCAN_UPDATE_TIME,
476            SCAN_BOOTING,
477            SCAN_DELETE_DATA_ON_FAILURES,
478            SCAN_REQUIRE_KNOWN,
479            SCAN_MOVE,
480            SCAN_INITIAL,
481            SCAN_CHECK_ONLY,
482            SCAN_DONT_KILL_APP,
483            SCAN_IGNORE_FROZEN,
484            SCAN_FIRST_BOOT_OR_UPGRADE,
485            SCAN_AS_INSTANT_APP,
486            SCAN_AS_FULL_APP,
487            SCAN_AS_VIRTUAL_PRELOAD,
488    })
489    @Retention(RetentionPolicy.SOURCE)
490    public @interface ScanFlags {}
491
492    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
493    /** Extension of the compressed packages */
494    public final static String COMPRESSED_EXTENSION = ".gz";
495    /** Suffix of stub packages on the system partition */
496    public final static String STUB_SUFFIX = "-Stub";
497
498    private static final int[] EMPTY_INT_ARRAY = new int[0];
499
500    private static final int TYPE_UNKNOWN = 0;
501    private static final int TYPE_ACTIVITY = 1;
502    private static final int TYPE_RECEIVER = 2;
503    private static final int TYPE_SERVICE = 3;
504    private static final int TYPE_PROVIDER = 4;
505    @IntDef(prefix = { "TYPE_" }, value = {
506            TYPE_UNKNOWN,
507            TYPE_ACTIVITY,
508            TYPE_RECEIVER,
509            TYPE_SERVICE,
510            TYPE_PROVIDER,
511    })
512    @Retention(RetentionPolicy.SOURCE)
513    public @interface ComponentType {}
514
515    /**
516     * Timeout (in milliseconds) after which the watchdog should declare that
517     * our handler thread is wedged.  The usual default for such things is one
518     * minute but we sometimes do very lengthy I/O operations on this thread,
519     * such as installing multi-gigabyte applications, so ours needs to be longer.
520     */
521    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
522
523    /**
524     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
525     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
526     * settings entry if available, otherwise we use the hardcoded default.  If it's been
527     * more than this long since the last fstrim, we force one during the boot sequence.
528     *
529     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
530     * one gets run at the next available charging+idle time.  This final mandatory
531     * no-fstrim check kicks in only of the other scheduling criteria is never met.
532     */
533    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
534
535    /**
536     * Whether verification is enabled by default.
537     */
538    private static final boolean DEFAULT_VERIFY_ENABLE = true;
539
540    /**
541     * The default maximum time to wait for the verification agent to return in
542     * milliseconds.
543     */
544    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
545
546    /**
547     * The default response for package verification timeout.
548     *
549     * This can be either PackageManager.VERIFICATION_ALLOW or
550     * PackageManager.VERIFICATION_REJECT.
551     */
552    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
553
554    public static final String PLATFORM_PACKAGE_NAME = "android";
555
556    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
557
558    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
559            DEFAULT_CONTAINER_PACKAGE,
560            "com.android.defcontainer.DefaultContainerService");
561
562    private static final String KILL_APP_REASON_GIDS_CHANGED =
563            "permission grant or revoke changed gids";
564
565    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
566            "permissions revoked";
567
568    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
569
570    private static final String PACKAGE_SCHEME = "package";
571
572    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
573
574    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
575
576    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
577
578    /** Canonical intent used to identify what counts as a "web browser" app */
579    private static final Intent sBrowserIntent;
580    static {
581        sBrowserIntent = new Intent();
582        sBrowserIntent.setAction(Intent.ACTION_VIEW);
583        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
584        sBrowserIntent.setData(Uri.parse("http:"));
585        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
586    }
587
588    /**
589     * The set of all protected actions [i.e. those actions for which a high priority
590     * intent filter is disallowed].
591     */
592    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
593    static {
594        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
595        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
596        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
597        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
598    }
599
600    // Compilation reasons.
601    public static final int REASON_FIRST_BOOT = 0;
602    public static final int REASON_BOOT = 1;
603    public static final int REASON_INSTALL = 2;
604    public static final int REASON_BACKGROUND_DEXOPT = 3;
605    public static final int REASON_AB_OTA = 4;
606    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
607    public static final int REASON_SHARED = 6;
608
609    public static final int REASON_LAST = REASON_SHARED;
610
611    /**
612     * Version number for the package parser cache. Increment this whenever the format or
613     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
614     */
615    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
616
617    /**
618     * Whether the package parser cache is enabled.
619     */
620    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
621
622    /**
623     * Permissions required in order to receive instant application lifecycle broadcasts.
624     */
625    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
626            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
627
628    final ServiceThread mHandlerThread;
629
630    final PackageHandler mHandler;
631
632    private final ProcessLoggingHandler mProcessLoggingHandler;
633
634    /**
635     * Messages for {@link #mHandler} that need to wait for system ready before
636     * being dispatched.
637     */
638    private ArrayList<Message> mPostSystemReadyMessages;
639
640    final int mSdkVersion = Build.VERSION.SDK_INT;
641
642    final Context mContext;
643    final boolean mFactoryTest;
644    final boolean mOnlyCore;
645    final DisplayMetrics mMetrics;
646    final int mDefParseFlags;
647    final String[] mSeparateProcesses;
648    final boolean mIsUpgrade;
649    final boolean mIsPreNUpgrade;
650    final boolean mIsPreNMR1Upgrade;
651
652    // Have we told the Activity Manager to whitelist the default container service by uid yet?
653    @GuardedBy("mPackages")
654    boolean mDefaultContainerWhitelisted = false;
655
656    @GuardedBy("mPackages")
657    private boolean mDexOptDialogShown;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed applications are stored */
665    private static final File sAppInstallDir =
666            new File(Environment.getDataDirectory(), "app");
667    /** Directory where installed application's 32-bit native libraries are copied. */
668    private static final File sAppLib32InstallDir =
669            new File(Environment.getDataDirectory(), "app-lib");
670    /** Directory where code and non-resource assets of forward-locked applications are stored */
671    private static final File sDrmAppPrivateInstallDir =
672            new File(Environment.getDataDirectory(), "app-private");
673
674    // ----------------------------------------------------------------
675
676    // Lock for state used when installing and doing other long running
677    // operations.  Methods that must be called with this lock held have
678    // the suffix "LI".
679    final Object mInstallLock = new Object();
680
681    // ----------------------------------------------------------------
682
683    // Keys are String (package name), values are Package.  This also serves
684    // as the lock for the global state.  Methods that must be called with
685    // this lock held have the prefix "LP".
686    @GuardedBy("mPackages")
687    final ArrayMap<String, PackageParser.Package> mPackages =
688            new ArrayMap<String, PackageParser.Package>();
689
690    final ArrayMap<String, Set<String>> mKnownCodebase =
691            new ArrayMap<String, Set<String>>();
692
693    // Keys are isolated uids and values are the uid of the application
694    // that created the isolated proccess.
695    @GuardedBy("mPackages")
696    final SparseIntArray mIsolatedOwners = new SparseIntArray();
697
698    /**
699     * Tracks new system packages [received in an OTA] that we expect to
700     * find updated user-installed versions. Keys are package name, values
701     * are package location.
702     */
703    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
704    /**
705     * Tracks high priority intent filters for protected actions. During boot, certain
706     * filter actions are protected and should never be allowed to have a high priority
707     * intent filter for them. However, there is one, and only one exception -- the
708     * setup wizard. It must be able to define a high priority intent filter for these
709     * actions to ensure there are no escapes from the wizard. We need to delay processing
710     * of these during boot as we need to look at all of the system packages in order
711     * to know which component is the setup wizard.
712     */
713    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
714    /**
715     * Whether or not processing protected filters should be deferred.
716     */
717    private boolean mDeferProtectedFilters = true;
718
719    /**
720     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
721     */
722    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
723    /**
724     * Whether or not system app permissions should be promoted from install to runtime.
725     */
726    boolean mPromoteSystemApps;
727
728    @GuardedBy("mPackages")
729    final Settings mSettings;
730
731    /**
732     * Set of package names that are currently "frozen", which means active
733     * surgery is being done on the code/data for that package. The platform
734     * will refuse to launch frozen packages to avoid race conditions.
735     *
736     * @see PackageFreezer
737     */
738    @GuardedBy("mPackages")
739    final ArraySet<String> mFrozenPackages = new ArraySet<>();
740
741    final ProtectedPackages mProtectedPackages;
742
743    @GuardedBy("mLoadedVolumes")
744    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
745
746    boolean mFirstBoot;
747
748    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
749
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    private final InstantAppRegistry mInstantAppRegistry;
754
755    @GuardedBy("mPackages")
756    int mChangedPackagesSequenceNumber;
757    /**
758     * List of changed [installed, removed or updated] packages.
759     * mapping from user id -> sequence number -> package name
760     */
761    @GuardedBy("mPackages")
762    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
763    /**
764     * The sequence number of the last change to a package.
765     * mapping from user id -> package name -> sequence number
766     */
767    @GuardedBy("mPackages")
768    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
769
770    @GuardedBy("mPackages")
771    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
801                String targetPackageName, String targetPath) {
802            if ("android".equals(targetPackageName)) {
803                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
804                // native AssetManager.
805                return null;
806            }
807            List<PackageParser.Package> overlayPackages =
808                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
809            if (overlayPackages == null || overlayPackages.isEmpty()) {
810                return null;
811            }
812            List<String> overlayPathList = null;
813            for (PackageParser.Package overlayPackage : overlayPackages) {
814                if (targetPath == null) {
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                    continue;
820                }
821
822                try {
823                    // Creates idmaps for system to parse correctly the Android manifest of the
824                    // target package.
825                    //
826                    // OverlayManagerService will update each of them with a correct gid from its
827                    // target package app id.
828                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
829                            UserHandle.getSharedAppGid(
830                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
831                    if (overlayPathList == null) {
832                        overlayPathList = new ArrayList<String>();
833                    }
834                    overlayPathList.add(overlayPackage.baseCodePath);
835                } catch (InstallerException e) {
836                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
837                            overlayPackage.baseCodePath);
838                }
839            }
840            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
841        }
842
843        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
844            synchronized (mPackages) {
845                return getStaticOverlayPathsLocked(
846                        mPackages.values(), targetPackageName, targetPath);
847            }
848        }
849
850        @Override public final String[] getOverlayApks(String targetPackageName) {
851            return getStaticOverlayPaths(targetPackageName, null);
852        }
853
854        @Override public final String[] getOverlayPaths(String targetPackageName,
855                String targetPath) {
856            return getStaticOverlayPaths(targetPackageName, targetPath);
857        }
858    }
859
860    class ParallelPackageParserCallback extends PackageParserCallback {
861        List<PackageParser.Package> mOverlayPackages = null;
862
863        void findStaticOverlayPackages() {
864            synchronized (mPackages) {
865                for (PackageParser.Package p : mPackages.values()) {
866                    if (p.mOverlayIsStatic) {
867                        if (mOverlayPackages == null) {
868                            mOverlayPackages = new ArrayList<PackageParser.Package>();
869                        }
870                        mOverlayPackages.add(p);
871                    }
872                }
873            }
874        }
875
876        @Override
877        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
878            // We can trust mOverlayPackages without holding mPackages because package uninstall
879            // can't happen while running parallel parsing.
880            // Moreover holding mPackages on each parsing thread causes dead-lock.
881            return mOverlayPackages == null ? null :
882                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
883        }
884    }
885
886    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
887    final ParallelPackageParserCallback mParallelPackageParserCallback =
888            new ParallelPackageParserCallback();
889
890    public static final class SharedLibraryEntry {
891        public final @Nullable String path;
892        public final @Nullable String apk;
893        public final @NonNull SharedLibraryInfo info;
894
895        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
896                String declaringPackageName, long declaringPackageVersionCode) {
897            path = _path;
898            apk = _apk;
899            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
900                    declaringPackageName, declaringPackageVersionCode), null);
901        }
902    }
903
904    // Currently known shared libraries.
905    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
906    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
907            new ArrayMap<>();
908
909    // All available activities, for your resolving pleasure.
910    final ActivityIntentResolver mActivities =
911            new ActivityIntentResolver();
912
913    // All available receivers, for your resolving pleasure.
914    final ActivityIntentResolver mReceivers =
915            new ActivityIntentResolver();
916
917    // All available services, for your resolving pleasure.
918    final ServiceIntentResolver mServices = new ServiceIntentResolver();
919
920    // All available providers, for your resolving pleasure.
921    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
922
923    // Mapping from provider base names (first directory in content URI codePath)
924    // to the provider information.
925    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
926            new ArrayMap<String, PackageParser.Provider>();
927
928    // Mapping from instrumentation class names to info about them.
929    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
930            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
931
932    // Packages whose data we have transfered into another package, thus
933    // should no longer exist.
934    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
935
936    // Broadcast actions that are only available to the system.
937    @GuardedBy("mProtectedBroadcasts")
938    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
939
940    /** List of packages waiting for verification. */
941    final SparseArray<PackageVerificationState> mPendingVerification
942            = new SparseArray<PackageVerificationState>();
943
944    final PackageInstallerService mInstallerService;
945
946    final ArtManagerService mArtManagerService;
947
948    private final PackageDexOptimizer mPackageDexOptimizer;
949    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
950    // is used by other apps).
951    private final DexManager mDexManager;
952
953    private AtomicInteger mNextMoveId = new AtomicInteger();
954    private final MoveCallbacks mMoveCallbacks;
955
956    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
957
958    // Cache of users who need badging.
959    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
960
961    /** Token for keys in mPendingVerification. */
962    private int mPendingVerificationToken = 0;
963
964    volatile boolean mSystemReady;
965    volatile boolean mSafeMode;
966    volatile boolean mHasSystemUidErrors;
967    private volatile boolean mEphemeralAppsDisabled;
968
969    ApplicationInfo mAndroidApplication;
970    final ActivityInfo mResolveActivity = new ActivityInfo();
971    final ResolveInfo mResolveInfo = new ResolveInfo();
972    ComponentName mResolveComponentName;
973    PackageParser.Package mPlatformPackage;
974    ComponentName mCustomResolverComponentName;
975
976    boolean mResolverReplaced = false;
977
978    private final @Nullable ComponentName mIntentFilterVerifierComponent;
979    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
980
981    private int mIntentFilterVerificationToken = 0;
982
983    /** The service connection to the ephemeral resolver */
984    final InstantAppResolverConnection mInstantAppResolverConnection;
985    /** Component used to show resolver settings for Instant Apps */
986    final ComponentName mInstantAppResolverSettingsComponent;
987
988    /** Activity used to install instant applications */
989    ActivityInfo mInstantAppInstallerActivity;
990    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
991
992    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
993            = new SparseArray<IntentFilterVerificationState>();
994
995    // TODO remove this and go through mPermissonManager directly
996    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
997    private final PermissionManagerInternal mPermissionManager;
998
999    // List of packages names to keep cached, even if they are uninstalled for all users
1000    private List<String> mKeepUninstalledPackages;
1001
1002    private UserManagerInternal mUserManagerInternal;
1003    private ActivityManagerInternal mActivityManagerInternal;
1004
1005    private DeviceIdleController.LocalService mDeviceIdleController;
1006
1007    private File mCacheDir;
1008
1009    private Future<?> mPrepareAppDataFuture;
1010
1011    private static class IFVerificationParams {
1012        PackageParser.Package pkg;
1013        boolean replacing;
1014        int userId;
1015        int verifierUid;
1016
1017        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1018                int _userId, int _verifierUid) {
1019            pkg = _pkg;
1020            replacing = _replacing;
1021            userId = _userId;
1022            replacing = _replacing;
1023            verifierUid = _verifierUid;
1024        }
1025    }
1026
1027    private interface IntentFilterVerifier<T extends IntentFilter> {
1028        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1029                                               T filter, String packageName);
1030        void startVerifications(int userId);
1031        void receiveVerificationResponse(int verificationId);
1032    }
1033
1034    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1035        private Context mContext;
1036        private ComponentName mIntentFilterVerifierComponent;
1037        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1038
1039        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1040            mContext = context;
1041            mIntentFilterVerifierComponent = verifierComponent;
1042        }
1043
1044        private String getDefaultScheme() {
1045            return IntentFilter.SCHEME_HTTPS;
1046        }
1047
1048        @Override
1049        public void startVerifications(int userId) {
1050            // Launch verifications requests
1051            int count = mCurrentIntentFilterVerifications.size();
1052            for (int n=0; n<count; n++) {
1053                int verificationId = mCurrentIntentFilterVerifications.get(n);
1054                final IntentFilterVerificationState ivs =
1055                        mIntentFilterVerificationStates.get(verificationId);
1056
1057                String packageName = ivs.getPackageName();
1058
1059                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1060                final int filterCount = filters.size();
1061                ArraySet<String> domainsSet = new ArraySet<>();
1062                for (int m=0; m<filterCount; m++) {
1063                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1064                    domainsSet.addAll(filter.getHostsList());
1065                }
1066                synchronized (mPackages) {
1067                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1068                            packageName, domainsSet) != null) {
1069                        scheduleWriteSettingsLocked();
1070                    }
1071                }
1072                sendVerificationRequest(verificationId, ivs);
1073            }
1074            mCurrentIntentFilterVerifications.clear();
1075        }
1076
1077        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1078            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1081                    verificationId);
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1084                    getDefaultScheme());
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1087                    ivs.getHostsString());
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1090                    ivs.getPackageName());
1091            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1092            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1093
1094            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1095            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1096                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1097                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1098
1099            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1100            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1101                    "Sending IntentFilter verification broadcast");
1102        }
1103
1104        public void receiveVerificationResponse(int verificationId) {
1105            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1106
1107            final boolean verified = ivs.isVerified();
1108
1109            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1110            final int count = filters.size();
1111            if (DEBUG_DOMAIN_VERIFICATION) {
1112                Slog.i(TAG, "Received verification response " + verificationId
1113                        + " for " + count + " filters, verified=" + verified);
1114            }
1115            for (int n=0; n<count; n++) {
1116                PackageParser.ActivityIntentInfo filter = filters.get(n);
1117                filter.setVerified(verified);
1118
1119                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1120                        + " verified with result:" + verified + " and hosts:"
1121                        + ivs.getHostsString());
1122            }
1123
1124            mIntentFilterVerificationStates.remove(verificationId);
1125
1126            final String packageName = ivs.getPackageName();
1127            IntentFilterVerificationInfo ivi = null;
1128
1129            synchronized (mPackages) {
1130                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1131            }
1132            if (ivi == null) {
1133                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1134                        + verificationId + " packageName:" + packageName);
1135                return;
1136            }
1137            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1138                    "Updating IntentFilterVerificationInfo for package " + packageName
1139                            +" verificationId:" + verificationId);
1140
1141            synchronized (mPackages) {
1142                if (verified) {
1143                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1144                } else {
1145                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1146                }
1147                scheduleWriteSettingsLocked();
1148
1149                final int userId = ivs.getUserId();
1150                if (userId != UserHandle.USER_ALL) {
1151                    final int userStatus =
1152                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1153
1154                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1155                    boolean needUpdate = false;
1156
1157                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1158                    // already been set by the User thru the Disambiguation dialog
1159                    switch (userStatus) {
1160                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1161                            if (verified) {
1162                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1163                            } else {
1164                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1165                            }
1166                            needUpdate = true;
1167                            break;
1168
1169                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1170                            if (verified) {
1171                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1172                                needUpdate = true;
1173                            }
1174                            break;
1175
1176                        default:
1177                            // Nothing to do
1178                    }
1179
1180                    if (needUpdate) {
1181                        mSettings.updateIntentFilterVerificationStatusLPw(
1182                                packageName, updatedStatus, userId);
1183                        scheduleWritePackageRestrictionsLocked(userId);
1184                    }
1185                }
1186            }
1187        }
1188
1189        @Override
1190        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1191                    ActivityIntentInfo filter, String packageName) {
1192            if (!hasValidDomains(filter)) {
1193                return false;
1194            }
1195            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1196            if (ivs == null) {
1197                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1198                        packageName);
1199            }
1200            if (DEBUG_DOMAIN_VERIFICATION) {
1201                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1202            }
1203            ivs.addFilter(filter);
1204            return true;
1205        }
1206
1207        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1208                int userId, int verificationId, String packageName) {
1209            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1210                    verifierUid, userId, packageName);
1211            ivs.setPendingState();
1212            synchronized (mPackages) {
1213                mIntentFilterVerificationStates.append(verificationId, ivs);
1214                mCurrentIntentFilterVerifications.add(verificationId);
1215            }
1216            return ivs;
1217        }
1218    }
1219
1220    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1221        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1222                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1223                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1224    }
1225
1226    // Set of pending broadcasts for aggregating enable/disable of components.
1227    static class PendingPackageBroadcasts {
1228        // for each user id, a map of <package name -> components within that package>
1229        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1230
1231        public PendingPackageBroadcasts() {
1232            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1233        }
1234
1235        public ArrayList<String> get(int userId, String packageName) {
1236            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1237            return packages.get(packageName);
1238        }
1239
1240        public void put(int userId, String packageName, ArrayList<String> components) {
1241            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1242            packages.put(packageName, components);
1243        }
1244
1245        public void remove(int userId, String packageName) {
1246            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1247            if (packages != null) {
1248                packages.remove(packageName);
1249            }
1250        }
1251
1252        public void remove(int userId) {
1253            mUidMap.remove(userId);
1254        }
1255
1256        public int userIdCount() {
1257            return mUidMap.size();
1258        }
1259
1260        public int userIdAt(int n) {
1261            return mUidMap.keyAt(n);
1262        }
1263
1264        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1265            return mUidMap.get(userId);
1266        }
1267
1268        public int size() {
1269            // total number of pending broadcast entries across all userIds
1270            int num = 0;
1271            for (int i = 0; i< mUidMap.size(); i++) {
1272                num += mUidMap.valueAt(i).size();
1273            }
1274            return num;
1275        }
1276
1277        public void clear() {
1278            mUidMap.clear();
1279        }
1280
1281        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1282            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1283            if (map == null) {
1284                map = new ArrayMap<String, ArrayList<String>>();
1285                mUidMap.put(userId, map);
1286            }
1287            return map;
1288        }
1289    }
1290    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1291
1292    // Service Connection to remote media container service to copy
1293    // package uri's from external media onto secure containers
1294    // or internal storage.
1295    private IMediaContainerService mContainerService = null;
1296
1297    static final int SEND_PENDING_BROADCAST = 1;
1298    static final int MCS_BOUND = 3;
1299    static final int END_COPY = 4;
1300    static final int INIT_COPY = 5;
1301    static final int MCS_UNBIND = 6;
1302    static final int START_CLEANING_PACKAGE = 7;
1303    static final int FIND_INSTALL_LOC = 8;
1304    static final int POST_INSTALL = 9;
1305    static final int MCS_RECONNECT = 10;
1306    static final int MCS_GIVE_UP = 11;
1307    static final int WRITE_SETTINGS = 13;
1308    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1309    static final int PACKAGE_VERIFIED = 15;
1310    static final int CHECK_PENDING_VERIFICATION = 16;
1311    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1312    static final int INTENT_FILTER_VERIFIED = 18;
1313    static final int WRITE_PACKAGE_LIST = 19;
1314    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1315
1316    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1317
1318    // Delay time in millisecs
1319    static final int BROADCAST_DELAY = 10 * 1000;
1320
1321    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1322            2 * 60 * 60 * 1000L; /* two hours */
1323
1324    static UserManagerService sUserManager;
1325
1326    // Stores a list of users whose package restrictions file needs to be updated
1327    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1328
1329    final private DefaultContainerConnection mDefContainerConn =
1330            new DefaultContainerConnection();
1331    class DefaultContainerConnection implements ServiceConnection {
1332        public void onServiceConnected(ComponentName name, IBinder service) {
1333            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1334            final IMediaContainerService imcs = IMediaContainerService.Stub
1335                    .asInterface(Binder.allowBlocking(service));
1336            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1337        }
1338
1339        public void onServiceDisconnected(ComponentName name) {
1340            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1341        }
1342    }
1343
1344    // Recordkeeping of restore-after-install operations that are currently in flight
1345    // between the Package Manager and the Backup Manager
1346    static class PostInstallData {
1347        public InstallArgs args;
1348        public PackageInstalledInfo res;
1349
1350        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1351            args = _a;
1352            res = _r;
1353        }
1354    }
1355
1356    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1357    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1358
1359    // XML tags for backup/restore of various bits of state
1360    private static final String TAG_PREFERRED_BACKUP = "pa";
1361    private static final String TAG_DEFAULT_APPS = "da";
1362    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1363
1364    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1365    private static final String TAG_ALL_GRANTS = "rt-grants";
1366    private static final String TAG_GRANT = "grant";
1367    private static final String ATTR_PACKAGE_NAME = "pkg";
1368
1369    private static final String TAG_PERMISSION = "perm";
1370    private static final String ATTR_PERMISSION_NAME = "name";
1371    private static final String ATTR_IS_GRANTED = "g";
1372    private static final String ATTR_USER_SET = "set";
1373    private static final String ATTR_USER_FIXED = "fixed";
1374    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1375
1376    // System/policy permission grants are not backed up
1377    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1378            FLAG_PERMISSION_POLICY_FIXED
1379            | FLAG_PERMISSION_SYSTEM_FIXED
1380            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1381
1382    // And we back up these user-adjusted states
1383    private static final int USER_RUNTIME_GRANT_MASK =
1384            FLAG_PERMISSION_USER_SET
1385            | FLAG_PERMISSION_USER_FIXED
1386            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1387
1388    final @Nullable String mRequiredVerifierPackage;
1389    final @NonNull String mRequiredInstallerPackage;
1390    final @NonNull String mRequiredUninstallerPackage;
1391    final @Nullable String mSetupWizardPackage;
1392    final @Nullable String mStorageManagerPackage;
1393    final @NonNull String mServicesSystemSharedLibraryPackageName;
1394    final @NonNull String mSharedSystemSharedLibraryPackageName;
1395
1396    private final PackageUsage mPackageUsage = new PackageUsage();
1397    private final CompilerStats mCompilerStats = new CompilerStats();
1398
1399    class PackageHandler extends Handler {
1400        private boolean mBound = false;
1401        final ArrayList<HandlerParams> mPendingInstalls =
1402            new ArrayList<HandlerParams>();
1403
1404        private boolean connectToService() {
1405            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1406                    " DefaultContainerService");
1407            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1410                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1411                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                mBound = true;
1413                return true;
1414            }
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416            return false;
1417        }
1418
1419        private void disconnectService() {
1420            mContainerService = null;
1421            mBound = false;
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            mContext.unbindService(mDefContainerConn);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425        }
1426
1427        PackageHandler(Looper looper) {
1428            super(looper);
1429        }
1430
1431        public void handleMessage(Message msg) {
1432            try {
1433                doHandleMessage(msg);
1434            } finally {
1435                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436            }
1437        }
1438
1439        void doHandleMessage(Message msg) {
1440            switch (msg.what) {
1441                case INIT_COPY: {
1442                    HandlerParams params = (HandlerParams) msg.obj;
1443                    int idx = mPendingInstalls.size();
1444                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1445                    // If a bind was already initiated we dont really
1446                    // need to do anything. The pending install
1447                    // will be processed later on.
1448                    if (!mBound) {
1449                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1450                                System.identityHashCode(mHandler));
1451                        // If this is the only one pending we might
1452                        // have to bind to the service again.
1453                        if (!connectToService()) {
1454                            Slog.e(TAG, "Failed to bind to media container service");
1455                            params.serviceError();
1456                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                    System.identityHashCode(mHandler));
1458                            if (params.traceMethod != null) {
1459                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1460                                        params.traceCookie);
1461                            }
1462                            return;
1463                        } else {
1464                            // Once we bind to the service, the first
1465                            // pending request will be processed.
1466                            mPendingInstalls.add(idx, params);
1467                        }
1468                    } else {
1469                        mPendingInstalls.add(idx, params);
1470                        // Already bound to the service. Just make
1471                        // sure we trigger off processing the first request.
1472                        if (idx == 0) {
1473                            mHandler.sendEmptyMessage(MCS_BOUND);
1474                        }
1475                    }
1476                    break;
1477                }
1478                case MCS_BOUND: {
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1480                    if (msg.obj != null) {
1481                        mContainerService = (IMediaContainerService) msg.obj;
1482                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                System.identityHashCode(mHandler));
1484                    }
1485                    if (mContainerService == null) {
1486                        if (!mBound) {
1487                            // Something seriously wrong since we are not bound and we are not
1488                            // waiting for connection. Bail out.
1489                            Slog.e(TAG, "Cannot bind to media container service");
1490                            for (HandlerParams params : mPendingInstalls) {
1491                                // Indicate service bind error
1492                                params.serviceError();
1493                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1494                                        System.identityHashCode(params));
1495                                if (params.traceMethod != null) {
1496                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1497                                            params.traceMethod, params.traceCookie);
1498                                }
1499                                return;
1500                            }
1501                            mPendingInstalls.clear();
1502                        } else {
1503                            Slog.w(TAG, "Waiting to connect to media container service");
1504                        }
1505                    } else if (mPendingInstalls.size() > 0) {
1506                        HandlerParams params = mPendingInstalls.get(0);
1507                        if (params != null) {
1508                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                    System.identityHashCode(params));
1510                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1511                            if (params.startCopy()) {
1512                                // We are done...  look for more work or to
1513                                // go idle.
1514                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                        "Checking for more work or unbind...");
1516                                // Delete pending install
1517                                if (mPendingInstalls.size() > 0) {
1518                                    mPendingInstalls.remove(0);
1519                                }
1520                                if (mPendingInstalls.size() == 0) {
1521                                    if (mBound) {
1522                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1523                                                "Posting delayed MCS_UNBIND");
1524                                        removeMessages(MCS_UNBIND);
1525                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1526                                        // Unbind after a little delay, to avoid
1527                                        // continual thrashing.
1528                                        sendMessageDelayed(ubmsg, 10000);
1529                                    }
1530                                } else {
1531                                    // There are more pending requests in queue.
1532                                    // Just post MCS_BOUND message to trigger processing
1533                                    // of next pending install.
1534                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1535                                            "Posting MCS_BOUND for next work");
1536                                    mHandler.sendEmptyMessage(MCS_BOUND);
1537                                }
1538                            }
1539                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1540                        }
1541                    } else {
1542                        // Should never happen ideally.
1543                        Slog.w(TAG, "Empty queue");
1544                    }
1545                    break;
1546                }
1547                case MCS_RECONNECT: {
1548                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1549                    if (mPendingInstalls.size() > 0) {
1550                        if (mBound) {
1551                            disconnectService();
1552                        }
1553                        if (!connectToService()) {
1554                            Slog.e(TAG, "Failed to bind to media container service");
1555                            for (HandlerParams params : mPendingInstalls) {
1556                                // Indicate service bind error
1557                                params.serviceError();
1558                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1559                                        System.identityHashCode(params));
1560                            }
1561                            mPendingInstalls.clear();
1562                        }
1563                    }
1564                    break;
1565                }
1566                case MCS_UNBIND: {
1567                    // If there is no actual work left, then time to unbind.
1568                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1569
1570                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1571                        if (mBound) {
1572                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1573
1574                            disconnectService();
1575                        }
1576                    } else if (mPendingInstalls.size() > 0) {
1577                        // There are more pending requests in queue.
1578                        // Just post MCS_BOUND message to trigger processing
1579                        // of next pending install.
1580                        mHandler.sendEmptyMessage(MCS_BOUND);
1581                    }
1582
1583                    break;
1584                }
1585                case MCS_GIVE_UP: {
1586                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1587                    HandlerParams params = mPendingInstalls.remove(0);
1588                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1589                            System.identityHashCode(params));
1590                    break;
1591                }
1592                case SEND_PENDING_BROADCAST: {
1593                    String packages[];
1594                    ArrayList<String> components[];
1595                    int size = 0;
1596                    int uids[];
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        if (mPendingBroadcasts == null) {
1600                            return;
1601                        }
1602                        size = mPendingBroadcasts.size();
1603                        if (size <= 0) {
1604                            // Nothing to be done. Just return
1605                            return;
1606                        }
1607                        packages = new String[size];
1608                        components = new ArrayList[size];
1609                        uids = new int[size];
1610                        int i = 0;  // filling out the above arrays
1611
1612                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1613                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1614                            Iterator<Map.Entry<String, ArrayList<String>>> it
1615                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1616                                            .entrySet().iterator();
1617                            while (it.hasNext() && i < size) {
1618                                Map.Entry<String, ArrayList<String>> ent = it.next();
1619                                packages[i] = ent.getKey();
1620                                components[i] = ent.getValue();
1621                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1622                                uids[i] = (ps != null)
1623                                        ? UserHandle.getUid(packageUserId, ps.appId)
1624                                        : -1;
1625                                i++;
1626                            }
1627                        }
1628                        size = i;
1629                        mPendingBroadcasts.clear();
1630                    }
1631                    // Send broadcasts
1632                    for (int i = 0; i < size; i++) {
1633                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1634                    }
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1636                    break;
1637                }
1638                case START_CLEANING_PACKAGE: {
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1640                    final String packageName = (String)msg.obj;
1641                    final int userId = msg.arg1;
1642                    final boolean andCode = msg.arg2 != 0;
1643                    synchronized (mPackages) {
1644                        if (userId == UserHandle.USER_ALL) {
1645                            int[] users = sUserManager.getUserIds();
1646                            for (int user : users) {
1647                                mSettings.addPackageToCleanLPw(
1648                                        new PackageCleanItem(user, packageName, andCode));
1649                            }
1650                        } else {
1651                            mSettings.addPackageToCleanLPw(
1652                                    new PackageCleanItem(userId, packageName, andCode));
1653                        }
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                    startCleaningPackages();
1657                } break;
1658                case POST_INSTALL: {
1659                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1660
1661                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1662                    final boolean didRestore = (msg.arg2 != 0);
1663                    mRunningInstalls.delete(msg.arg1);
1664
1665                    if (data != null) {
1666                        InstallArgs args = data.args;
1667                        PackageInstalledInfo parentRes = data.res;
1668
1669                        final boolean grantPermissions = (args.installFlags
1670                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1671                        final boolean killApp = (args.installFlags
1672                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1673                        final boolean virtualPreload = ((args.installFlags
1674                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1675                        final String[] grantedPermissions = args.installGrantPermissions;
1676
1677                        // Handle the parent package
1678                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1679                                virtualPreload, grantedPermissions, didRestore,
1680                                args.installerPackageName, args.observer);
1681
1682                        // Handle the child packages
1683                        final int childCount = (parentRes.addedChildPackages != null)
1684                                ? parentRes.addedChildPackages.size() : 0;
1685                        for (int i = 0; i < childCount; i++) {
1686                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1687                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1688                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1689                                    args.installerPackageName, args.observer);
1690                        }
1691
1692                        // Log tracing if needed
1693                        if (args.traceMethod != null) {
1694                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1695                                    args.traceCookie);
1696                        }
1697                    } else {
1698                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1699                    }
1700
1701                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1702                } break;
1703                case WRITE_SETTINGS: {
1704                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1705                    synchronized (mPackages) {
1706                        removeMessages(WRITE_SETTINGS);
1707                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1708                        mSettings.writeLPr();
1709                        mDirtyUsers.clear();
1710                    }
1711                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1712                } break;
1713                case WRITE_PACKAGE_RESTRICTIONS: {
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1715                    synchronized (mPackages) {
1716                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1717                        for (int userId : mDirtyUsers) {
1718                            mSettings.writePackageRestrictionsLPr(userId);
1719                        }
1720                        mDirtyUsers.clear();
1721                    }
1722                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1723                } break;
1724                case WRITE_PACKAGE_LIST: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_PACKAGE_LIST);
1728                        mSettings.writePackageListLPr(msg.arg1);
1729                    }
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1731                } break;
1732                case CHECK_PENDING_VERIFICATION: {
1733                    final int verificationId = msg.arg1;
1734                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1735
1736                    if ((state != null) && !state.timeoutExtended()) {
1737                        final InstallArgs args = state.getInstallArgs();
1738                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1739
1740                        Slog.i(TAG, "Verification timed out for " + originUri);
1741                        mPendingVerification.remove(verificationId);
1742
1743                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1744
1745                        final UserHandle user = args.getUser();
1746                        if (getDefaultVerificationResponse(user)
1747                                == PackageManager.VERIFICATION_ALLOW) {
1748                            Slog.i(TAG, "Continuing with installation of " + originUri);
1749                            state.setVerifierResponse(Binder.getCallingUid(),
1750                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1751                            broadcastPackageVerified(verificationId, originUri,
1752                                    PackageManager.VERIFICATION_ALLOW, user);
1753                            try {
1754                                ret = args.copyApk(mContainerService, true);
1755                            } catch (RemoteException e) {
1756                                Slog.e(TAG, "Could not contact the ContainerService");
1757                            }
1758                        } else {
1759                            broadcastPackageVerified(verificationId, originUri,
1760                                    PackageManager.VERIFICATION_REJECT, user);
1761                        }
1762
1763                        Trace.asyncTraceEnd(
1764                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1765
1766                        processPendingInstall(args, ret);
1767                        mHandler.sendEmptyMessage(MCS_UNBIND);
1768                    }
1769                    break;
1770                }
1771                case PACKAGE_VERIFIED: {
1772                    final int verificationId = msg.arg1;
1773
1774                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1775                    if (state == null) {
1776                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1777                        break;
1778                    }
1779
1780                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1781
1782                    state.setVerifierResponse(response.callerUid, response.code);
1783
1784                    if (state.isVerificationComplete()) {
1785                        mPendingVerification.remove(verificationId);
1786
1787                        final InstallArgs args = state.getInstallArgs();
1788                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1789
1790                        int ret;
1791                        if (state.isInstallAllowed()) {
1792                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1793                            broadcastPackageVerified(verificationId, originUri,
1794                                    response.code, state.getInstallArgs().getUser());
1795                            try {
1796                                ret = args.copyApk(mContainerService, true);
1797                            } catch (RemoteException e) {
1798                                Slog.e(TAG, "Could not contact the ContainerService");
1799                            }
1800                        } else {
1801                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1802                        }
1803
1804                        Trace.asyncTraceEnd(
1805                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1806
1807                        processPendingInstall(args, ret);
1808                        mHandler.sendEmptyMessage(MCS_UNBIND);
1809                    }
1810
1811                    break;
1812                }
1813                case START_INTENT_FILTER_VERIFICATIONS: {
1814                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1815                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1816                            params.replacing, params.pkg);
1817                    break;
1818                }
1819                case INTENT_FILTER_VERIFIED: {
1820                    final int verificationId = msg.arg1;
1821
1822                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1823                            verificationId);
1824                    if (state == null) {
1825                        Slog.w(TAG, "Invalid IntentFilter verification token "
1826                                + verificationId + " received");
1827                        break;
1828                    }
1829
1830                    final int userId = state.getUserId();
1831
1832                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1833                            "Processing IntentFilter verification with token:"
1834                            + verificationId + " and userId:" + userId);
1835
1836                    final IntentFilterVerificationResponse response =
1837                            (IntentFilterVerificationResponse) msg.obj;
1838
1839                    state.setVerifierResponse(response.callerUid, response.code);
1840
1841                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1842                            "IntentFilter verification with token:" + verificationId
1843                            + " and userId:" + userId
1844                            + " is settings verifier response with response code:"
1845                            + response.code);
1846
1847                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1848                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1849                                + response.getFailedDomainsString());
1850                    }
1851
1852                    if (state.isVerificationComplete()) {
1853                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1854                    } else {
1855                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1856                                "IntentFilter verification with token:" + verificationId
1857                                + " was not said to be complete");
1858                    }
1859
1860                    break;
1861                }
1862                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1863                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1864                            mInstantAppResolverConnection,
1865                            (InstantAppRequest) msg.obj,
1866                            mInstantAppInstallerActivity,
1867                            mHandler);
1868                }
1869            }
1870        }
1871    }
1872
1873    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1874        @Override
1875        public void onGidsChanged(int appId, int userId) {
1876            mHandler.post(new Runnable() {
1877                @Override
1878                public void run() {
1879                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1880                }
1881            });
1882        }
1883        @Override
1884        public void onPermissionGranted(int uid, int userId) {
1885            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1886
1887            // Not critical; if this is lost, the application has to request again.
1888            synchronized (mPackages) {
1889                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1890            }
1891        }
1892        @Override
1893        public void onInstallPermissionGranted() {
1894            synchronized (mPackages) {
1895                scheduleWriteSettingsLocked();
1896            }
1897        }
1898        @Override
1899        public void onPermissionRevoked(int uid, int userId) {
1900            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1901
1902            synchronized (mPackages) {
1903                // Critical; after this call the application should never have the permission
1904                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1905            }
1906
1907            final int appId = UserHandle.getAppId(uid);
1908            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1909        }
1910        @Override
1911        public void onInstallPermissionRevoked() {
1912            synchronized (mPackages) {
1913                scheduleWriteSettingsLocked();
1914            }
1915        }
1916        @Override
1917        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1918            synchronized (mPackages) {
1919                for (int userId : updatedUserIds) {
1920                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1921                }
1922            }
1923        }
1924        @Override
1925        public void onInstallPermissionUpdated() {
1926            synchronized (mPackages) {
1927                scheduleWriteSettingsLocked();
1928            }
1929        }
1930        @Override
1931        public void onPermissionRemoved() {
1932            synchronized (mPackages) {
1933                mSettings.writeLPr();
1934            }
1935        }
1936    };
1937
1938    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1939            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1940            boolean launchedForRestore, String installerPackage,
1941            IPackageInstallObserver2 installObserver) {
1942        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1943            // Send the removed broadcasts
1944            if (res.removedInfo != null) {
1945                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1946            }
1947
1948            // Now that we successfully installed the package, grant runtime
1949            // permissions if requested before broadcasting the install. Also
1950            // for legacy apps in permission review mode we clear the permission
1951            // review flag which is used to emulate runtime permissions for
1952            // legacy apps.
1953            if (grantPermissions) {
1954                final int callingUid = Binder.getCallingUid();
1955                mPermissionManager.grantRequestedRuntimePermissions(
1956                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1957                        mPermissionCallback);
1958            }
1959
1960            final boolean update = res.removedInfo != null
1961                    && res.removedInfo.removedPackage != null;
1962            final String installerPackageName =
1963                    res.installerPackageName != null
1964                            ? res.installerPackageName
1965                            : res.removedInfo != null
1966                                    ? res.removedInfo.installerPackageName
1967                                    : null;
1968
1969            // If this is the first time we have child packages for a disabled privileged
1970            // app that had no children, we grant requested runtime permissions to the new
1971            // children if the parent on the system image had them already granted.
1972            if (res.pkg.parentPackage != null) {
1973                final int callingUid = Binder.getCallingUid();
1974                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1975                        res.pkg, callingUid, mPermissionCallback);
1976            }
1977
1978            synchronized (mPackages) {
1979                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1980            }
1981
1982            final String packageName = res.pkg.applicationInfo.packageName;
1983
1984            // Determine the set of users who are adding this package for
1985            // the first time vs. those who are seeing an update.
1986            int[] firstUserIds = EMPTY_INT_ARRAY;
1987            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1988            int[] updateUserIds = EMPTY_INT_ARRAY;
1989            int[] instantUserIds = EMPTY_INT_ARRAY;
1990            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1991            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1992            for (int newUser : res.newUsers) {
1993                final boolean isInstantApp = ps.getInstantApp(newUser);
1994                if (allNewUsers) {
1995                    if (isInstantApp) {
1996                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1997                    } else {
1998                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1999                    }
2000                    continue;
2001                }
2002                boolean isNew = true;
2003                for (int origUser : res.origUsers) {
2004                    if (origUser == newUser) {
2005                        isNew = false;
2006                        break;
2007                    }
2008                }
2009                if (isNew) {
2010                    if (isInstantApp) {
2011                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2012                    } else {
2013                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2014                    }
2015                } else {
2016                    if (isInstantApp) {
2017                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2018                    } else {
2019                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2020                    }
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, firstUserIds, firstInstantUserIds);
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*/,
2044                        updateUserIds, instantUserIds);
2045                if (installerPackageName != null) {
2046                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2047                            extras, 0 /*flags*/,
2048                            installerPackageName, null /*finishedReceiver*/,
2049                            updateUserIds, instantUserIds);
2050                }
2051
2052                // Send replaced for users that don't see the package for the first time
2053                if (update) {
2054                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2055                            packageName, extras, 0 /*flags*/,
2056                            null /*targetPackage*/, null /*finishedReceiver*/,
2057                            updateUserIds, instantUserIds);
2058                    if (installerPackageName != null) {
2059                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2060                                extras, 0 /*flags*/,
2061                                installerPackageName, null /*finishedReceiver*/,
2062                                updateUserIds, instantUserIds);
2063                    }
2064                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2065                            null /*package*/, null /*extras*/, 0 /*flags*/,
2066                            packageName /*targetPackage*/,
2067                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2068                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2069                    // First-install and we did a restore, so we're responsible for the
2070                    // first-launch broadcast.
2071                    if (DEBUG_BACKUP) {
2072                        Slog.i(TAG, "Post-restore of " + packageName
2073                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2074                    }
2075                    sendFirstLaunchBroadcast(packageName, installerPackage,
2076                            firstUserIds, firstInstantUserIds);
2077                }
2078
2079                // Send broadcast package appeared if forward locked/external for all users
2080                // treat asec-hosted packages like removable media on upgrade
2081                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2082                    if (DEBUG_INSTALL) {
2083                        Slog.i(TAG, "upgrading pkg " + res.pkg
2084                                + " is ASEC-hosted -> AVAILABLE");
2085                    }
2086                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2087                    ArrayList<String> pkgList = new ArrayList<>(1);
2088                    pkgList.add(packageName);
2089                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2090                }
2091            }
2092
2093            // Work that needs to happen on first install within each user
2094            if (firstUserIds != null && firstUserIds.length > 0) {
2095                synchronized (mPackages) {
2096                    for (int userId : firstUserIds) {
2097                        // If this app is a browser and it's newly-installed for some
2098                        // users, clear any default-browser state in those users. The
2099                        // app's nature doesn't depend on the user, so we can just check
2100                        // its browser nature in any user and generalize.
2101                        if (packageIsBrowser(packageName, userId)) {
2102                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2103                        }
2104
2105                        // We may also need to apply pending (restored) runtime
2106                        // permission grants within these users.
2107                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2108                    }
2109                }
2110            }
2111
2112            if (allNewUsers && !update) {
2113                notifyPackageAdded(packageName);
2114            }
2115
2116            // Log current value of "unknown sources" setting
2117            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2118                    getUnknownSourcesSettings());
2119
2120            // Remove the replaced package's older resources safely now
2121            // We delete after a gc for applications  on sdcard.
2122            if (res.removedInfo != null && res.removedInfo.args != null) {
2123                Runtime.getRuntime().gc();
2124                synchronized (mInstallLock) {
2125                    res.removedInfo.args.doPostDeleteLI(true);
2126                }
2127            } else {
2128                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2129                // and not block here.
2130                VMRuntime.getRuntime().requestConcurrentGC();
2131            }
2132
2133            // Notify DexManager that the package was installed for new users.
2134            // The updated users should already be indexed and the package code paths
2135            // should not change.
2136            // Don't notify the manager for ephemeral apps as they are not expected to
2137            // survive long enough to benefit of background optimizations.
2138            for (int userId : firstUserIds) {
2139                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2140                // There's a race currently where some install events may interleave with an uninstall.
2141                // This can lead to package info being null (b/36642664).
2142                if (info != null) {
2143                    mDexManager.notifyPackageInstalled(info, userId);
2144                }
2145            }
2146        }
2147
2148        // If someone is watching installs - notify them
2149        if (installObserver != null) {
2150            try {
2151                Bundle extras = extrasForInstallResult(res);
2152                installObserver.onPackageInstalled(res.name, res.returnCode,
2153                        res.returnMsg, extras);
2154            } catch (RemoteException e) {
2155                Slog.i(TAG, "Observer no longer exists.");
2156            }
2157        }
2158    }
2159
2160    private StorageEventListener mStorageListener = new StorageEventListener() {
2161        @Override
2162        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2163            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2164                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2165                    final String volumeUuid = vol.getFsUuid();
2166
2167                    // Clean up any users or apps that were removed or recreated
2168                    // while this volume was missing
2169                    sUserManager.reconcileUsers(volumeUuid);
2170                    reconcileApps(volumeUuid);
2171
2172                    // Clean up any install sessions that expired or were
2173                    // cancelled while this volume was missing
2174                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2175
2176                    loadPrivatePackages(vol);
2177
2178                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2179                    unloadPrivatePackages(vol);
2180                }
2181            }
2182        }
2183
2184        @Override
2185        public void onVolumeForgotten(String fsUuid) {
2186            if (TextUtils.isEmpty(fsUuid)) {
2187                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2188                return;
2189            }
2190
2191            // Remove any apps installed on the forgotten volume
2192            synchronized (mPackages) {
2193                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2194                for (PackageSetting ps : packages) {
2195                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2196                    deletePackageVersioned(new VersionedPackage(ps.name,
2197                            PackageManager.VERSION_CODE_HIGHEST),
2198                            new LegacyPackageDeleteObserver(null).getBinder(),
2199                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2200                    // Try very hard to release any references to this package
2201                    // so we don't risk the system server being killed due to
2202                    // open FDs
2203                    AttributeCache.instance().removePackage(ps.name);
2204                }
2205
2206                mSettings.onVolumeForgotten(fsUuid);
2207                mSettings.writeLPr();
2208            }
2209        }
2210    };
2211
2212    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2213        Bundle extras = null;
2214        switch (res.returnCode) {
2215            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2216                extras = new Bundle();
2217                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2218                        res.origPermission);
2219                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2220                        res.origPackage);
2221                break;
2222            }
2223            case PackageManager.INSTALL_SUCCEEDED: {
2224                extras = new Bundle();
2225                extras.putBoolean(Intent.EXTRA_REPLACING,
2226                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2227                break;
2228            }
2229        }
2230        return extras;
2231    }
2232
2233    void scheduleWriteSettingsLocked() {
2234        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2235            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2236        }
2237    }
2238
2239    void scheduleWritePackageListLocked(int userId) {
2240        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2241            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2242            msg.arg1 = userId;
2243            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2244        }
2245    }
2246
2247    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2248        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2249        scheduleWritePackageRestrictionsLocked(userId);
2250    }
2251
2252    void scheduleWritePackageRestrictionsLocked(int userId) {
2253        final int[] userIds = (userId == UserHandle.USER_ALL)
2254                ? sUserManager.getUserIds() : new int[]{userId};
2255        for (int nextUserId : userIds) {
2256            if (!sUserManager.exists(nextUserId)) return;
2257            mDirtyUsers.add(nextUserId);
2258            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2259                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2260            }
2261        }
2262    }
2263
2264    public static PackageManagerService main(Context context, Installer installer,
2265            boolean factoryTest, boolean onlyCore) {
2266        // Self-check for initial settings.
2267        PackageManagerServiceCompilerMapping.checkProperties();
2268
2269        PackageManagerService m = new PackageManagerService(context, installer,
2270                factoryTest, onlyCore);
2271        m.enableSystemUserPackages();
2272        ServiceManager.addService("package", m);
2273        final PackageManagerNative pmn = m.new PackageManagerNative();
2274        ServiceManager.addService("package_native", pmn);
2275        return m;
2276    }
2277
2278    private void enableSystemUserPackages() {
2279        if (!UserManager.isSplitSystemUser()) {
2280            return;
2281        }
2282        // For system user, enable apps based on the following conditions:
2283        // - app is whitelisted or belong to one of these groups:
2284        //   -- system app which has no launcher icons
2285        //   -- system app which has INTERACT_ACROSS_USERS permission
2286        //   -- system IME app
2287        // - app is not in the blacklist
2288        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2289        Set<String> enableApps = new ArraySet<>();
2290        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2291                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2292                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2293        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2294        enableApps.addAll(wlApps);
2295        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2296                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2297        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2298        enableApps.removeAll(blApps);
2299        Log.i(TAG, "Applications installed for system user: " + enableApps);
2300        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2301                UserHandle.SYSTEM);
2302        final int allAppsSize = allAps.size();
2303        synchronized (mPackages) {
2304            for (int i = 0; i < allAppsSize; i++) {
2305                String pName = allAps.get(i);
2306                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2307                // Should not happen, but we shouldn't be failing if it does
2308                if (pkgSetting == null) {
2309                    continue;
2310                }
2311                boolean install = enableApps.contains(pName);
2312                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2313                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2314                            + " for system user");
2315                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2316                }
2317            }
2318            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2319        }
2320    }
2321
2322    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2323        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2324                Context.DISPLAY_SERVICE);
2325        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2326    }
2327
2328    /**
2329     * Requests that files preopted on a secondary system partition be copied to the data partition
2330     * if possible.  Note that the actual copying of the files is accomplished by init for security
2331     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2332     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2333     */
2334    private static void requestCopyPreoptedFiles() {
2335        final int WAIT_TIME_MS = 100;
2336        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2337        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2338            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2339            // We will wait for up to 100 seconds.
2340            final long timeStart = SystemClock.uptimeMillis();
2341            final long timeEnd = timeStart + 100 * 1000;
2342            long timeNow = timeStart;
2343            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2344                try {
2345                    Thread.sleep(WAIT_TIME_MS);
2346                } catch (InterruptedException e) {
2347                    // Do nothing
2348                }
2349                timeNow = SystemClock.uptimeMillis();
2350                if (timeNow > timeEnd) {
2351                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2352                    Slog.wtf(TAG, "cppreopt did not finish!");
2353                    break;
2354                }
2355            }
2356
2357            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2358        }
2359    }
2360
2361    public PackageManagerService(Context context, Installer installer,
2362            boolean factoryTest, boolean onlyCore) {
2363        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2365        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2366                SystemClock.uptimeMillis());
2367
2368        if (mSdkVersion <= 0) {
2369            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2370        }
2371
2372        mContext = context;
2373
2374        mFactoryTest = factoryTest;
2375        mOnlyCore = onlyCore;
2376        mMetrics = new DisplayMetrics();
2377        mInstaller = installer;
2378
2379        // Create sub-components that provide services / data. Order here is important.
2380        synchronized (mInstallLock) {
2381        synchronized (mPackages) {
2382            // Expose private service for system components to use.
2383            LocalServices.addService(
2384                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2385            sUserManager = new UserManagerService(context, this,
2386                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2387            mPermissionManager = PermissionManagerService.create(context,
2388                    new DefaultPermissionGrantedCallback() {
2389                        @Override
2390                        public void onDefaultRuntimePermissionsGranted(int userId) {
2391                            synchronized(mPackages) {
2392                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2393                            }
2394                        }
2395                    }, mPackages /*externalLock*/);
2396            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2397            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2398        }
2399        }
2400        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414
2415        String separateProcesses = SystemProperties.get("debug.separate_processes");
2416        if (separateProcesses != null && separateProcesses.length() > 0) {
2417            if ("*".equals(separateProcesses)) {
2418                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2419                mSeparateProcesses = null;
2420                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2421            } else {
2422                mDefParseFlags = 0;
2423                mSeparateProcesses = separateProcesses.split(",");
2424                Slog.w(TAG, "Running with debug.separate_processes: "
2425                        + separateProcesses);
2426            }
2427        } else {
2428            mDefParseFlags = 0;
2429            mSeparateProcesses = null;
2430        }
2431
2432        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2433                "*dexopt*");
2434        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2435                installer, mInstallLock);
2436        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2437                dexManagerListener);
2438        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2439        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2440
2441        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2442                FgThread.get().getLooper());
2443
2444        getDefaultDisplayMetrics(context, mMetrics);
2445
2446        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2447        SystemConfig systemConfig = SystemConfig.getInstance();
2448        mAvailableFeatures = systemConfig.getAvailableFeatures();
2449        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2450
2451        mProtectedPackages = new ProtectedPackages(mContext);
2452
2453        synchronized (mInstallLock) {
2454        // writer
2455        synchronized (mPackages) {
2456            mHandlerThread = new ServiceThread(TAG,
2457                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2458            mHandlerThread.start();
2459            mHandler = new PackageHandler(mHandlerThread.getLooper());
2460            mProcessLoggingHandler = new ProcessLoggingHandler();
2461            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2462            mInstantAppRegistry = new InstantAppRegistry(this);
2463
2464            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2465            final int builtInLibCount = libConfig.size();
2466            for (int i = 0; i < builtInLibCount; i++) {
2467                String name = libConfig.keyAt(i);
2468                String path = libConfig.valueAt(i);
2469                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2470                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2471            }
2472
2473            SELinuxMMAC.readInstallPolicy();
2474
2475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2476            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2477            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2478
2479            // Clean up orphaned packages for which the code path doesn't exist
2480            // and they are an update to a system app - caused by bug/32321269
2481            final int packageSettingCount = mSettings.mPackages.size();
2482            for (int i = packageSettingCount - 1; i >= 0; i--) {
2483                PackageSetting ps = mSettings.mPackages.valueAt(i);
2484                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2485                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2486                    mSettings.mPackages.removeAt(i);
2487                    mSettings.enableSystemPackageLPw(ps.name);
2488                }
2489            }
2490
2491            if (mFirstBoot) {
2492                requestCopyPreoptedFiles();
2493            }
2494
2495            String customResolverActivity = Resources.getSystem().getString(
2496                    R.string.config_customResolverActivity);
2497            if (TextUtils.isEmpty(customResolverActivity)) {
2498                customResolverActivity = null;
2499            } else {
2500                mCustomResolverComponentName = ComponentName.unflattenFromString(
2501                        customResolverActivity);
2502            }
2503
2504            long startTime = SystemClock.uptimeMillis();
2505
2506            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2507                    startTime);
2508
2509            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2510            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2511
2512            if (bootClassPath == null) {
2513                Slog.w(TAG, "No BOOTCLASSPATH found!");
2514            }
2515
2516            if (systemServerClassPath == null) {
2517                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2518            }
2519
2520            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2521
2522            final VersionInfo ver = mSettings.getInternalVersion();
2523            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2524            if (mIsUpgrade) {
2525                logCriticalInfo(Log.INFO,
2526                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2527            }
2528
2529            // when upgrading from pre-M, promote system app permissions from install to runtime
2530            mPromoteSystemApps =
2531                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2532
2533            // When upgrading from pre-N, we need to handle package extraction like first boot,
2534            // as there is no profiling data available.
2535            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2536
2537            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2538
2539            // save off the names of pre-existing system packages prior to scanning; we don't
2540            // want to automatically grant runtime permissions for new system apps
2541            if (mPromoteSystemApps) {
2542                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2543                while (pkgSettingIter.hasNext()) {
2544                    PackageSetting ps = pkgSettingIter.next();
2545                    if (isSystemApp(ps)) {
2546                        mExistingSystemPackages.add(ps.name);
2547                    }
2548                }
2549            }
2550
2551            mCacheDir = preparePackageParserCache(mIsUpgrade);
2552
2553            // Set flag to monitor and not change apk file paths when
2554            // scanning install directories.
2555            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2556
2557            if (mIsUpgrade || mFirstBoot) {
2558                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2559            }
2560
2561            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2562            // For security and version matching reason, only consider
2563            // overlay packages if they reside in the right directory.
2564            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2565                    mDefParseFlags
2566                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2567                    scanFlags
2568                    | SCAN_AS_SYSTEM
2569                    | SCAN_AS_VENDOR,
2570                    0);
2571            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2572                    mDefParseFlags
2573                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2574                    scanFlags
2575                    | SCAN_AS_SYSTEM
2576                    | SCAN_AS_PRODUCT,
2577                    0);
2578
2579            mParallelPackageParserCallback.findStaticOverlayPackages();
2580
2581            // Find base frameworks (resource packages without code).
2582            scanDirTracedLI(frameworkDir,
2583                    mDefParseFlags
2584                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2585                    scanFlags
2586                    | SCAN_NO_DEX
2587                    | SCAN_AS_SYSTEM
2588                    | SCAN_AS_PRIVILEGED,
2589                    0);
2590
2591            // Collected privileged system packages.
2592            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2593            scanDirTracedLI(privilegedAppDir,
2594                    mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2596                    scanFlags
2597                    | SCAN_AS_SYSTEM
2598                    | SCAN_AS_PRIVILEGED,
2599                    0);
2600
2601            // Collect ordinary system packages.
2602            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2603            scanDirTracedLI(systemAppDir,
2604                    mDefParseFlags
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2606                    scanFlags
2607                    | SCAN_AS_SYSTEM,
2608                    0);
2609
2610            // Collected privileged vendor packages.
2611            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2612            try {
2613                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2614            } catch (IOException e) {
2615                // failed to look up canonical path, continue with original one
2616            }
2617            scanDirTracedLI(privilegedVendorAppDir,
2618                    mDefParseFlags
2619                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2620                    scanFlags
2621                    | SCAN_AS_SYSTEM
2622                    | SCAN_AS_VENDOR
2623                    | SCAN_AS_PRIVILEGED,
2624                    0);
2625
2626            // Collect ordinary vendor packages.
2627            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2628            try {
2629                vendorAppDir = vendorAppDir.getCanonicalFile();
2630            } catch (IOException e) {
2631                // failed to look up canonical path, continue with original one
2632            }
2633            scanDirTracedLI(vendorAppDir,
2634                    mDefParseFlags
2635                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2636                    scanFlags
2637                    | SCAN_AS_SYSTEM
2638                    | SCAN_AS_VENDOR,
2639                    0);
2640
2641            // Collect all OEM packages.
2642            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2643            scanDirTracedLI(oemAppDir,
2644                    mDefParseFlags
2645                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2646                    scanFlags
2647                    | SCAN_AS_SYSTEM
2648                    | SCAN_AS_OEM,
2649                    0);
2650
2651            // Collected privileged product packages.
2652            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2653            try {
2654                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2655            } catch (IOException e) {
2656                // failed to look up canonical path, continue with original one
2657            }
2658            scanDirTracedLI(privilegedProductAppDir,
2659                    mDefParseFlags
2660                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2661                    scanFlags
2662                    | SCAN_AS_SYSTEM
2663                    | SCAN_AS_PRODUCT
2664                    | SCAN_AS_PRIVILEGED,
2665                    0);
2666
2667            // Collect ordinary product packages.
2668            File productAppDir = new File(Environment.getProductDirectory(), "app");
2669            try {
2670                productAppDir = productAppDir.getCanonicalFile();
2671            } catch (IOException e) {
2672                // failed to look up canonical path, continue with original one
2673            }
2674            scanDirTracedLI(productAppDir,
2675                    mDefParseFlags
2676                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2677                    scanFlags
2678                    | SCAN_AS_SYSTEM
2679                    | SCAN_AS_PRODUCT,
2680                    0);
2681
2682            // Prune any system packages that no longer exist.
2683            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2684            // Stub packages must either be replaced with full versions in the /data
2685            // partition or be disabled.
2686            final List<String> stubSystemApps = new ArrayList<>();
2687            if (!mOnlyCore) {
2688                // do this first before mucking with mPackages for the "expecting better" case
2689                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2690                while (pkgIterator.hasNext()) {
2691                    final PackageParser.Package pkg = pkgIterator.next();
2692                    if (pkg.isStub) {
2693                        stubSystemApps.add(pkg.packageName);
2694                    }
2695                }
2696
2697                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2698                while (psit.hasNext()) {
2699                    PackageSetting ps = psit.next();
2700
2701                    /*
2702                     * If this is not a system app, it can't be a
2703                     * disable system app.
2704                     */
2705                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2706                        continue;
2707                    }
2708
2709                    /*
2710                     * If the package is scanned, it's not erased.
2711                     */
2712                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2713                    if (scannedPkg != null) {
2714                        /*
2715                         * If the system app is both scanned and in the
2716                         * disabled packages list, then it must have been
2717                         * added via OTA. Remove it from the currently
2718                         * scanned package so the previously user-installed
2719                         * application can be scanned.
2720                         */
2721                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2722                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2723                                    + ps.name + "; removing system app.  Last known codePath="
2724                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2725                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2726                                    + scannedPkg.getLongVersionCode());
2727                            removePackageLI(scannedPkg, true);
2728                            mExpectingBetter.put(ps.name, ps.codePath);
2729                        }
2730
2731                        continue;
2732                    }
2733
2734                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2735                        psit.remove();
2736                        logCriticalInfo(Log.WARN, "System package " + ps.name
2737                                + " no longer exists; it's data will be wiped");
2738                        // Actual deletion of code and data will be handled by later
2739                        // reconciliation step
2740                    } else {
2741                        // we still have a disabled system package, but, it still might have
2742                        // been removed. check the code path still exists and check there's
2743                        // still a package. the latter can happen if an OTA keeps the same
2744                        // code path, but, changes the package name.
2745                        final PackageSetting disabledPs =
2746                                mSettings.getDisabledSystemPkgLPr(ps.name);
2747                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2748                                || disabledPs.pkg == null) {
2749                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2750                        }
2751                    }
2752                }
2753            }
2754
2755            //look for any incomplete package installations
2756            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2757            for (int i = 0; i < deletePkgsList.size(); i++) {
2758                // Actual deletion of code and data will be handled by later
2759                // reconciliation step
2760                final String packageName = deletePkgsList.get(i).name;
2761                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2762                synchronized (mPackages) {
2763                    mSettings.removePackageLPw(packageName);
2764                }
2765            }
2766
2767            //delete tmp files
2768            deleteTempPackageFiles();
2769
2770            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2771
2772            // Remove any shared userIDs that have no associated packages
2773            mSettings.pruneSharedUsersLPw();
2774            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2775            final int systemPackagesCount = mPackages.size();
2776            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2777                    + " ms, packageCount: " + systemPackagesCount
2778                    + " , timePerPackage: "
2779                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2780                    + " , cached: " + cachedSystemApps);
2781            if (mIsUpgrade && systemPackagesCount > 0) {
2782                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2783                        ((int) systemScanTime) / systemPackagesCount);
2784            }
2785            if (!mOnlyCore) {
2786                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2787                        SystemClock.uptimeMillis());
2788                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2789
2790                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2791                        | PackageParser.PARSE_FORWARD_LOCK,
2792                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2793
2794                // Remove disable package settings for updated system apps that were
2795                // removed via an OTA. If the update is no longer present, remove the
2796                // app completely. Otherwise, revoke their system privileges.
2797                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2798                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2799                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2800                    final String msg;
2801                    if (deletedPkg == null) {
2802                        // should have found an update, but, we didn't; remove everything
2803                        msg = "Updated system package " + deletedAppName
2804                                + " no longer exists; removing its data";
2805                        // Actual deletion of code and data will be handled by later
2806                        // reconciliation step
2807                    } else {
2808                        // found an update; revoke system privileges
2809                        msg = "Updated system package + " + deletedAppName
2810                                + " no longer exists; revoking system privileges";
2811
2812                        // Don't do anything if a stub is removed from the system image. If
2813                        // we were to remove the uncompressed version from the /data partition,
2814                        // this is where it'd be done.
2815
2816                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2817                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2818                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2819                    }
2820                    logCriticalInfo(Log.WARN, msg);
2821                }
2822
2823                /*
2824                 * Make sure all system apps that we expected to appear on
2825                 * the userdata partition actually showed up. If they never
2826                 * appeared, crawl back and revive the system version.
2827                 */
2828                for (int i = 0; i < mExpectingBetter.size(); i++) {
2829                    final String packageName = mExpectingBetter.keyAt(i);
2830                    if (!mPackages.containsKey(packageName)) {
2831                        final File scanFile = mExpectingBetter.valueAt(i);
2832
2833                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2834                                + " but never showed up; reverting to system");
2835
2836                        final @ParseFlags int reparseFlags;
2837                        final @ScanFlags int rescanFlags;
2838                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2839                            reparseFlags =
2840                                    mDefParseFlags |
2841                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2842                            rescanFlags =
2843                                    scanFlags
2844                                    | SCAN_AS_SYSTEM
2845                                    | SCAN_AS_PRIVILEGED;
2846                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2847                            reparseFlags =
2848                                    mDefParseFlags |
2849                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2850                            rescanFlags =
2851                                    scanFlags
2852                                    | SCAN_AS_SYSTEM;
2853                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2854                            reparseFlags =
2855                                    mDefParseFlags |
2856                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2857                            rescanFlags =
2858                                    scanFlags
2859                                    | SCAN_AS_SYSTEM
2860                                    | SCAN_AS_VENDOR
2861                                    | SCAN_AS_PRIVILEGED;
2862                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2863                            reparseFlags =
2864                                    mDefParseFlags |
2865                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2866                            rescanFlags =
2867                                    scanFlags
2868                                    | SCAN_AS_SYSTEM
2869                                    | SCAN_AS_VENDOR;
2870                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2871                            reparseFlags =
2872                                    mDefParseFlags |
2873                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2874                            rescanFlags =
2875                                    scanFlags
2876                                    | SCAN_AS_SYSTEM
2877                                    | SCAN_AS_OEM;
2878                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2879                            reparseFlags =
2880                                    mDefParseFlags |
2881                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2882                            rescanFlags =
2883                                    scanFlags
2884                                    | SCAN_AS_SYSTEM
2885                                    | SCAN_AS_PRODUCT
2886                                    | SCAN_AS_PRIVILEGED;
2887                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2888                            reparseFlags =
2889                                    mDefParseFlags |
2890                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2891                            rescanFlags =
2892                                    scanFlags
2893                                    | SCAN_AS_SYSTEM
2894                                    | SCAN_AS_PRODUCT;
2895                        } else {
2896                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2897                            continue;
2898                        }
2899
2900                        mSettings.enableSystemPackageLPw(packageName);
2901
2902                        try {
2903                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2904                        } catch (PackageManagerException e) {
2905                            Slog.e(TAG, "Failed to parse original system package: "
2906                                    + e.getMessage());
2907                        }
2908                    }
2909                }
2910
2911                // Uncompress and install any stubbed system applications.
2912                // This must be done last to ensure all stubs are replaced or disabled.
2913                decompressSystemApplications(stubSystemApps, scanFlags);
2914
2915                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2916                                - cachedSystemApps;
2917
2918                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2919                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2920                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2921                        + " ms, packageCount: " + dataPackagesCount
2922                        + " , timePerPackage: "
2923                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2924                        + " , cached: " + cachedNonSystemApps);
2925                if (mIsUpgrade && dataPackagesCount > 0) {
2926                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2927                            ((int) dataScanTime) / dataPackagesCount);
2928                }
2929            }
2930            mExpectingBetter.clear();
2931
2932            // Resolve the storage manager.
2933            mStorageManagerPackage = getStorageManagerPackageName();
2934
2935            // Resolve protected action filters. Only the setup wizard is allowed to
2936            // have a high priority filter for these actions.
2937            mSetupWizardPackage = getSetupWizardPackageName();
2938            if (mProtectedFilters.size() > 0) {
2939                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2940                    Slog.i(TAG, "No setup wizard;"
2941                        + " All protected intents capped to priority 0");
2942                }
2943                for (ActivityIntentInfo filter : mProtectedFilters) {
2944                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2945                        if (DEBUG_FILTERS) {
2946                            Slog.i(TAG, "Found setup wizard;"
2947                                + " allow priority " + filter.getPriority() + ";"
2948                                + " package: " + filter.activity.info.packageName
2949                                + " activity: " + filter.activity.className
2950                                + " priority: " + filter.getPriority());
2951                        }
2952                        // skip setup wizard; allow it to keep the high priority filter
2953                        continue;
2954                    }
2955                    if (DEBUG_FILTERS) {
2956                        Slog.i(TAG, "Protected action; cap priority to 0;"
2957                                + " package: " + filter.activity.info.packageName
2958                                + " activity: " + filter.activity.className
2959                                + " origPrio: " + filter.getPriority());
2960                    }
2961                    filter.setPriority(0);
2962                }
2963            }
2964            mDeferProtectedFilters = false;
2965            mProtectedFilters.clear();
2966
2967            // Now that we know all of the shared libraries, update all clients to have
2968            // the correct library paths.
2969            updateAllSharedLibrariesLPw(null);
2970
2971            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2972                // NOTE: We ignore potential failures here during a system scan (like
2973                // the rest of the commands above) because there's precious little we
2974                // can do about it. A settings error is reported, though.
2975                final List<String> changedAbiCodePath =
2976                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2977                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
2978                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
2979                        final String codePathString = changedAbiCodePath.get(i);
2980                        try {
2981                            mInstaller.rmdex(codePathString,
2982                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
2983                        } catch (InstallerException ignored) {
2984                        }
2985                    }
2986                }
2987            }
2988
2989            // Now that we know all the packages we are keeping,
2990            // read and update their last usage times.
2991            mPackageUsage.read(mPackages);
2992            mCompilerStats.read();
2993
2994            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2995                    SystemClock.uptimeMillis());
2996            Slog.i(TAG, "Time to scan packages: "
2997                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2998                    + " seconds");
2999
3000            // If the platform SDK has changed since the last time we booted,
3001            // we need to re-grant app permission to catch any new ones that
3002            // appear.  This is really a hack, and means that apps can in some
3003            // cases get permissions that the user didn't initially explicitly
3004            // allow...  it would be nice to have some better way to handle
3005            // this situation.
3006            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3007            if (sdkUpdated) {
3008                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3009                        + mSdkVersion + "; regranting permissions for internal storage");
3010            }
3011            mPermissionManager.updateAllPermissions(
3012                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3013                    mPermissionCallback);
3014            ver.sdkVersion = mSdkVersion;
3015
3016            // If this is the first boot or an update from pre-M, and it is a normal
3017            // boot, then we need to initialize the default preferred apps across
3018            // all defined users.
3019            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3020                for (UserInfo user : sUserManager.getUsers(true)) {
3021                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3022                    applyFactoryDefaultBrowserLPw(user.id);
3023                    primeDomainVerificationsLPw(user.id);
3024                }
3025            }
3026
3027            // Prepare storage for system user really early during boot,
3028            // since core system apps like SettingsProvider and SystemUI
3029            // can't wait for user to start
3030            final int storageFlags;
3031            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3032                storageFlags = StorageManager.FLAG_STORAGE_DE;
3033            } else {
3034                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3035            }
3036            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3037                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3038                    true /* onlyCoreApps */);
3039            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3040                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3041                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3042                traceLog.traceBegin("AppDataFixup");
3043                try {
3044                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3045                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3046                } catch (InstallerException e) {
3047                    Slog.w(TAG, "Trouble fixing GIDs", e);
3048                }
3049                traceLog.traceEnd();
3050
3051                traceLog.traceBegin("AppDataPrepare");
3052                if (deferPackages == null || deferPackages.isEmpty()) {
3053                    return;
3054                }
3055                int count = 0;
3056                for (String pkgName : deferPackages) {
3057                    PackageParser.Package pkg = null;
3058                    synchronized (mPackages) {
3059                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3060                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3061                            pkg = ps.pkg;
3062                        }
3063                    }
3064                    if (pkg != null) {
3065                        synchronized (mInstallLock) {
3066                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3067                                    true /* maybeMigrateAppData */);
3068                        }
3069                        count++;
3070                    }
3071                }
3072                traceLog.traceEnd();
3073                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3074            }, "prepareAppData");
3075
3076            // If this is first boot after an OTA, and a normal boot, then
3077            // we need to clear code cache directories.
3078            // Note that we do *not* clear the application profiles. These remain valid
3079            // across OTAs and are used to drive profile verification (post OTA) and
3080            // profile compilation (without waiting to collect a fresh set of profiles).
3081            if (mIsUpgrade && !onlyCore) {
3082                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3083                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3084                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3085                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3086                        // No apps are running this early, so no need to freeze
3087                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3088                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3089                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3090                    }
3091                }
3092                ver.fingerprint = Build.FINGERPRINT;
3093            }
3094
3095            checkDefaultBrowser();
3096
3097            // clear only after permissions and other defaults have been updated
3098            mExistingSystemPackages.clear();
3099            mPromoteSystemApps = false;
3100
3101            // All the changes are done during package scanning.
3102            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3103
3104            // can downgrade to reader
3105            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3106            mSettings.writeLPr();
3107            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3108            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3109                    SystemClock.uptimeMillis());
3110
3111            if (!mOnlyCore) {
3112                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3113                mRequiredInstallerPackage = getRequiredInstallerLPr();
3114                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3115                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3116                if (mIntentFilterVerifierComponent != null) {
3117                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3118                            mIntentFilterVerifierComponent);
3119                } else {
3120                    mIntentFilterVerifier = null;
3121                }
3122                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3123                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3124                        SharedLibraryInfo.VERSION_UNDEFINED);
3125                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3126                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3127                        SharedLibraryInfo.VERSION_UNDEFINED);
3128            } else {
3129                mRequiredVerifierPackage = null;
3130                mRequiredInstallerPackage = null;
3131                mRequiredUninstallerPackage = null;
3132                mIntentFilterVerifierComponent = null;
3133                mIntentFilterVerifier = null;
3134                mServicesSystemSharedLibraryPackageName = null;
3135                mSharedSystemSharedLibraryPackageName = null;
3136            }
3137
3138            mInstallerService = new PackageInstallerService(context, this);
3139            final Pair<ComponentName, String> instantAppResolverComponent =
3140                    getInstantAppResolverLPr();
3141            if (instantAppResolverComponent != null) {
3142                if (DEBUG_INSTANT) {
3143                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3144                }
3145                mInstantAppResolverConnection = new InstantAppResolverConnection(
3146                        mContext, instantAppResolverComponent.first,
3147                        instantAppResolverComponent.second);
3148                mInstantAppResolverSettingsComponent =
3149                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3150            } else {
3151                mInstantAppResolverConnection = null;
3152                mInstantAppResolverSettingsComponent = null;
3153            }
3154            updateInstantAppInstallerLocked(null);
3155
3156            // Read and update the usage of dex files.
3157            // Do this at the end of PM init so that all the packages have their
3158            // data directory reconciled.
3159            // At this point we know the code paths of the packages, so we can validate
3160            // the disk file and build the internal cache.
3161            // The usage file is expected to be small so loading and verifying it
3162            // should take a fairly small time compare to the other activities (e.g. package
3163            // scanning).
3164            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3165            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3166            for (int userId : currentUserIds) {
3167                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3168            }
3169            mDexManager.load(userPackages);
3170            if (mIsUpgrade) {
3171                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3172                        (int) (SystemClock.uptimeMillis() - startTime));
3173            }
3174        } // synchronized (mPackages)
3175        } // synchronized (mInstallLock)
3176
3177        // Now after opening every single application zip, make sure they
3178        // are all flushed.  Not really needed, but keeps things nice and
3179        // tidy.
3180        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3181        Runtime.getRuntime().gc();
3182        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3183
3184        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3185        FallbackCategoryProvider.loadFallbacks();
3186        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3187
3188        // The initial scanning above does many calls into installd while
3189        // holding the mPackages lock, but we're mostly interested in yelling
3190        // once we have a booted system.
3191        mInstaller.setWarnIfHeld(mPackages);
3192
3193        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3194    }
3195
3196    /**
3197     * Uncompress and install stub applications.
3198     * <p>In order to save space on the system partition, some applications are shipped in a
3199     * compressed form. In addition the compressed bits for the full application, the
3200     * system image contains a tiny stub comprised of only the Android manifest.
3201     * <p>During the first boot, attempt to uncompress and install the full application. If
3202     * the application can't be installed for any reason, disable the stub and prevent
3203     * uncompressing the full application during future boots.
3204     * <p>In order to forcefully attempt an installation of a full application, go to app
3205     * settings and enable the application.
3206     */
3207    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3208        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3209            final String pkgName = stubSystemApps.get(i);
3210            // skip if the system package is already disabled
3211            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3212                stubSystemApps.remove(i);
3213                continue;
3214            }
3215            // skip if the package isn't installed (?!); this should never happen
3216            final PackageParser.Package pkg = mPackages.get(pkgName);
3217            if (pkg == null) {
3218                stubSystemApps.remove(i);
3219                continue;
3220            }
3221            // skip if the package has been disabled by the user
3222            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3223            if (ps != null) {
3224                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3225                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3226                    stubSystemApps.remove(i);
3227                    continue;
3228                }
3229            }
3230
3231            if (DEBUG_COMPRESSION) {
3232                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3233            }
3234
3235            // uncompress the binary to its eventual destination on /data
3236            final File scanFile = decompressPackage(pkg);
3237            if (scanFile == null) {
3238                continue;
3239            }
3240
3241            // install the package to replace the stub on /system
3242            try {
3243                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3244                removePackageLI(pkg, true /*chatty*/);
3245                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3246                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3247                        UserHandle.USER_SYSTEM, "android");
3248                stubSystemApps.remove(i);
3249                continue;
3250            } catch (PackageManagerException e) {
3251                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3252            }
3253
3254            // any failed attempt to install the package will be cleaned up later
3255        }
3256
3257        // disable any stub still left; these failed to install the full application
3258        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3259            final String pkgName = stubSystemApps.get(i);
3260            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3261            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3262                    UserHandle.USER_SYSTEM, "android");
3263            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3264        }
3265    }
3266
3267    /**
3268     * Decompresses the given package on the system image onto
3269     * the /data partition.
3270     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3271     */
3272    private File decompressPackage(PackageParser.Package pkg) {
3273        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3274        if (compressedFiles == null || compressedFiles.length == 0) {
3275            if (DEBUG_COMPRESSION) {
3276                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3277            }
3278            return null;
3279        }
3280        final File dstCodePath =
3281                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3282        int ret = PackageManager.INSTALL_SUCCEEDED;
3283        try {
3284            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3285            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3286            for (File srcFile : compressedFiles) {
3287                final String srcFileName = srcFile.getName();
3288                final String dstFileName = srcFileName.substring(
3289                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3290                final File dstFile = new File(dstCodePath, dstFileName);
3291                ret = decompressFile(srcFile, dstFile);
3292                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3293                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3294                            + "; pkg: " + pkg.packageName
3295                            + ", file: " + dstFileName);
3296                    break;
3297                }
3298            }
3299        } catch (ErrnoException e) {
3300            logCriticalInfo(Log.ERROR, "Failed to decompress"
3301                    + "; pkg: " + pkg.packageName
3302                    + ", err: " + e.errno);
3303        }
3304        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3305            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3306            NativeLibraryHelper.Handle handle = null;
3307            try {
3308                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3309                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3310                        null /*abiOverride*/);
3311            } catch (IOException e) {
3312                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3313                        + "; pkg: " + pkg.packageName);
3314                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3315            } finally {
3316                IoUtils.closeQuietly(handle);
3317            }
3318        }
3319        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3320            if (dstCodePath == null || !dstCodePath.exists()) {
3321                return null;
3322            }
3323            removeCodePathLI(dstCodePath);
3324            return null;
3325        }
3326
3327        return dstCodePath;
3328    }
3329
3330    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3331        // we're only interested in updating the installer appliction when 1) it's not
3332        // already set or 2) the modified package is the installer
3333        if (mInstantAppInstallerActivity != null
3334                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3335                        .equals(modifiedPackage)) {
3336            return;
3337        }
3338        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3339    }
3340
3341    private static File preparePackageParserCache(boolean isUpgrade) {
3342        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3343            return null;
3344        }
3345
3346        // Disable package parsing on eng builds to allow for faster incremental development.
3347        if (Build.IS_ENG) {
3348            return null;
3349        }
3350
3351        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3352            Slog.i(TAG, "Disabling package parser cache due to system property.");
3353            return null;
3354        }
3355
3356        // The base directory for the package parser cache lives under /data/system/.
3357        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3358                "package_cache");
3359        if (cacheBaseDir == null) {
3360            return null;
3361        }
3362
3363        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3364        // This also serves to "GC" unused entries when the package cache version changes (which
3365        // can only happen during upgrades).
3366        if (isUpgrade) {
3367            FileUtils.deleteContents(cacheBaseDir);
3368        }
3369
3370
3371        // Return the versioned package cache directory. This is something like
3372        // "/data/system/package_cache/1"
3373        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3374
3375        // The following is a workaround to aid development on non-numbered userdebug
3376        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3377        // the system partition is newer.
3378        //
3379        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3380        // that starts with "eng." to signify that this is an engineering build and not
3381        // destined for release.
3382        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3383            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3384
3385            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3386            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3387            // in general and should not be used for production changes. In this specific case,
3388            // we know that they will work.
3389            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3390            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3391                FileUtils.deleteContents(cacheBaseDir);
3392                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3393            }
3394        }
3395
3396        return cacheDir;
3397    }
3398
3399    @Override
3400    public boolean isFirstBoot() {
3401        // allow instant applications
3402        return mFirstBoot;
3403    }
3404
3405    @Override
3406    public boolean isOnlyCoreApps() {
3407        // allow instant applications
3408        return mOnlyCore;
3409    }
3410
3411    @Override
3412    public boolean isUpgrade() {
3413        // allow instant applications
3414        // The system property allows testing ota flow when upgraded to the same image.
3415        return mIsUpgrade || SystemProperties.getBoolean(
3416                "persist.pm.mock-upgrade", false /* default */);
3417    }
3418
3419    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3420        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3421
3422        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3423                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3424                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3425        if (matches.size() == 1) {
3426            return matches.get(0).getComponentInfo().packageName;
3427        } else if (matches.size() == 0) {
3428            Log.e(TAG, "There should probably be a verifier, but, none were found");
3429            return null;
3430        }
3431        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3432    }
3433
3434    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3435        synchronized (mPackages) {
3436            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3437            if (libraryEntry == null) {
3438                throw new IllegalStateException("Missing required shared library:" + name);
3439            }
3440            return libraryEntry.apk;
3441        }
3442    }
3443
3444    private @NonNull String getRequiredInstallerLPr() {
3445        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3446        intent.addCategory(Intent.CATEGORY_DEFAULT);
3447        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3448
3449        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3450                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3451                UserHandle.USER_SYSTEM);
3452        if (matches.size() == 1) {
3453            ResolveInfo resolveInfo = matches.get(0);
3454            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3455                throw new RuntimeException("The installer must be a privileged app");
3456            }
3457            return matches.get(0).getComponentInfo().packageName;
3458        } else {
3459            throw new RuntimeException("There must be exactly one installer; found " + matches);
3460        }
3461    }
3462
3463    private @NonNull String getRequiredUninstallerLPr() {
3464        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3465        intent.addCategory(Intent.CATEGORY_DEFAULT);
3466        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3467
3468        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3469                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3470                UserHandle.USER_SYSTEM);
3471        if (resolveInfo == null ||
3472                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3473            throw new RuntimeException("There must be exactly one uninstaller; found "
3474                    + resolveInfo);
3475        }
3476        return resolveInfo.getComponentInfo().packageName;
3477    }
3478
3479    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3480        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3481
3482        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3483                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3484                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3485        ResolveInfo best = null;
3486        final int N = matches.size();
3487        for (int i = 0; i < N; i++) {
3488            final ResolveInfo cur = matches.get(i);
3489            final String packageName = cur.getComponentInfo().packageName;
3490            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3491                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3492                continue;
3493            }
3494
3495            if (best == null || cur.priority > best.priority) {
3496                best = cur;
3497            }
3498        }
3499
3500        if (best != null) {
3501            return best.getComponentInfo().getComponentName();
3502        }
3503        Slog.w(TAG, "Intent filter verifier not found");
3504        return null;
3505    }
3506
3507    @Override
3508    public @Nullable ComponentName getInstantAppResolverComponent() {
3509        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3510            return null;
3511        }
3512        synchronized (mPackages) {
3513            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3514            if (instantAppResolver == null) {
3515                return null;
3516            }
3517            return instantAppResolver.first;
3518        }
3519    }
3520
3521    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3522        final String[] packageArray =
3523                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3524        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3525            if (DEBUG_INSTANT) {
3526                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3527            }
3528            return null;
3529        }
3530
3531        final int callingUid = Binder.getCallingUid();
3532        final int resolveFlags =
3533                MATCH_DIRECT_BOOT_AWARE
3534                | MATCH_DIRECT_BOOT_UNAWARE
3535                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3536        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3537        final Intent resolverIntent = new Intent(actionName);
3538        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3539                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3540        final int N = resolvers.size();
3541        if (N == 0) {
3542            if (DEBUG_INSTANT) {
3543                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3544            }
3545            return null;
3546        }
3547
3548        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3549        for (int i = 0; i < N; i++) {
3550            final ResolveInfo info = resolvers.get(i);
3551
3552            if (info.serviceInfo == null) {
3553                continue;
3554            }
3555
3556            final String packageName = info.serviceInfo.packageName;
3557            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3558                if (DEBUG_INSTANT) {
3559                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3560                            + " pkg: " + packageName + ", info:" + info);
3561                }
3562                continue;
3563            }
3564
3565            if (DEBUG_INSTANT) {
3566                Slog.v(TAG, "Ephemeral resolver found;"
3567                        + " pkg: " + packageName + ", info:" + info);
3568            }
3569            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3570        }
3571        if (DEBUG_INSTANT) {
3572            Slog.v(TAG, "Ephemeral resolver NOT found");
3573        }
3574        return null;
3575    }
3576
3577    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3578        String[] orderedActions = Build.IS_ENG
3579                ? new String[]{
3580                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3581                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3582                : new String[]{
3583                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3584
3585        final int resolveFlags =
3586                MATCH_DIRECT_BOOT_AWARE
3587                        | MATCH_DIRECT_BOOT_UNAWARE
3588                        | Intent.FLAG_IGNORE_EPHEMERAL
3589                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3590        final Intent intent = new Intent();
3591        intent.addCategory(Intent.CATEGORY_DEFAULT);
3592        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3593        List<ResolveInfo> matches = null;
3594        for (String action : orderedActions) {
3595            intent.setAction(action);
3596            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3597                    resolveFlags, UserHandle.USER_SYSTEM);
3598            if (matches.isEmpty()) {
3599                if (DEBUG_INSTANT) {
3600                    Slog.d(TAG, "Instant App installer not found with " + action);
3601                }
3602            } else {
3603                break;
3604            }
3605        }
3606        Iterator<ResolveInfo> iter = matches.iterator();
3607        while (iter.hasNext()) {
3608            final ResolveInfo rInfo = iter.next();
3609            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3610            if (ps != null) {
3611                final PermissionsState permissionsState = ps.getPermissionsState();
3612                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3613                        || Build.IS_ENG) {
3614                    continue;
3615                }
3616            }
3617            iter.remove();
3618        }
3619        if (matches.size() == 0) {
3620            return null;
3621        } else if (matches.size() == 1) {
3622            return (ActivityInfo) matches.get(0).getComponentInfo();
3623        } else {
3624            throw new RuntimeException(
3625                    "There must be at most one ephemeral installer; found " + matches);
3626        }
3627    }
3628
3629    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3630            @NonNull ComponentName resolver) {
3631        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3632                .addCategory(Intent.CATEGORY_DEFAULT)
3633                .setPackage(resolver.getPackageName());
3634        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3635        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3636                UserHandle.USER_SYSTEM);
3637        if (matches.isEmpty()) {
3638            return null;
3639        }
3640        return matches.get(0).getComponentInfo().getComponentName();
3641    }
3642
3643    private void primeDomainVerificationsLPw(int userId) {
3644        if (DEBUG_DOMAIN_VERIFICATION) {
3645            Slog.d(TAG, "Priming domain verifications in user " + userId);
3646        }
3647
3648        SystemConfig systemConfig = SystemConfig.getInstance();
3649        ArraySet<String> packages = systemConfig.getLinkedApps();
3650
3651        for (String packageName : packages) {
3652            PackageParser.Package pkg = mPackages.get(packageName);
3653            if (pkg != null) {
3654                if (!pkg.isSystem()) {
3655                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3656                    continue;
3657                }
3658
3659                ArraySet<String> domains = null;
3660                for (PackageParser.Activity a : pkg.activities) {
3661                    for (ActivityIntentInfo filter : a.intents) {
3662                        if (hasValidDomains(filter)) {
3663                            if (domains == null) {
3664                                domains = new ArraySet<String>();
3665                            }
3666                            domains.addAll(filter.getHostsList());
3667                        }
3668                    }
3669                }
3670
3671                if (domains != null && domains.size() > 0) {
3672                    if (DEBUG_DOMAIN_VERIFICATION) {
3673                        Slog.v(TAG, "      + " + packageName);
3674                    }
3675                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3676                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3677                    // and then 'always' in the per-user state actually used for intent resolution.
3678                    final IntentFilterVerificationInfo ivi;
3679                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3680                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3681                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3682                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3683                } else {
3684                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3685                            + "' does not handle web links");
3686                }
3687            } else {
3688                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3689            }
3690        }
3691
3692        scheduleWritePackageRestrictionsLocked(userId);
3693        scheduleWriteSettingsLocked();
3694    }
3695
3696    private void applyFactoryDefaultBrowserLPw(int userId) {
3697        // The default browser app's package name is stored in a string resource,
3698        // with a product-specific overlay used for vendor customization.
3699        String browserPkg = mContext.getResources().getString(
3700                com.android.internal.R.string.default_browser);
3701        if (!TextUtils.isEmpty(browserPkg)) {
3702            // non-empty string => required to be a known package
3703            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3704            if (ps == null) {
3705                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3706                browserPkg = null;
3707            } else {
3708                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3709            }
3710        }
3711
3712        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3713        // default.  If there's more than one, just leave everything alone.
3714        if (browserPkg == null) {
3715            calculateDefaultBrowserLPw(userId);
3716        }
3717    }
3718
3719    private void calculateDefaultBrowserLPw(int userId) {
3720        List<String> allBrowsers = resolveAllBrowserApps(userId);
3721        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3722        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3723    }
3724
3725    private List<String> resolveAllBrowserApps(int userId) {
3726        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3727        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3728                PackageManager.MATCH_ALL, userId);
3729
3730        final int count = list.size();
3731        List<String> result = new ArrayList<String>(count);
3732        for (int i=0; i<count; i++) {
3733            ResolveInfo info = list.get(i);
3734            if (info.activityInfo == null
3735                    || !info.handleAllWebDataURI
3736                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3737                    || result.contains(info.activityInfo.packageName)) {
3738                continue;
3739            }
3740            result.add(info.activityInfo.packageName);
3741        }
3742
3743        return result;
3744    }
3745
3746    private boolean packageIsBrowser(String packageName, int userId) {
3747        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3748                PackageManager.MATCH_ALL, userId);
3749        final int N = list.size();
3750        for (int i = 0; i < N; i++) {
3751            ResolveInfo info = list.get(i);
3752            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3753                return true;
3754            }
3755        }
3756        return false;
3757    }
3758
3759    private void checkDefaultBrowser() {
3760        final int myUserId = UserHandle.myUserId();
3761        final String packageName = getDefaultBrowserPackageName(myUserId);
3762        if (packageName != null) {
3763            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3764            if (info == null) {
3765                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3766                synchronized (mPackages) {
3767                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3768                }
3769            }
3770        }
3771    }
3772
3773    @Override
3774    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3775            throws RemoteException {
3776        try {
3777            return super.onTransact(code, data, reply, flags);
3778        } catch (RuntimeException e) {
3779            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3780                Slog.wtf(TAG, "Package Manager Crash", e);
3781            }
3782            throw e;
3783        }
3784    }
3785
3786    static int[] appendInts(int[] cur, int[] add) {
3787        if (add == null) return cur;
3788        if (cur == null) return add;
3789        final int N = add.length;
3790        for (int i=0; i<N; i++) {
3791            cur = appendInt(cur, add[i]);
3792        }
3793        return cur;
3794    }
3795
3796    /**
3797     * Returns whether or not a full application can see an instant application.
3798     * <p>
3799     * Currently, there are three cases in which this can occur:
3800     * <ol>
3801     * <li>The calling application is a "special" process. Special processes
3802     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3803     * <li>The calling application has the permission
3804     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3805     * <li>The calling application is the default launcher on the
3806     *     system partition.</li>
3807     * </ol>
3808     */
3809    private boolean canViewInstantApps(int callingUid, int userId) {
3810        if (callingUid < Process.FIRST_APPLICATION_UID) {
3811            return true;
3812        }
3813        if (mContext.checkCallingOrSelfPermission(
3814                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3815            return true;
3816        }
3817        if (mContext.checkCallingOrSelfPermission(
3818                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3819            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3820            if (homeComponent != null
3821                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3822                return true;
3823            }
3824        }
3825        return false;
3826    }
3827
3828    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3829        if (!sUserManager.exists(userId)) return null;
3830        if (ps == null) {
3831            return null;
3832        }
3833        final int callingUid = Binder.getCallingUid();
3834        // Filter out ephemeral app metadata:
3835        //   * The system/shell/root can see metadata for any app
3836        //   * An installed app can see metadata for 1) other installed apps
3837        //     and 2) ephemeral apps that have explicitly interacted with it
3838        //   * Ephemeral apps can only see their own data and exposed installed apps
3839        //   * Holding a signature permission allows seeing instant apps
3840        if (filterAppAccessLPr(ps, callingUid, userId)) {
3841            return null;
3842        }
3843
3844        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3845                && ps.isSystem()) {
3846            flags |= MATCH_ANY_USER;
3847        }
3848
3849        final PackageUserState state = ps.readUserState(userId);
3850        PackageParser.Package p = ps.pkg;
3851        if (p != null) {
3852            final PermissionsState permissionsState = ps.getPermissionsState();
3853
3854            // Compute GIDs only if requested
3855            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3856                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3857            // Compute granted permissions only if package has requested permissions
3858            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3859                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3860
3861            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3862                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3863
3864            if (packageInfo == null) {
3865                return null;
3866            }
3867
3868            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3869                    resolveExternalPackageNameLPr(p);
3870
3871            return packageInfo;
3872        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3873            PackageInfo pi = new PackageInfo();
3874            pi.packageName = ps.name;
3875            pi.setLongVersionCode(ps.versionCode);
3876            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3877            pi.firstInstallTime = ps.firstInstallTime;
3878            pi.lastUpdateTime = ps.lastUpdateTime;
3879
3880            ApplicationInfo ai = new ApplicationInfo();
3881            ai.packageName = ps.name;
3882            ai.uid = UserHandle.getUid(userId, ps.appId);
3883            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3884            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3885            ai.versionCode = ps.versionCode;
3886            ai.flags = ps.pkgFlags;
3887            ai.privateFlags = ps.pkgPrivateFlags;
3888            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3889
3890            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3891                    + ps.name + "]. Provides a minimum info.");
3892            return pi;
3893        } else {
3894            return null;
3895        }
3896    }
3897
3898    @Override
3899    public void checkPackageStartable(String packageName, int userId) {
3900        final int callingUid = Binder.getCallingUid();
3901        if (getInstantAppPackageName(callingUid) != null) {
3902            throw new SecurityException("Instant applications don't have access to this method");
3903        }
3904        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3905        synchronized (mPackages) {
3906            final PackageSetting ps = mSettings.mPackages.get(packageName);
3907            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3908                throw new SecurityException("Package " + packageName + " was not found!");
3909            }
3910
3911            if (!ps.getInstalled(userId)) {
3912                throw new SecurityException(
3913                        "Package " + packageName + " was not installed for user " + userId + "!");
3914            }
3915
3916            if (mSafeMode && !ps.isSystem()) {
3917                throw new SecurityException("Package " + packageName + " not a system app!");
3918            }
3919
3920            if (mFrozenPackages.contains(packageName)) {
3921                throw new SecurityException("Package " + packageName + " is currently frozen!");
3922            }
3923
3924            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3925                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3926            }
3927        }
3928    }
3929
3930    @Override
3931    public boolean isPackageAvailable(String packageName, int userId) {
3932        if (!sUserManager.exists(userId)) return false;
3933        final int callingUid = Binder.getCallingUid();
3934        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3935                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3936        synchronized (mPackages) {
3937            PackageParser.Package p = mPackages.get(packageName);
3938            if (p != null) {
3939                final PackageSetting ps = (PackageSetting) p.mExtras;
3940                if (filterAppAccessLPr(ps, callingUid, userId)) {
3941                    return false;
3942                }
3943                if (ps != null) {
3944                    final PackageUserState state = ps.readUserState(userId);
3945                    if (state != null) {
3946                        return PackageParser.isAvailable(state);
3947                    }
3948                }
3949            }
3950        }
3951        return false;
3952    }
3953
3954    @Override
3955    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3956        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3957                flags, Binder.getCallingUid(), userId);
3958    }
3959
3960    @Override
3961    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3962            int flags, int userId) {
3963        return getPackageInfoInternal(versionedPackage.getPackageName(),
3964                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3965    }
3966
3967    /**
3968     * Important: The provided filterCallingUid is used exclusively to filter out packages
3969     * that can be seen based on user state. It's typically the original caller uid prior
3970     * to clearing. Because it can only be provided by trusted code, it's value can be
3971     * trusted and will be used as-is; unlike userId which will be validated by this method.
3972     */
3973    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3974            int flags, int filterCallingUid, int userId) {
3975        if (!sUserManager.exists(userId)) return null;
3976        flags = updateFlagsForPackage(flags, userId, packageName);
3977        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3978                false /* requireFullPermission */, false /* checkShell */, "get package info");
3979
3980        // reader
3981        synchronized (mPackages) {
3982            // Normalize package name to handle renamed packages and static libs
3983            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3984
3985            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3986            if (matchFactoryOnly) {
3987                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3988                if (ps != null) {
3989                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3990                        return null;
3991                    }
3992                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3993                        return null;
3994                    }
3995                    return generatePackageInfo(ps, flags, userId);
3996                }
3997            }
3998
3999            PackageParser.Package p = mPackages.get(packageName);
4000            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4001                return null;
4002            }
4003            if (DEBUG_PACKAGE_INFO)
4004                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4005            if (p != null) {
4006                final PackageSetting ps = (PackageSetting) p.mExtras;
4007                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4008                    return null;
4009                }
4010                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4011                    return null;
4012                }
4013                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4014            }
4015            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4016                final PackageSetting ps = mSettings.mPackages.get(packageName);
4017                if (ps == null) return null;
4018                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4019                    return null;
4020                }
4021                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4022                    return null;
4023                }
4024                return generatePackageInfo(ps, flags, userId);
4025            }
4026        }
4027        return null;
4028    }
4029
4030    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4031        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4032            return true;
4033        }
4034        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4035            return true;
4036        }
4037        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4038            return true;
4039        }
4040        return false;
4041    }
4042
4043    private boolean isComponentVisibleToInstantApp(
4044            @Nullable ComponentName component, @ComponentType int type) {
4045        if (type == TYPE_ACTIVITY) {
4046            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4047            return activity != null
4048                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4049                    : false;
4050        } else if (type == TYPE_RECEIVER) {
4051            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4052            return activity != null
4053                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4054                    : false;
4055        } else if (type == TYPE_SERVICE) {
4056            final PackageParser.Service service = mServices.mServices.get(component);
4057            return service != null
4058                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4059                    : false;
4060        } else if (type == TYPE_PROVIDER) {
4061            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4062            return provider != null
4063                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4064                    : false;
4065        } else if (type == TYPE_UNKNOWN) {
4066            return isComponentVisibleToInstantApp(component);
4067        }
4068        return false;
4069    }
4070
4071    /**
4072     * Returns whether or not access to the application should be filtered.
4073     * <p>
4074     * Access may be limited based upon whether the calling or target applications
4075     * are instant applications.
4076     *
4077     * @see #canAccessInstantApps(int)
4078     */
4079    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4080            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4081        // if we're in an isolated process, get the real calling UID
4082        if (Process.isIsolated(callingUid)) {
4083            callingUid = mIsolatedOwners.get(callingUid);
4084        }
4085        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4086        final boolean callerIsInstantApp = instantAppPkgName != null;
4087        if (ps == null) {
4088            if (callerIsInstantApp) {
4089                // pretend the application exists, but, needs to be filtered
4090                return true;
4091            }
4092            return false;
4093        }
4094        // if the target and caller are the same application, don't filter
4095        if (isCallerSameApp(ps.name, callingUid)) {
4096            return false;
4097        }
4098        if (callerIsInstantApp) {
4099            // request for a specific component; if it hasn't been explicitly exposed, filter
4100            if (component != null) {
4101                return !isComponentVisibleToInstantApp(component, componentType);
4102            }
4103            // request for application; if no components have been explicitly exposed, filter
4104            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4105        }
4106        if (ps.getInstantApp(userId)) {
4107            // caller can see all components of all instant applications, don't filter
4108            if (canViewInstantApps(callingUid, userId)) {
4109                return false;
4110            }
4111            // request for a specific instant application component, filter
4112            if (component != null) {
4113                return true;
4114            }
4115            // request for an instant application; if the caller hasn't been granted access, filter
4116            return !mInstantAppRegistry.isInstantAccessGranted(
4117                    userId, UserHandle.getAppId(callingUid), ps.appId);
4118        }
4119        return false;
4120    }
4121
4122    /**
4123     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4124     */
4125    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4126        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4127    }
4128
4129    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4130            int flags) {
4131        // Callers can access only the libs they depend on, otherwise they need to explicitly
4132        // ask for the shared libraries given the caller is allowed to access all static libs.
4133        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4134            // System/shell/root get to see all static libs
4135            final int appId = UserHandle.getAppId(uid);
4136            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4137                    || appId == Process.ROOT_UID) {
4138                return false;
4139            }
4140        }
4141
4142        // No package means no static lib as it is always on internal storage
4143        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4144            return false;
4145        }
4146
4147        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4148                ps.pkg.staticSharedLibVersion);
4149        if (libEntry == null) {
4150            return false;
4151        }
4152
4153        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4154        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4155        if (uidPackageNames == null) {
4156            return true;
4157        }
4158
4159        for (String uidPackageName : uidPackageNames) {
4160            if (ps.name.equals(uidPackageName)) {
4161                return false;
4162            }
4163            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4164            if (uidPs != null) {
4165                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4166                        libEntry.info.getName());
4167                if (index < 0) {
4168                    continue;
4169                }
4170                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4171                    return false;
4172                }
4173            }
4174        }
4175        return true;
4176    }
4177
4178    @Override
4179    public String[] currentToCanonicalPackageNames(String[] names) {
4180        final int callingUid = Binder.getCallingUid();
4181        if (getInstantAppPackageName(callingUid) != null) {
4182            return names;
4183        }
4184        final String[] out = new String[names.length];
4185        // reader
4186        synchronized (mPackages) {
4187            final int callingUserId = UserHandle.getUserId(callingUid);
4188            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4189            for (int i=names.length-1; i>=0; i--) {
4190                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4191                boolean translateName = false;
4192                if (ps != null && ps.realName != null) {
4193                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4194                    translateName = !targetIsInstantApp
4195                            || canViewInstantApps
4196                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4197                                    UserHandle.getAppId(callingUid), ps.appId);
4198                }
4199                out[i] = translateName ? ps.realName : names[i];
4200            }
4201        }
4202        return out;
4203    }
4204
4205    @Override
4206    public String[] canonicalToCurrentPackageNames(String[] names) {
4207        final int callingUid = Binder.getCallingUid();
4208        if (getInstantAppPackageName(callingUid) != null) {
4209            return names;
4210        }
4211        final String[] out = new String[names.length];
4212        // reader
4213        synchronized (mPackages) {
4214            final int callingUserId = UserHandle.getUserId(callingUid);
4215            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4216            for (int i=names.length-1; i>=0; i--) {
4217                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4218                boolean translateName = false;
4219                if (cur != null) {
4220                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4221                    final boolean targetIsInstantApp =
4222                            ps != null && ps.getInstantApp(callingUserId);
4223                    translateName = !targetIsInstantApp
4224                            || canViewInstantApps
4225                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4226                                    UserHandle.getAppId(callingUid), ps.appId);
4227                }
4228                out[i] = translateName ? cur : names[i];
4229            }
4230        }
4231        return out;
4232    }
4233
4234    @Override
4235    public int getPackageUid(String packageName, int flags, int userId) {
4236        if (!sUserManager.exists(userId)) return -1;
4237        final int callingUid = Binder.getCallingUid();
4238        flags = updateFlagsForPackage(flags, userId, packageName);
4239        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4240                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4241
4242        // reader
4243        synchronized (mPackages) {
4244            final PackageParser.Package p = mPackages.get(packageName);
4245            if (p != null && p.isMatch(flags)) {
4246                PackageSetting ps = (PackageSetting) p.mExtras;
4247                if (filterAppAccessLPr(ps, callingUid, userId)) {
4248                    return -1;
4249                }
4250                return UserHandle.getUid(userId, p.applicationInfo.uid);
4251            }
4252            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4253                final PackageSetting ps = mSettings.mPackages.get(packageName);
4254                if (ps != null && ps.isMatch(flags)
4255                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4256                    return UserHandle.getUid(userId, ps.appId);
4257                }
4258            }
4259        }
4260
4261        return -1;
4262    }
4263
4264    @Override
4265    public int[] getPackageGids(String packageName, int flags, int userId) {
4266        if (!sUserManager.exists(userId)) return null;
4267        final int callingUid = Binder.getCallingUid();
4268        flags = updateFlagsForPackage(flags, userId, packageName);
4269        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4270                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4271
4272        // reader
4273        synchronized (mPackages) {
4274            final PackageParser.Package p = mPackages.get(packageName);
4275            if (p != null && p.isMatch(flags)) {
4276                PackageSetting ps = (PackageSetting) p.mExtras;
4277                if (filterAppAccessLPr(ps, callingUid, userId)) {
4278                    return null;
4279                }
4280                // TODO: Shouldn't this be checking for package installed state for userId and
4281                // return null?
4282                return ps.getPermissionsState().computeGids(userId);
4283            }
4284            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4285                final PackageSetting ps = mSettings.mPackages.get(packageName);
4286                if (ps != null && ps.isMatch(flags)
4287                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4288                    return ps.getPermissionsState().computeGids(userId);
4289                }
4290            }
4291        }
4292
4293        return null;
4294    }
4295
4296    @Override
4297    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4298        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4299    }
4300
4301    @Override
4302    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4303            int flags) {
4304        final List<PermissionInfo> permissionList =
4305                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4306        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4307    }
4308
4309    @Override
4310    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4311        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4312    }
4313
4314    @Override
4315    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4316        final List<PermissionGroupInfo> permissionList =
4317                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4318        return (permissionList == null)
4319                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4320    }
4321
4322    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4323            int filterCallingUid, int userId) {
4324        if (!sUserManager.exists(userId)) return null;
4325        PackageSetting ps = mSettings.mPackages.get(packageName);
4326        if (ps != null) {
4327            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4328                return null;
4329            }
4330            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4331                return null;
4332            }
4333            if (ps.pkg == null) {
4334                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4335                if (pInfo != null) {
4336                    return pInfo.applicationInfo;
4337                }
4338                return null;
4339            }
4340            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4341                    ps.readUserState(userId), userId);
4342            if (ai != null) {
4343                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4344            }
4345            return ai;
4346        }
4347        return null;
4348    }
4349
4350    @Override
4351    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4352        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4353    }
4354
4355    /**
4356     * Important: The provided filterCallingUid is used exclusively to filter out applications
4357     * that can be seen based on user state. It's typically the original caller uid prior
4358     * to clearing. Because it can only be provided by trusted code, it's value can be
4359     * trusted and will be used as-is; unlike userId which will be validated by this method.
4360     */
4361    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4362            int filterCallingUid, int userId) {
4363        if (!sUserManager.exists(userId)) return null;
4364        flags = updateFlagsForApplication(flags, userId, packageName);
4365        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4366                false /* requireFullPermission */, false /* checkShell */, "get application info");
4367
4368        // writer
4369        synchronized (mPackages) {
4370            // Normalize package name to handle renamed packages and static libs
4371            packageName = resolveInternalPackageNameLPr(packageName,
4372                    PackageManager.VERSION_CODE_HIGHEST);
4373
4374            PackageParser.Package p = mPackages.get(packageName);
4375            if (DEBUG_PACKAGE_INFO) Log.v(
4376                    TAG, "getApplicationInfo " + packageName
4377                    + ": " + p);
4378            if (p != null) {
4379                PackageSetting ps = mSettings.mPackages.get(packageName);
4380                if (ps == null) return null;
4381                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4382                    return null;
4383                }
4384                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4385                    return null;
4386                }
4387                // Note: isEnabledLP() does not apply here - always return info
4388                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4389                        p, flags, ps.readUserState(userId), userId);
4390                if (ai != null) {
4391                    ai.packageName = resolveExternalPackageNameLPr(p);
4392                }
4393                return ai;
4394            }
4395            if ("android".equals(packageName)||"system".equals(packageName)) {
4396                return mAndroidApplication;
4397            }
4398            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4399                // Already generates the external package name
4400                return generateApplicationInfoFromSettingsLPw(packageName,
4401                        flags, filterCallingUid, userId);
4402            }
4403        }
4404        return null;
4405    }
4406
4407    private String normalizePackageNameLPr(String packageName) {
4408        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4409        return normalizedPackageName != null ? normalizedPackageName : packageName;
4410    }
4411
4412    @Override
4413    public void deletePreloadsFileCache() {
4414        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4415            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4416        }
4417        File dir = Environment.getDataPreloadsFileCacheDirectory();
4418        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4419        FileUtils.deleteContents(dir);
4420    }
4421
4422    @Override
4423    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4424            final int storageFlags, final IPackageDataObserver observer) {
4425        mContext.enforceCallingOrSelfPermission(
4426                android.Manifest.permission.CLEAR_APP_CACHE, null);
4427        mHandler.post(() -> {
4428            boolean success = false;
4429            try {
4430                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4431                success = true;
4432            } catch (IOException e) {
4433                Slog.w(TAG, e);
4434            }
4435            if (observer != null) {
4436                try {
4437                    observer.onRemoveCompleted(null, success);
4438                } catch (RemoteException e) {
4439                    Slog.w(TAG, e);
4440                }
4441            }
4442        });
4443    }
4444
4445    @Override
4446    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4447            final int storageFlags, final IntentSender pi) {
4448        mContext.enforceCallingOrSelfPermission(
4449                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4450        mHandler.post(() -> {
4451            boolean success = false;
4452            try {
4453                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4454                success = true;
4455            } catch (IOException e) {
4456                Slog.w(TAG, e);
4457            }
4458            if (pi != null) {
4459                try {
4460                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4461                } catch (SendIntentException e) {
4462                    Slog.w(TAG, e);
4463                }
4464            }
4465        });
4466    }
4467
4468    /**
4469     * Blocking call to clear various types of cached data across the system
4470     * until the requested bytes are available.
4471     */
4472    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4473        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4474        final File file = storage.findPathForUuid(volumeUuid);
4475        if (file.getUsableSpace() >= bytes) return;
4476
4477        if (ENABLE_FREE_CACHE_V2) {
4478            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4479                    volumeUuid);
4480            final boolean aggressive = (storageFlags
4481                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4482            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4483
4484            // 1. Pre-flight to determine if we have any chance to succeed
4485            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4486            if (internalVolume && (aggressive || SystemProperties
4487                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4488                deletePreloadsFileCache();
4489                if (file.getUsableSpace() >= bytes) return;
4490            }
4491
4492            // 3. Consider parsed APK data (aggressive only)
4493            if (internalVolume && aggressive) {
4494                FileUtils.deleteContents(mCacheDir);
4495                if (file.getUsableSpace() >= bytes) return;
4496            }
4497
4498            // 4. Consider cached app data (above quotas)
4499            try {
4500                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4501                        Installer.FLAG_FREE_CACHE_V2);
4502            } catch (InstallerException ignored) {
4503            }
4504            if (file.getUsableSpace() >= bytes) return;
4505
4506            // 5. Consider shared libraries with refcount=0 and age>min cache period
4507            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4508                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4509                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4510                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4511                return;
4512            }
4513
4514            // 6. Consider dexopt output (aggressive only)
4515            // TODO: Implement
4516
4517            // 7. Consider installed instant apps unused longer than min cache period
4518            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4519                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4520                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4521                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4522                return;
4523            }
4524
4525            // 8. Consider cached app data (below quotas)
4526            try {
4527                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4528                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4529            } catch (InstallerException ignored) {
4530            }
4531            if (file.getUsableSpace() >= bytes) return;
4532
4533            // 9. Consider DropBox entries
4534            // TODO: Implement
4535
4536            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4537            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4538                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4539                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4540                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4541                return;
4542            }
4543        } else {
4544            try {
4545                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4546            } catch (InstallerException ignored) {
4547            }
4548            if (file.getUsableSpace() >= bytes) return;
4549        }
4550
4551        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4552    }
4553
4554    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4555            throws IOException {
4556        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4557        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4558
4559        List<VersionedPackage> packagesToDelete = null;
4560        final long now = System.currentTimeMillis();
4561
4562        synchronized (mPackages) {
4563            final int[] allUsers = sUserManager.getUserIds();
4564            final int libCount = mSharedLibraries.size();
4565            for (int i = 0; i < libCount; i++) {
4566                final LongSparseArray<SharedLibraryEntry> versionedLib
4567                        = mSharedLibraries.valueAt(i);
4568                if (versionedLib == null) {
4569                    continue;
4570                }
4571                final int versionCount = versionedLib.size();
4572                for (int j = 0; j < versionCount; j++) {
4573                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4574                    // Skip packages that are not static shared libs.
4575                    if (!libInfo.isStatic()) {
4576                        break;
4577                    }
4578                    // Important: We skip static shared libs used for some user since
4579                    // in such a case we need to keep the APK on the device. The check for
4580                    // a lib being used for any user is performed by the uninstall call.
4581                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4582                    // Resolve the package name - we use synthetic package names internally
4583                    final String internalPackageName = resolveInternalPackageNameLPr(
4584                            declaringPackage.getPackageName(),
4585                            declaringPackage.getLongVersionCode());
4586                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4587                    // Skip unused static shared libs cached less than the min period
4588                    // to prevent pruning a lib needed by a subsequently installed package.
4589                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4590                        continue;
4591                    }
4592                    if (packagesToDelete == null) {
4593                        packagesToDelete = new ArrayList<>();
4594                    }
4595                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4596                            declaringPackage.getLongVersionCode()));
4597                }
4598            }
4599        }
4600
4601        if (packagesToDelete != null) {
4602            final int packageCount = packagesToDelete.size();
4603            for (int i = 0; i < packageCount; i++) {
4604                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4605                // Delete the package synchronously (will fail of the lib used for any user).
4606                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4607                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4608                                == PackageManager.DELETE_SUCCEEDED) {
4609                    if (volume.getUsableSpace() >= neededSpace) {
4610                        return true;
4611                    }
4612                }
4613            }
4614        }
4615
4616        return false;
4617    }
4618
4619    /**
4620     * Update given flags based on encryption status of current user.
4621     */
4622    private int updateFlags(int flags, int userId) {
4623        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4624                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4625            // Caller expressed an explicit opinion about what encryption
4626            // aware/unaware components they want to see, so fall through and
4627            // give them what they want
4628        } else {
4629            // Caller expressed no opinion, so match based on user state
4630            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4631                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4632            } else {
4633                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4634            }
4635        }
4636        return flags;
4637    }
4638
4639    private UserManagerInternal getUserManagerInternal() {
4640        if (mUserManagerInternal == null) {
4641            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4642        }
4643        return mUserManagerInternal;
4644    }
4645
4646    private ActivityManagerInternal getActivityManagerInternal() {
4647        if (mActivityManagerInternal == null) {
4648            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4649        }
4650        return mActivityManagerInternal;
4651    }
4652
4653
4654    private DeviceIdleController.LocalService getDeviceIdleController() {
4655        if (mDeviceIdleController == null) {
4656            mDeviceIdleController =
4657                    LocalServices.getService(DeviceIdleController.LocalService.class);
4658        }
4659        return mDeviceIdleController;
4660    }
4661
4662    /**
4663     * Update given flags when being used to request {@link PackageInfo}.
4664     */
4665    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4666        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4667        boolean triaged = true;
4668        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4669                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4670            // Caller is asking for component details, so they'd better be
4671            // asking for specific encryption matching behavior, or be triaged
4672            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4673                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4674                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4675                triaged = false;
4676            }
4677        }
4678        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4679                | PackageManager.MATCH_SYSTEM_ONLY
4680                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4681            triaged = false;
4682        }
4683        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4684            mPermissionManager.enforceCrossUserPermission(
4685                    Binder.getCallingUid(), userId, false, false,
4686                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4687                    + Debug.getCallers(5));
4688        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4689                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4690            // If the caller wants all packages and has a restricted profile associated with it,
4691            // then match all users. This is to make sure that launchers that need to access work
4692            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4693            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4694            flags |= PackageManager.MATCH_ANY_USER;
4695        }
4696        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4697            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4698                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4699        }
4700        return updateFlags(flags, userId);
4701    }
4702
4703    /**
4704     * Update given flags when being used to request {@link ApplicationInfo}.
4705     */
4706    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4707        return updateFlagsForPackage(flags, userId, cookie);
4708    }
4709
4710    /**
4711     * Update given flags when being used to request {@link ComponentInfo}.
4712     */
4713    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4714        if (cookie instanceof Intent) {
4715            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4716                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4717            }
4718        }
4719
4720        boolean triaged = true;
4721        // Caller is asking for component details, so they'd better be
4722        // asking for specific encryption matching behavior, or be triaged
4723        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4724                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4725                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4726            triaged = false;
4727        }
4728        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4729            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4730                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4731        }
4732
4733        return updateFlags(flags, userId);
4734    }
4735
4736    /**
4737     * Update given intent when being used to request {@link ResolveInfo}.
4738     */
4739    private Intent updateIntentForResolve(Intent intent) {
4740        if (intent.getSelector() != null) {
4741            intent = intent.getSelector();
4742        }
4743        if (DEBUG_PREFERRED) {
4744            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4745        }
4746        return intent;
4747    }
4748
4749    /**
4750     * Update given flags when being used to request {@link ResolveInfo}.
4751     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4752     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4753     * flag set. However, this flag is only honoured in three circumstances:
4754     * <ul>
4755     * <li>when called from a system process</li>
4756     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4757     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4758     * action and a {@code android.intent.category.BROWSABLE} category</li>
4759     * </ul>
4760     */
4761    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4762        return updateFlagsForResolve(flags, userId, intent, callingUid,
4763                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4764    }
4765    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4766            boolean wantInstantApps) {
4767        return updateFlagsForResolve(flags, userId, intent, callingUid,
4768                wantInstantApps, false /*onlyExposedExplicitly*/);
4769    }
4770    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4771            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4772        // Safe mode means we shouldn't match any third-party components
4773        if (mSafeMode) {
4774            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4775        }
4776        if (getInstantAppPackageName(callingUid) != null) {
4777            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4778            if (onlyExposedExplicitly) {
4779                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4780            }
4781            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4782            flags |= PackageManager.MATCH_INSTANT;
4783        } else {
4784            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4785            final boolean allowMatchInstant = wantInstantApps
4786                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4787            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4788                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4789            if (!allowMatchInstant) {
4790                flags &= ~PackageManager.MATCH_INSTANT;
4791            }
4792        }
4793        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4794    }
4795
4796    @Override
4797    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4798        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4799    }
4800
4801    /**
4802     * Important: The provided filterCallingUid is used exclusively to filter out activities
4803     * that can be seen based on user state. It's typically the original caller uid prior
4804     * to clearing. Because it can only be provided by trusted code, it's value can be
4805     * trusted and will be used as-is; unlike userId which will be validated by this method.
4806     */
4807    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4808            int filterCallingUid, int userId) {
4809        if (!sUserManager.exists(userId)) return null;
4810        flags = updateFlagsForComponent(flags, userId, component);
4811
4812        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4813            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4814                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4815        }
4816
4817        synchronized (mPackages) {
4818            PackageParser.Activity a = mActivities.mActivities.get(component);
4819
4820            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4821            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4822                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4823                if (ps == null) return null;
4824                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4825                    return null;
4826                }
4827                return PackageParser.generateActivityInfo(
4828                        a, flags, ps.readUserState(userId), userId);
4829            }
4830            if (mResolveComponentName.equals(component)) {
4831                return PackageParser.generateActivityInfo(
4832                        mResolveActivity, flags, new PackageUserState(), userId);
4833            }
4834        }
4835        return null;
4836    }
4837
4838    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4839        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4840            return false;
4841        }
4842        final long token = Binder.clearCallingIdentity();
4843        try {
4844            final int callingUserId = UserHandle.getUserId(callingUid);
4845            if (ActivityManager.getCurrentUser() != callingUserId) {
4846                return false;
4847            }
4848            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4849        } finally {
4850            Binder.restoreCallingIdentity(token);
4851        }
4852    }
4853
4854    @Override
4855    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4856            String resolvedType) {
4857        synchronized (mPackages) {
4858            if (component.equals(mResolveComponentName)) {
4859                // The resolver supports EVERYTHING!
4860                return true;
4861            }
4862            final int callingUid = Binder.getCallingUid();
4863            final int callingUserId = UserHandle.getUserId(callingUid);
4864            PackageParser.Activity a = mActivities.mActivities.get(component);
4865            if (a == null) {
4866                return false;
4867            }
4868            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4869            if (ps == null) {
4870                return false;
4871            }
4872            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4873                return false;
4874            }
4875            for (int i=0; i<a.intents.size(); i++) {
4876                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4877                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4878                    return true;
4879                }
4880            }
4881            return false;
4882        }
4883    }
4884
4885    @Override
4886    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4887        if (!sUserManager.exists(userId)) return null;
4888        final int callingUid = Binder.getCallingUid();
4889        flags = updateFlagsForComponent(flags, userId, component);
4890        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4891                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4892        synchronized (mPackages) {
4893            PackageParser.Activity a = mReceivers.mActivities.get(component);
4894            if (DEBUG_PACKAGE_INFO) Log.v(
4895                TAG, "getReceiverInfo " + component + ": " + a);
4896            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4897                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4898                if (ps == null) return null;
4899                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4900                    return null;
4901                }
4902                return PackageParser.generateActivityInfo(
4903                        a, flags, ps.readUserState(userId), userId);
4904            }
4905        }
4906        return null;
4907    }
4908
4909    @Override
4910    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4911            int flags, int userId) {
4912        if (!sUserManager.exists(userId)) return null;
4913        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4914        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4915            return null;
4916        }
4917
4918        flags = updateFlagsForPackage(flags, userId, null);
4919
4920        final boolean canSeeStaticLibraries =
4921                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4922                        == PERMISSION_GRANTED
4923                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4924                        == PERMISSION_GRANTED
4925                || canRequestPackageInstallsInternal(packageName,
4926                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4927                        false  /* throwIfPermNotDeclared*/)
4928                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4929                        == PERMISSION_GRANTED;
4930
4931        synchronized (mPackages) {
4932            List<SharedLibraryInfo> result = null;
4933
4934            final int libCount = mSharedLibraries.size();
4935            for (int i = 0; i < libCount; i++) {
4936                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4937                if (versionedLib == null) {
4938                    continue;
4939                }
4940
4941                final int versionCount = versionedLib.size();
4942                for (int j = 0; j < versionCount; j++) {
4943                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4944                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4945                        break;
4946                    }
4947                    final long identity = Binder.clearCallingIdentity();
4948                    try {
4949                        PackageInfo packageInfo = getPackageInfoVersioned(
4950                                libInfo.getDeclaringPackage(), flags
4951                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4952                        if (packageInfo == null) {
4953                            continue;
4954                        }
4955                    } finally {
4956                        Binder.restoreCallingIdentity(identity);
4957                    }
4958
4959                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4960                            libInfo.getLongVersion(), libInfo.getType(),
4961                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4962                            flags, userId));
4963
4964                    if (result == null) {
4965                        result = new ArrayList<>();
4966                    }
4967                    result.add(resLibInfo);
4968                }
4969            }
4970
4971            return result != null ? new ParceledListSlice<>(result) : null;
4972        }
4973    }
4974
4975    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4976            SharedLibraryInfo libInfo, int flags, int userId) {
4977        List<VersionedPackage> versionedPackages = null;
4978        final int packageCount = mSettings.mPackages.size();
4979        for (int i = 0; i < packageCount; i++) {
4980            PackageSetting ps = mSettings.mPackages.valueAt(i);
4981
4982            if (ps == null) {
4983                continue;
4984            }
4985
4986            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4987                continue;
4988            }
4989
4990            final String libName = libInfo.getName();
4991            if (libInfo.isStatic()) {
4992                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4993                if (libIdx < 0) {
4994                    continue;
4995                }
4996                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4997                    continue;
4998                }
4999                if (versionedPackages == null) {
5000                    versionedPackages = new ArrayList<>();
5001                }
5002                // If the dependent is a static shared lib, use the public package name
5003                String dependentPackageName = ps.name;
5004                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5005                    dependentPackageName = ps.pkg.manifestPackageName;
5006                }
5007                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5008            } else if (ps.pkg != null) {
5009                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5010                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5011                    if (versionedPackages == null) {
5012                        versionedPackages = new ArrayList<>();
5013                    }
5014                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5015                }
5016            }
5017        }
5018
5019        return versionedPackages;
5020    }
5021
5022    @Override
5023    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5024        if (!sUserManager.exists(userId)) return null;
5025        final int callingUid = Binder.getCallingUid();
5026        flags = updateFlagsForComponent(flags, userId, component);
5027        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5028                false /* requireFullPermission */, false /* checkShell */, "get service info");
5029        synchronized (mPackages) {
5030            PackageParser.Service s = mServices.mServices.get(component);
5031            if (DEBUG_PACKAGE_INFO) Log.v(
5032                TAG, "getServiceInfo " + component + ": " + s);
5033            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5034                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5035                if (ps == null) return null;
5036                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5037                    return null;
5038                }
5039                return PackageParser.generateServiceInfo(
5040                        s, flags, ps.readUserState(userId), userId);
5041            }
5042        }
5043        return null;
5044    }
5045
5046    @Override
5047    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5048        if (!sUserManager.exists(userId)) return null;
5049        final int callingUid = Binder.getCallingUid();
5050        flags = updateFlagsForComponent(flags, userId, component);
5051        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5052                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5053        synchronized (mPackages) {
5054            PackageParser.Provider p = mProviders.mProviders.get(component);
5055            if (DEBUG_PACKAGE_INFO) Log.v(
5056                TAG, "getProviderInfo " + component + ": " + p);
5057            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5058                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5059                if (ps == null) return null;
5060                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5061                    return null;
5062                }
5063                return PackageParser.generateProviderInfo(
5064                        p, flags, ps.readUserState(userId), userId);
5065            }
5066        }
5067        return null;
5068    }
5069
5070    @Override
5071    public String[] getSystemSharedLibraryNames() {
5072        // allow instant applications
5073        synchronized (mPackages) {
5074            Set<String> libs = null;
5075            final int libCount = mSharedLibraries.size();
5076            for (int i = 0; i < libCount; i++) {
5077                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5078                if (versionedLib == null) {
5079                    continue;
5080                }
5081                final int versionCount = versionedLib.size();
5082                for (int j = 0; j < versionCount; j++) {
5083                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5084                    if (!libEntry.info.isStatic()) {
5085                        if (libs == null) {
5086                            libs = new ArraySet<>();
5087                        }
5088                        libs.add(libEntry.info.getName());
5089                        break;
5090                    }
5091                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5092                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5093                            UserHandle.getUserId(Binder.getCallingUid()),
5094                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5095                        if (libs == null) {
5096                            libs = new ArraySet<>();
5097                        }
5098                        libs.add(libEntry.info.getName());
5099                        break;
5100                    }
5101                }
5102            }
5103
5104            if (libs != null) {
5105                String[] libsArray = new String[libs.size()];
5106                libs.toArray(libsArray);
5107                return libsArray;
5108            }
5109
5110            return null;
5111        }
5112    }
5113
5114    @Override
5115    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5116        // allow instant applications
5117        synchronized (mPackages) {
5118            return mServicesSystemSharedLibraryPackageName;
5119        }
5120    }
5121
5122    @Override
5123    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5124        // allow instant applications
5125        synchronized (mPackages) {
5126            return mSharedSystemSharedLibraryPackageName;
5127        }
5128    }
5129
5130    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5131        for (int i = userList.length - 1; i >= 0; --i) {
5132            final int userId = userList[i];
5133            // don't add instant app to the list of updates
5134            if (pkgSetting.getInstantApp(userId)) {
5135                continue;
5136            }
5137            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5138            if (changedPackages == null) {
5139                changedPackages = new SparseArray<>();
5140                mChangedPackages.put(userId, changedPackages);
5141            }
5142            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5143            if (sequenceNumbers == null) {
5144                sequenceNumbers = new HashMap<>();
5145                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5146            }
5147            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5148            if (sequenceNumber != null) {
5149                changedPackages.remove(sequenceNumber);
5150            }
5151            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5152            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5153        }
5154        mChangedPackagesSequenceNumber++;
5155    }
5156
5157    @Override
5158    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5159        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5160            return null;
5161        }
5162        synchronized (mPackages) {
5163            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5164                return null;
5165            }
5166            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5167            if (changedPackages == null) {
5168                return null;
5169            }
5170            final List<String> packageNames =
5171                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5172            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5173                final String packageName = changedPackages.get(i);
5174                if (packageName != null) {
5175                    packageNames.add(packageName);
5176                }
5177            }
5178            return packageNames.isEmpty()
5179                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5180        }
5181    }
5182
5183    @Override
5184    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5185        // allow instant applications
5186        ArrayList<FeatureInfo> res;
5187        synchronized (mAvailableFeatures) {
5188            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5189            res.addAll(mAvailableFeatures.values());
5190        }
5191        final FeatureInfo fi = new FeatureInfo();
5192        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5193                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5194        res.add(fi);
5195
5196        return new ParceledListSlice<>(res);
5197    }
5198
5199    @Override
5200    public boolean hasSystemFeature(String name, int version) {
5201        // allow instant applications
5202        synchronized (mAvailableFeatures) {
5203            final FeatureInfo feat = mAvailableFeatures.get(name);
5204            if (feat == null) {
5205                return false;
5206            } else {
5207                return feat.version >= version;
5208            }
5209        }
5210    }
5211
5212    @Override
5213    public int checkPermission(String permName, String pkgName, int userId) {
5214        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5215    }
5216
5217    @Override
5218    public int checkUidPermission(String permName, int uid) {
5219        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5220    }
5221
5222    @Override
5223    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5224        if (UserHandle.getCallingUserId() != userId) {
5225            mContext.enforceCallingPermission(
5226                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5227                    "isPermissionRevokedByPolicy for user " + userId);
5228        }
5229
5230        if (checkPermission(permission, packageName, userId)
5231                == PackageManager.PERMISSION_GRANTED) {
5232            return false;
5233        }
5234
5235        final int callingUid = Binder.getCallingUid();
5236        if (getInstantAppPackageName(callingUid) != null) {
5237            if (!isCallerSameApp(packageName, callingUid)) {
5238                return false;
5239            }
5240        } else {
5241            if (isInstantApp(packageName, userId)) {
5242                return false;
5243            }
5244        }
5245
5246        final long identity = Binder.clearCallingIdentity();
5247        try {
5248            final int flags = getPermissionFlags(permission, packageName, userId);
5249            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5250        } finally {
5251            Binder.restoreCallingIdentity(identity);
5252        }
5253    }
5254
5255    @Override
5256    public String getPermissionControllerPackageName() {
5257        synchronized (mPackages) {
5258            return mRequiredInstallerPackage;
5259        }
5260    }
5261
5262    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5263        return mPermissionManager.addDynamicPermission(
5264                info, async, getCallingUid(), new PermissionCallback() {
5265                    @Override
5266                    public void onPermissionChanged() {
5267                        if (!async) {
5268                            mSettings.writeLPr();
5269                        } else {
5270                            scheduleWriteSettingsLocked();
5271                        }
5272                    }
5273                });
5274    }
5275
5276    @Override
5277    public boolean addPermission(PermissionInfo info) {
5278        synchronized (mPackages) {
5279            return addDynamicPermission(info, false);
5280        }
5281    }
5282
5283    @Override
5284    public boolean addPermissionAsync(PermissionInfo info) {
5285        synchronized (mPackages) {
5286            return addDynamicPermission(info, true);
5287        }
5288    }
5289
5290    @Override
5291    public void removePermission(String permName) {
5292        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5293    }
5294
5295    @Override
5296    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5297        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5298                getCallingUid(), userId, mPermissionCallback);
5299    }
5300
5301    @Override
5302    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5303        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5304                getCallingUid(), userId, mPermissionCallback);
5305    }
5306
5307    @Override
5308    public void resetRuntimePermissions() {
5309        mContext.enforceCallingOrSelfPermission(
5310                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5311                "revokeRuntimePermission");
5312
5313        int callingUid = Binder.getCallingUid();
5314        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5315            mContext.enforceCallingOrSelfPermission(
5316                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5317                    "resetRuntimePermissions");
5318        }
5319
5320        synchronized (mPackages) {
5321            mPermissionManager.updateAllPermissions(
5322                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5323                    mPermissionCallback);
5324            for (int userId : UserManagerService.getInstance().getUserIds()) {
5325                final int packageCount = mPackages.size();
5326                for (int i = 0; i < packageCount; i++) {
5327                    PackageParser.Package pkg = mPackages.valueAt(i);
5328                    if (!(pkg.mExtras instanceof PackageSetting)) {
5329                        continue;
5330                    }
5331                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5332                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5333                }
5334            }
5335        }
5336    }
5337
5338    @Override
5339    public int getPermissionFlags(String permName, String packageName, int userId) {
5340        return mPermissionManager.getPermissionFlags(
5341                permName, packageName, getCallingUid(), userId);
5342    }
5343
5344    @Override
5345    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5346            int flagValues, int userId) {
5347        mPermissionManager.updatePermissionFlags(
5348                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5349                mPermissionCallback);
5350    }
5351
5352    /**
5353     * Update the permission flags for all packages and runtime permissions of a user in order
5354     * to allow device or profile owner to remove POLICY_FIXED.
5355     */
5356    @Override
5357    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5358        synchronized (mPackages) {
5359            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5360                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5361                    mPermissionCallback);
5362            if (changed) {
5363                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5364            }
5365        }
5366    }
5367
5368    @Override
5369    public boolean shouldShowRequestPermissionRationale(String permissionName,
5370            String packageName, int userId) {
5371        if (UserHandle.getCallingUserId() != userId) {
5372            mContext.enforceCallingPermission(
5373                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5374                    "canShowRequestPermissionRationale for user " + userId);
5375        }
5376
5377        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5378        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5379            return false;
5380        }
5381
5382        if (checkPermission(permissionName, packageName, userId)
5383                == PackageManager.PERMISSION_GRANTED) {
5384            return false;
5385        }
5386
5387        final int flags;
5388
5389        final long identity = Binder.clearCallingIdentity();
5390        try {
5391            flags = getPermissionFlags(permissionName,
5392                    packageName, userId);
5393        } finally {
5394            Binder.restoreCallingIdentity(identity);
5395        }
5396
5397        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5398                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5399                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5400
5401        if ((flags & fixedFlags) != 0) {
5402            return false;
5403        }
5404
5405        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5406    }
5407
5408    @Override
5409    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5410        mContext.enforceCallingOrSelfPermission(
5411                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5412                "addOnPermissionsChangeListener");
5413
5414        synchronized (mPackages) {
5415            mOnPermissionChangeListeners.addListenerLocked(listener);
5416        }
5417    }
5418
5419    @Override
5420    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5421        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5422            throw new SecurityException("Instant applications don't have access to this method");
5423        }
5424        synchronized (mPackages) {
5425            mOnPermissionChangeListeners.removeListenerLocked(listener);
5426        }
5427    }
5428
5429    @Override
5430    public boolean isProtectedBroadcast(String actionName) {
5431        // allow instant applications
5432        synchronized (mProtectedBroadcasts) {
5433            if (mProtectedBroadcasts.contains(actionName)) {
5434                return true;
5435            } else if (actionName != null) {
5436                // TODO: remove these terrible hacks
5437                if (actionName.startsWith("android.net.netmon.lingerExpired")
5438                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5439                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5440                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5441                    return true;
5442                }
5443            }
5444        }
5445        return false;
5446    }
5447
5448    @Override
5449    public int checkSignatures(String pkg1, String pkg2) {
5450        synchronized (mPackages) {
5451            final PackageParser.Package p1 = mPackages.get(pkg1);
5452            final PackageParser.Package p2 = mPackages.get(pkg2);
5453            if (p1 == null || p1.mExtras == null
5454                    || p2 == null || p2.mExtras == null) {
5455                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5456            }
5457            final int callingUid = Binder.getCallingUid();
5458            final int callingUserId = UserHandle.getUserId(callingUid);
5459            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5460            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5461            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5462                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5463                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5464            }
5465            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5466        }
5467    }
5468
5469    @Override
5470    public int checkUidSignatures(int uid1, int uid2) {
5471        final int callingUid = Binder.getCallingUid();
5472        final int callingUserId = UserHandle.getUserId(callingUid);
5473        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5474        // Map to base uids.
5475        uid1 = UserHandle.getAppId(uid1);
5476        uid2 = UserHandle.getAppId(uid2);
5477        // reader
5478        synchronized (mPackages) {
5479            Signature[] s1;
5480            Signature[] s2;
5481            Object obj = mSettings.getUserIdLPr(uid1);
5482            if (obj != null) {
5483                if (obj instanceof SharedUserSetting) {
5484                    if (isCallerInstantApp) {
5485                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5486                    }
5487                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5488                } else if (obj instanceof PackageSetting) {
5489                    final PackageSetting ps = (PackageSetting) obj;
5490                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5491                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5492                    }
5493                    s1 = ps.signatures.mSigningDetails.signatures;
5494                } else {
5495                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5496                }
5497            } else {
5498                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5499            }
5500            obj = mSettings.getUserIdLPr(uid2);
5501            if (obj != null) {
5502                if (obj instanceof SharedUserSetting) {
5503                    if (isCallerInstantApp) {
5504                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5505                    }
5506                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5507                } else if (obj instanceof PackageSetting) {
5508                    final PackageSetting ps = (PackageSetting) obj;
5509                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5510                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5511                    }
5512                    s2 = ps.signatures.mSigningDetails.signatures;
5513                } else {
5514                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5515                }
5516            } else {
5517                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5518            }
5519            return compareSignatures(s1, s2);
5520        }
5521    }
5522
5523    @Override
5524    public boolean hasSigningCertificate(
5525            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5526
5527        synchronized (mPackages) {
5528            final PackageParser.Package p = mPackages.get(packageName);
5529            if (p == null || p.mExtras == null) {
5530                return false;
5531            }
5532            final int callingUid = Binder.getCallingUid();
5533            final int callingUserId = UserHandle.getUserId(callingUid);
5534            final PackageSetting ps = (PackageSetting) p.mExtras;
5535            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5536                return false;
5537            }
5538            switch (type) {
5539                case CERT_INPUT_RAW_X509:
5540                    return p.mSigningDetails.hasCertificate(certificate);
5541                case CERT_INPUT_SHA256:
5542                    return p.mSigningDetails.hasSha256Certificate(certificate);
5543                default:
5544                    return false;
5545            }
5546        }
5547    }
5548
5549    @Override
5550    public boolean hasUidSigningCertificate(
5551            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5552        final int callingUid = Binder.getCallingUid();
5553        final int callingUserId = UserHandle.getUserId(callingUid);
5554        // Map to base uids.
5555        uid = UserHandle.getAppId(uid);
5556        // reader
5557        synchronized (mPackages) {
5558            final PackageParser.SigningDetails signingDetails;
5559            final Object obj = mSettings.getUserIdLPr(uid);
5560            if (obj != null) {
5561                if (obj instanceof SharedUserSetting) {
5562                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5563                    if (isCallerInstantApp) {
5564                        return false;
5565                    }
5566                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5567                } else if (obj instanceof PackageSetting) {
5568                    final PackageSetting ps = (PackageSetting) obj;
5569                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5570                        return false;
5571                    }
5572                    signingDetails = ps.signatures.mSigningDetails;
5573                } else {
5574                    return false;
5575                }
5576            } else {
5577                return false;
5578            }
5579            switch (type) {
5580                case CERT_INPUT_RAW_X509:
5581                    return signingDetails.hasCertificate(certificate);
5582                case CERT_INPUT_SHA256:
5583                    return signingDetails.hasSha256Certificate(certificate);
5584                default:
5585                    return false;
5586            }
5587        }
5588    }
5589
5590    /**
5591     * This method should typically only be used when granting or revoking
5592     * permissions, since the app may immediately restart after this call.
5593     * <p>
5594     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5595     * guard your work against the app being relaunched.
5596     */
5597    private void killUid(int appId, int userId, String reason) {
5598        final long identity = Binder.clearCallingIdentity();
5599        try {
5600            IActivityManager am = ActivityManager.getService();
5601            if (am != null) {
5602                try {
5603                    am.killUid(appId, userId, reason);
5604                } catch (RemoteException e) {
5605                    /* ignore - same process */
5606                }
5607            }
5608        } finally {
5609            Binder.restoreCallingIdentity(identity);
5610        }
5611    }
5612
5613    /**
5614     * If the database version for this type of package (internal storage or
5615     * external storage) is less than the version where package signatures
5616     * were updated, return true.
5617     */
5618    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5619        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5620        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5621    }
5622
5623    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5624        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5625        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5626    }
5627
5628    @Override
5629    public List<String> getAllPackages() {
5630        final int callingUid = Binder.getCallingUid();
5631        final int callingUserId = UserHandle.getUserId(callingUid);
5632        synchronized (mPackages) {
5633            if (canViewInstantApps(callingUid, callingUserId)) {
5634                return new ArrayList<String>(mPackages.keySet());
5635            }
5636            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5637            final List<String> result = new ArrayList<>();
5638            if (instantAppPkgName != null) {
5639                // caller is an instant application; filter unexposed applications
5640                for (PackageParser.Package pkg : mPackages.values()) {
5641                    if (!pkg.visibleToInstantApps) {
5642                        continue;
5643                    }
5644                    result.add(pkg.packageName);
5645                }
5646            } else {
5647                // caller is a normal application; filter instant applications
5648                for (PackageParser.Package pkg : mPackages.values()) {
5649                    final PackageSetting ps =
5650                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5651                    if (ps != null
5652                            && ps.getInstantApp(callingUserId)
5653                            && !mInstantAppRegistry.isInstantAccessGranted(
5654                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5655                        continue;
5656                    }
5657                    result.add(pkg.packageName);
5658                }
5659            }
5660            return result;
5661        }
5662    }
5663
5664    @Override
5665    public String[] getPackagesForUid(int uid) {
5666        final int callingUid = Binder.getCallingUid();
5667        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5668        final int userId = UserHandle.getUserId(uid);
5669        uid = UserHandle.getAppId(uid);
5670        // reader
5671        synchronized (mPackages) {
5672            Object obj = mSettings.getUserIdLPr(uid);
5673            if (obj instanceof SharedUserSetting) {
5674                if (isCallerInstantApp) {
5675                    return null;
5676                }
5677                final SharedUserSetting sus = (SharedUserSetting) obj;
5678                final int N = sus.packages.size();
5679                String[] res = new String[N];
5680                final Iterator<PackageSetting> it = sus.packages.iterator();
5681                int i = 0;
5682                while (it.hasNext()) {
5683                    PackageSetting ps = it.next();
5684                    if (ps.getInstalled(userId)) {
5685                        res[i++] = ps.name;
5686                    } else {
5687                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5688                    }
5689                }
5690                return res;
5691            } else if (obj instanceof PackageSetting) {
5692                final PackageSetting ps = (PackageSetting) obj;
5693                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5694                    return new String[]{ps.name};
5695                }
5696            }
5697        }
5698        return null;
5699    }
5700
5701    @Override
5702    public String getNameForUid(int uid) {
5703        final int callingUid = Binder.getCallingUid();
5704        if (getInstantAppPackageName(callingUid) != null) {
5705            return null;
5706        }
5707        synchronized (mPackages) {
5708            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5709            if (obj instanceof SharedUserSetting) {
5710                final SharedUserSetting sus = (SharedUserSetting) obj;
5711                return sus.name + ":" + sus.userId;
5712            } else if (obj instanceof PackageSetting) {
5713                final PackageSetting ps = (PackageSetting) obj;
5714                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5715                    return null;
5716                }
5717                return ps.name;
5718            }
5719            return null;
5720        }
5721    }
5722
5723    @Override
5724    public String[] getNamesForUids(int[] uids) {
5725        if (uids == null || uids.length == 0) {
5726            return null;
5727        }
5728        final int callingUid = Binder.getCallingUid();
5729        if (getInstantAppPackageName(callingUid) != null) {
5730            return null;
5731        }
5732        final String[] names = new String[uids.length];
5733        synchronized (mPackages) {
5734            for (int i = uids.length - 1; i >= 0; i--) {
5735                final int uid = uids[i];
5736                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5737                if (obj instanceof SharedUserSetting) {
5738                    final SharedUserSetting sus = (SharedUserSetting) obj;
5739                    names[i] = "shared:" + sus.name;
5740                } else if (obj instanceof PackageSetting) {
5741                    final PackageSetting ps = (PackageSetting) obj;
5742                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5743                        names[i] = null;
5744                    } else {
5745                        names[i] = ps.name;
5746                    }
5747                } else {
5748                    names[i] = null;
5749                }
5750            }
5751        }
5752        return names;
5753    }
5754
5755    @Override
5756    public int getUidForSharedUser(String sharedUserName) {
5757        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5758            return -1;
5759        }
5760        if (sharedUserName == null) {
5761            return -1;
5762        }
5763        // reader
5764        synchronized (mPackages) {
5765            SharedUserSetting suid;
5766            try {
5767                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5768                if (suid != null) {
5769                    return suid.userId;
5770                }
5771            } catch (PackageManagerException ignore) {
5772                // can't happen, but, still need to catch it
5773            }
5774            return -1;
5775        }
5776    }
5777
5778    @Override
5779    public int getFlagsForUid(int uid) {
5780        final int callingUid = Binder.getCallingUid();
5781        if (getInstantAppPackageName(callingUid) != null) {
5782            return 0;
5783        }
5784        synchronized (mPackages) {
5785            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5786            if (obj instanceof SharedUserSetting) {
5787                final SharedUserSetting sus = (SharedUserSetting) obj;
5788                return sus.pkgFlags;
5789            } else if (obj instanceof PackageSetting) {
5790                final PackageSetting ps = (PackageSetting) obj;
5791                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5792                    return 0;
5793                }
5794                return ps.pkgFlags;
5795            }
5796        }
5797        return 0;
5798    }
5799
5800    @Override
5801    public int getPrivateFlagsForUid(int uid) {
5802        final int callingUid = Binder.getCallingUid();
5803        if (getInstantAppPackageName(callingUid) != null) {
5804            return 0;
5805        }
5806        synchronized (mPackages) {
5807            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5808            if (obj instanceof SharedUserSetting) {
5809                final SharedUserSetting sus = (SharedUserSetting) obj;
5810                return sus.pkgPrivateFlags;
5811            } else if (obj instanceof PackageSetting) {
5812                final PackageSetting ps = (PackageSetting) obj;
5813                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5814                    return 0;
5815                }
5816                return ps.pkgPrivateFlags;
5817            }
5818        }
5819        return 0;
5820    }
5821
5822    @Override
5823    public boolean isUidPrivileged(int uid) {
5824        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5825            return false;
5826        }
5827        uid = UserHandle.getAppId(uid);
5828        // reader
5829        synchronized (mPackages) {
5830            Object obj = mSettings.getUserIdLPr(uid);
5831            if (obj instanceof SharedUserSetting) {
5832                final SharedUserSetting sus = (SharedUserSetting) obj;
5833                final Iterator<PackageSetting> it = sus.packages.iterator();
5834                while (it.hasNext()) {
5835                    if (it.next().isPrivileged()) {
5836                        return true;
5837                    }
5838                }
5839            } else if (obj instanceof PackageSetting) {
5840                final PackageSetting ps = (PackageSetting) obj;
5841                return ps.isPrivileged();
5842            }
5843        }
5844        return false;
5845    }
5846
5847    @Override
5848    public String[] getAppOpPermissionPackages(String permName) {
5849        return mPermissionManager.getAppOpPermissionPackages(permName);
5850    }
5851
5852    @Override
5853    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5854            int flags, int userId) {
5855        return resolveIntentInternal(
5856                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5857    }
5858
5859    /**
5860     * Normally instant apps can only be resolved when they're visible to the caller.
5861     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5862     * since we need to allow the system to start any installed application.
5863     */
5864    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5865            int flags, int userId, boolean resolveForStart) {
5866        try {
5867            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5868
5869            if (!sUserManager.exists(userId)) return null;
5870            final int callingUid = Binder.getCallingUid();
5871            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5872            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5873                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5874
5875            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5876            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5877                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5878            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5879
5880            final ResolveInfo bestChoice =
5881                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5882            return bestChoice;
5883        } finally {
5884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5885        }
5886    }
5887
5888    @Override
5889    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5890        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5891            throw new SecurityException(
5892                    "findPersistentPreferredActivity can only be run by the system");
5893        }
5894        if (!sUserManager.exists(userId)) {
5895            return null;
5896        }
5897        final int callingUid = Binder.getCallingUid();
5898        intent = updateIntentForResolve(intent);
5899        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5900        final int flags = updateFlagsForResolve(
5901                0, userId, intent, callingUid, false /*includeInstantApps*/);
5902        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5903                userId);
5904        synchronized (mPackages) {
5905            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5906                    userId);
5907        }
5908    }
5909
5910    @Override
5911    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5912            IntentFilter filter, int match, ComponentName activity) {
5913        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5914            return;
5915        }
5916        final int userId = UserHandle.getCallingUserId();
5917        if (DEBUG_PREFERRED) {
5918            Log.v(TAG, "setLastChosenActivity intent=" + intent
5919                + " resolvedType=" + resolvedType
5920                + " flags=" + flags
5921                + " filter=" + filter
5922                + " match=" + match
5923                + " activity=" + activity);
5924            filter.dump(new PrintStreamPrinter(System.out), "    ");
5925        }
5926        intent.setComponent(null);
5927        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5928                userId);
5929        // Find any earlier preferred or last chosen entries and nuke them
5930        findPreferredActivity(intent, resolvedType,
5931                flags, query, 0, false, true, false, userId);
5932        // Add the new activity as the last chosen for this filter
5933        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5934                "Setting last chosen");
5935    }
5936
5937    @Override
5938    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5939        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5940            return null;
5941        }
5942        final int userId = UserHandle.getCallingUserId();
5943        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5944        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5945                userId);
5946        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5947                false, false, false, userId);
5948    }
5949
5950    /**
5951     * Returns whether or not instant apps have been disabled remotely.
5952     */
5953    private boolean isEphemeralDisabled() {
5954        return mEphemeralAppsDisabled;
5955    }
5956
5957    private boolean isInstantAppAllowed(
5958            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5959            boolean skipPackageCheck) {
5960        if (mInstantAppResolverConnection == null) {
5961            return false;
5962        }
5963        if (mInstantAppInstallerActivity == null) {
5964            return false;
5965        }
5966        if (intent.getComponent() != null) {
5967            return false;
5968        }
5969        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5970            return false;
5971        }
5972        if (!skipPackageCheck && intent.getPackage() != null) {
5973            return false;
5974        }
5975        if (!intent.isWebIntent()) {
5976            // for non web intents, we should not resolve externally if an app already exists to
5977            // handle it or if the caller didn't explicitly request it.
5978            if ((resolvedActivities != null && resolvedActivities.size() != 0)
5979                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
5980                return false;
5981            }
5982        } else if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
5983            return false;
5984        }
5985        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5986        // Or if there's already an ephemeral app installed that handles the action
5987        synchronized (mPackages) {
5988            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5989            for (int n = 0; n < count; n++) {
5990                final ResolveInfo info = resolvedActivities.get(n);
5991                final String packageName = info.activityInfo.packageName;
5992                final PackageSetting ps = mSettings.mPackages.get(packageName);
5993                if (ps != null) {
5994                    // only check domain verification status if the app is not a browser
5995                    if (!info.handleAllWebDataURI) {
5996                        // Try to get the status from User settings first
5997                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5998                        final int status = (int) (packedStatus >> 32);
5999                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6000                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6001                            if (DEBUG_INSTANT) {
6002                                Slog.v(TAG, "DENY instant app;"
6003                                    + " pkg: " + packageName + ", status: " + status);
6004                            }
6005                            return false;
6006                        }
6007                    }
6008                    if (ps.getInstantApp(userId)) {
6009                        if (DEBUG_INSTANT) {
6010                            Slog.v(TAG, "DENY instant app installed;"
6011                                    + " pkg: " + packageName);
6012                        }
6013                        return false;
6014                    }
6015                }
6016            }
6017        }
6018        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6019        return true;
6020    }
6021
6022    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6023            Intent origIntent, String resolvedType, String callingPackage,
6024            Bundle verificationBundle, int userId) {
6025        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6026                new InstantAppRequest(responseObj, origIntent, resolvedType,
6027                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6028        mHandler.sendMessage(msg);
6029    }
6030
6031    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6032            int flags, List<ResolveInfo> query, int userId) {
6033        if (query != null) {
6034            final int N = query.size();
6035            if (N == 1) {
6036                return query.get(0);
6037            } else if (N > 1) {
6038                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6039                // If there is more than one activity with the same priority,
6040                // then let the user decide between them.
6041                ResolveInfo r0 = query.get(0);
6042                ResolveInfo r1 = query.get(1);
6043                if (DEBUG_INTENT_MATCHING || debug) {
6044                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6045                            + r1.activityInfo.name + "=" + r1.priority);
6046                }
6047                // If the first activity has a higher priority, or a different
6048                // default, then it is always desirable to pick it.
6049                if (r0.priority != r1.priority
6050                        || r0.preferredOrder != r1.preferredOrder
6051                        || r0.isDefault != r1.isDefault) {
6052                    return query.get(0);
6053                }
6054                // If we have saved a preference for a preferred activity for
6055                // this Intent, use that.
6056                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6057                        flags, query, r0.priority, true, false, debug, userId);
6058                if (ri != null) {
6059                    return ri;
6060                }
6061                // If we have an ephemeral app, use it
6062                for (int i = 0; i < N; i++) {
6063                    ri = query.get(i);
6064                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6065                        final String packageName = ri.activityInfo.packageName;
6066                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6067                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6068                        final int status = (int)(packedStatus >> 32);
6069                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6070                            return ri;
6071                        }
6072                    }
6073                }
6074                ri = new ResolveInfo(mResolveInfo);
6075                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6076                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6077                // If all of the options come from the same package, show the application's
6078                // label and icon instead of the generic resolver's.
6079                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6080                // and then throw away the ResolveInfo itself, meaning that the caller loses
6081                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6082                // a fallback for this case; we only set the target package's resources on
6083                // the ResolveInfo, not the ActivityInfo.
6084                final String intentPackage = intent.getPackage();
6085                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6086                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6087                    ri.resolvePackageName = intentPackage;
6088                    if (userNeedsBadging(userId)) {
6089                        ri.noResourceId = true;
6090                    } else {
6091                        ri.icon = appi.icon;
6092                    }
6093                    ri.iconResourceId = appi.icon;
6094                    ri.labelRes = appi.labelRes;
6095                }
6096                ri.activityInfo.applicationInfo = new ApplicationInfo(
6097                        ri.activityInfo.applicationInfo);
6098                if (userId != 0) {
6099                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6100                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6101                }
6102                // Make sure that the resolver is displayable in car mode
6103                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6104                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6105                return ri;
6106            }
6107        }
6108        return null;
6109    }
6110
6111    /**
6112     * Return true if the given list is not empty and all of its contents have
6113     * an activityInfo with the given package name.
6114     */
6115    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6116        if (ArrayUtils.isEmpty(list)) {
6117            return false;
6118        }
6119        for (int i = 0, N = list.size(); i < N; i++) {
6120            final ResolveInfo ri = list.get(i);
6121            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6122            if (ai == null || !packageName.equals(ai.packageName)) {
6123                return false;
6124            }
6125        }
6126        return true;
6127    }
6128
6129    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6130            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6131        final int N = query.size();
6132        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6133                .get(userId);
6134        // Get the list of persistent preferred activities that handle the intent
6135        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6136        List<PersistentPreferredActivity> pprefs = ppir != null
6137                ? ppir.queryIntent(intent, resolvedType,
6138                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6139                        userId)
6140                : null;
6141        if (pprefs != null && pprefs.size() > 0) {
6142            final int M = pprefs.size();
6143            for (int i=0; i<M; i++) {
6144                final PersistentPreferredActivity ppa = pprefs.get(i);
6145                if (DEBUG_PREFERRED || debug) {
6146                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6147                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6148                            + "\n  component=" + ppa.mComponent);
6149                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6150                }
6151                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6152                        flags | MATCH_DISABLED_COMPONENTS, userId);
6153                if (DEBUG_PREFERRED || debug) {
6154                    Slog.v(TAG, "Found persistent preferred activity:");
6155                    if (ai != null) {
6156                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6157                    } else {
6158                        Slog.v(TAG, "  null");
6159                    }
6160                }
6161                if (ai == null) {
6162                    // This previously registered persistent preferred activity
6163                    // component is no longer known. Ignore it and do NOT remove it.
6164                    continue;
6165                }
6166                for (int j=0; j<N; j++) {
6167                    final ResolveInfo ri = query.get(j);
6168                    if (!ri.activityInfo.applicationInfo.packageName
6169                            .equals(ai.applicationInfo.packageName)) {
6170                        continue;
6171                    }
6172                    if (!ri.activityInfo.name.equals(ai.name)) {
6173                        continue;
6174                    }
6175                    //  Found a persistent preference that can handle the intent.
6176                    if (DEBUG_PREFERRED || debug) {
6177                        Slog.v(TAG, "Returning persistent preferred activity: " +
6178                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6179                    }
6180                    return ri;
6181                }
6182            }
6183        }
6184        return null;
6185    }
6186
6187    // TODO: handle preferred activities missing while user has amnesia
6188    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6189            List<ResolveInfo> query, int priority, boolean always,
6190            boolean removeMatches, boolean debug, int userId) {
6191        if (!sUserManager.exists(userId)) return null;
6192        final int callingUid = Binder.getCallingUid();
6193        flags = updateFlagsForResolve(
6194                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6195        intent = updateIntentForResolve(intent);
6196        // writer
6197        synchronized (mPackages) {
6198            // Try to find a matching persistent preferred activity.
6199            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6200                    debug, userId);
6201
6202            // If a persistent preferred activity matched, use it.
6203            if (pri != null) {
6204                return pri;
6205            }
6206
6207            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6208            // Get the list of preferred activities that handle the intent
6209            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6210            List<PreferredActivity> prefs = pir != null
6211                    ? pir.queryIntent(intent, resolvedType,
6212                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6213                            userId)
6214                    : null;
6215            if (prefs != null && prefs.size() > 0) {
6216                boolean changed = false;
6217                try {
6218                    // First figure out how good the original match set is.
6219                    // We will only allow preferred activities that came
6220                    // from the same match quality.
6221                    int match = 0;
6222
6223                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6224
6225                    final int N = query.size();
6226                    for (int j=0; j<N; j++) {
6227                        final ResolveInfo ri = query.get(j);
6228                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6229                                + ": 0x" + Integer.toHexString(match));
6230                        if (ri.match > match) {
6231                            match = ri.match;
6232                        }
6233                    }
6234
6235                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6236                            + Integer.toHexString(match));
6237
6238                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6239                    final int M = prefs.size();
6240                    for (int i=0; i<M; i++) {
6241                        final PreferredActivity pa = prefs.get(i);
6242                        if (DEBUG_PREFERRED || debug) {
6243                            Slog.v(TAG, "Checking PreferredActivity ds="
6244                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6245                                    + "\n  component=" + pa.mPref.mComponent);
6246                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6247                        }
6248                        if (pa.mPref.mMatch != match) {
6249                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6250                                    + Integer.toHexString(pa.mPref.mMatch));
6251                            continue;
6252                        }
6253                        // If it's not an "always" type preferred activity and that's what we're
6254                        // looking for, skip it.
6255                        if (always && !pa.mPref.mAlways) {
6256                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6257                            continue;
6258                        }
6259                        final ActivityInfo ai = getActivityInfo(
6260                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6261                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6262                                userId);
6263                        if (DEBUG_PREFERRED || debug) {
6264                            Slog.v(TAG, "Found preferred activity:");
6265                            if (ai != null) {
6266                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6267                            } else {
6268                                Slog.v(TAG, "  null");
6269                            }
6270                        }
6271                        if (ai == null) {
6272                            // This previously registered preferred activity
6273                            // component is no longer known.  Most likely an update
6274                            // to the app was installed and in the new version this
6275                            // component no longer exists.  Clean it up by removing
6276                            // it from the preferred activities list, and skip it.
6277                            Slog.w(TAG, "Removing dangling preferred activity: "
6278                                    + pa.mPref.mComponent);
6279                            pir.removeFilter(pa);
6280                            changed = true;
6281                            continue;
6282                        }
6283                        for (int j=0; j<N; j++) {
6284                            final ResolveInfo ri = query.get(j);
6285                            if (!ri.activityInfo.applicationInfo.packageName
6286                                    .equals(ai.applicationInfo.packageName)) {
6287                                continue;
6288                            }
6289                            if (!ri.activityInfo.name.equals(ai.name)) {
6290                                continue;
6291                            }
6292
6293                            if (removeMatches) {
6294                                pir.removeFilter(pa);
6295                                changed = true;
6296                                if (DEBUG_PREFERRED) {
6297                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6298                                }
6299                                break;
6300                            }
6301
6302                            // Okay we found a previously set preferred or last chosen app.
6303                            // If the result set is different from when this
6304                            // was created, and is not a subset of the preferred set, we need to
6305                            // clear it and re-ask the user their preference, if we're looking for
6306                            // an "always" type entry.
6307                            if (always && !pa.mPref.sameSet(query)) {
6308                                if (pa.mPref.isSuperset(query)) {
6309                                    // some components of the set are no longer present in
6310                                    // the query, but the preferred activity can still be reused
6311                                    if (DEBUG_PREFERRED) {
6312                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6313                                                + " still valid as only non-preferred components"
6314                                                + " were removed for " + intent + " type "
6315                                                + resolvedType);
6316                                    }
6317                                    // remove obsolete components and re-add the up-to-date filter
6318                                    PreferredActivity freshPa = new PreferredActivity(pa,
6319                                            pa.mPref.mMatch,
6320                                            pa.mPref.discardObsoleteComponents(query),
6321                                            pa.mPref.mComponent,
6322                                            pa.mPref.mAlways);
6323                                    pir.removeFilter(pa);
6324                                    pir.addFilter(freshPa);
6325                                    changed = true;
6326                                } else {
6327                                    Slog.i(TAG,
6328                                            "Result set changed, dropping preferred activity for "
6329                                                    + intent + " type " + resolvedType);
6330                                    if (DEBUG_PREFERRED) {
6331                                        Slog.v(TAG, "Removing preferred activity since set changed "
6332                                                + pa.mPref.mComponent);
6333                                    }
6334                                    pir.removeFilter(pa);
6335                                    // Re-add the filter as a "last chosen" entry (!always)
6336                                    PreferredActivity lastChosen = new PreferredActivity(
6337                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6338                                    pir.addFilter(lastChosen);
6339                                    changed = true;
6340                                    return null;
6341                                }
6342                            }
6343
6344                            // Yay! Either the set matched or we're looking for the last chosen
6345                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6346                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6347                            return ri;
6348                        }
6349                    }
6350                } finally {
6351                    if (changed) {
6352                        if (DEBUG_PREFERRED) {
6353                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6354                        }
6355                        scheduleWritePackageRestrictionsLocked(userId);
6356                    }
6357                }
6358            }
6359        }
6360        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6361        return null;
6362    }
6363
6364    /*
6365     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6366     */
6367    @Override
6368    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6369            int targetUserId) {
6370        mContext.enforceCallingOrSelfPermission(
6371                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6372        List<CrossProfileIntentFilter> matches =
6373                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6374        if (matches != null) {
6375            int size = matches.size();
6376            for (int i = 0; i < size; i++) {
6377                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6378            }
6379        }
6380        if (intent.hasWebURI()) {
6381            // cross-profile app linking works only towards the parent.
6382            final int callingUid = Binder.getCallingUid();
6383            final UserInfo parent = getProfileParent(sourceUserId);
6384            synchronized(mPackages) {
6385                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6386                        false /*includeInstantApps*/);
6387                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6388                        intent, resolvedType, flags, sourceUserId, parent.id);
6389                return xpDomainInfo != null;
6390            }
6391        }
6392        return false;
6393    }
6394
6395    private UserInfo getProfileParent(int userId) {
6396        final long identity = Binder.clearCallingIdentity();
6397        try {
6398            return sUserManager.getProfileParent(userId);
6399        } finally {
6400            Binder.restoreCallingIdentity(identity);
6401        }
6402    }
6403
6404    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6405            String resolvedType, int userId) {
6406        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6407        if (resolver != null) {
6408            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6409        }
6410        return null;
6411    }
6412
6413    @Override
6414    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6415            String resolvedType, int flags, int userId) {
6416        try {
6417            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6418
6419            return new ParceledListSlice<>(
6420                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6421        } finally {
6422            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6423        }
6424    }
6425
6426    /**
6427     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6428     * instant, returns {@code null}.
6429     */
6430    private String getInstantAppPackageName(int callingUid) {
6431        synchronized (mPackages) {
6432            // If the caller is an isolated app use the owner's uid for the lookup.
6433            if (Process.isIsolated(callingUid)) {
6434                callingUid = mIsolatedOwners.get(callingUid);
6435            }
6436            final int appId = UserHandle.getAppId(callingUid);
6437            final Object obj = mSettings.getUserIdLPr(appId);
6438            if (obj instanceof PackageSetting) {
6439                final PackageSetting ps = (PackageSetting) obj;
6440                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6441                return isInstantApp ? ps.pkg.packageName : null;
6442            }
6443        }
6444        return null;
6445    }
6446
6447    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6448            String resolvedType, int flags, int userId) {
6449        return queryIntentActivitiesInternal(
6450                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6451                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6452    }
6453
6454    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6455            String resolvedType, int flags, int filterCallingUid, int userId,
6456            boolean resolveForStart, boolean allowDynamicSplits) {
6457        if (!sUserManager.exists(userId)) return Collections.emptyList();
6458        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6459        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6460                false /* requireFullPermission */, false /* checkShell */,
6461                "query intent activities");
6462        final String pkgName = intent.getPackage();
6463        ComponentName comp = intent.getComponent();
6464        if (comp == null) {
6465            if (intent.getSelector() != null) {
6466                intent = intent.getSelector();
6467                comp = intent.getComponent();
6468            }
6469        }
6470
6471        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6472                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6473        if (comp != null) {
6474            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6475            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6476            if (ai != null) {
6477                // When specifying an explicit component, we prevent the activity from being
6478                // used when either 1) the calling package is normal and the activity is within
6479                // an ephemeral application or 2) the calling package is ephemeral and the
6480                // activity is not visible to ephemeral applications.
6481                final boolean matchInstantApp =
6482                        (flags & PackageManager.MATCH_INSTANT) != 0;
6483                final boolean matchVisibleToInstantAppOnly =
6484                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6485                final boolean matchExplicitlyVisibleOnly =
6486                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6487                final boolean isCallerInstantApp =
6488                        instantAppPkgName != null;
6489                final boolean isTargetSameInstantApp =
6490                        comp.getPackageName().equals(instantAppPkgName);
6491                final boolean isTargetInstantApp =
6492                        (ai.applicationInfo.privateFlags
6493                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6494                final boolean isTargetVisibleToInstantApp =
6495                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6496                final boolean isTargetExplicitlyVisibleToInstantApp =
6497                        isTargetVisibleToInstantApp
6498                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6499                final boolean isTargetHiddenFromInstantApp =
6500                        !isTargetVisibleToInstantApp
6501                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6502                final boolean blockResolution =
6503                        !isTargetSameInstantApp
6504                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6505                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6506                                        && isTargetHiddenFromInstantApp));
6507                if (!blockResolution) {
6508                    final ResolveInfo ri = new ResolveInfo();
6509                    ri.activityInfo = ai;
6510                    list.add(ri);
6511                }
6512            }
6513            return applyPostResolutionFilter(
6514                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6515        }
6516
6517        // reader
6518        boolean sortResult = false;
6519        boolean addEphemeral = false;
6520        List<ResolveInfo> result;
6521        final boolean ephemeralDisabled = isEphemeralDisabled();
6522        synchronized (mPackages) {
6523            if (pkgName == null) {
6524                List<CrossProfileIntentFilter> matchingFilters =
6525                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6526                // Check for results that need to skip the current profile.
6527                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6528                        resolvedType, flags, userId);
6529                if (xpResolveInfo != null) {
6530                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6531                    xpResult.add(xpResolveInfo);
6532                    return applyPostResolutionFilter(
6533                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6534                            allowDynamicSplits, filterCallingUid, userId);
6535                }
6536
6537                // Check for results in the current profile.
6538                result = filterIfNotSystemUser(mActivities.queryIntent(
6539                        intent, resolvedType, flags, userId), userId);
6540                addEphemeral = !ephemeralDisabled
6541                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6542                // Check for cross profile results.
6543                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6544                xpResolveInfo = queryCrossProfileIntents(
6545                        matchingFilters, intent, resolvedType, flags, userId,
6546                        hasNonNegativePriorityResult);
6547                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6548                    boolean isVisibleToUser = filterIfNotSystemUser(
6549                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6550                    if (isVisibleToUser) {
6551                        result.add(xpResolveInfo);
6552                        sortResult = true;
6553                    }
6554                }
6555                if (intent.hasWebURI()) {
6556                    CrossProfileDomainInfo xpDomainInfo = null;
6557                    final UserInfo parent = getProfileParent(userId);
6558                    if (parent != null) {
6559                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6560                                flags, userId, parent.id);
6561                    }
6562                    if (xpDomainInfo != null) {
6563                        if (xpResolveInfo != null) {
6564                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6565                            // in the result.
6566                            result.remove(xpResolveInfo);
6567                        }
6568                        if (result.size() == 0 && !addEphemeral) {
6569                            // No result in current profile, but found candidate in parent user.
6570                            // And we are not going to add emphemeral app, so we can return the
6571                            // result straight away.
6572                            result.add(xpDomainInfo.resolveInfo);
6573                            return applyPostResolutionFilter(result, instantAppPkgName,
6574                                    allowDynamicSplits, filterCallingUid, userId);
6575                        }
6576                    } else if (result.size() <= 1 && !addEphemeral) {
6577                        // No result in parent user and <= 1 result in current profile, and we
6578                        // are not going to add emphemeral app, so we can return the result without
6579                        // further processing.
6580                        return applyPostResolutionFilter(result, instantAppPkgName,
6581                                allowDynamicSplits, filterCallingUid, userId);
6582                    }
6583                    // We have more than one candidate (combining results from current and parent
6584                    // profile), so we need filtering and sorting.
6585                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6586                            intent, flags, result, xpDomainInfo, userId);
6587                    sortResult = true;
6588                }
6589            } else {
6590                final PackageParser.Package pkg = mPackages.get(pkgName);
6591                result = null;
6592                if (pkg != null) {
6593                    result = filterIfNotSystemUser(
6594                            mActivities.queryIntentForPackage(
6595                                    intent, resolvedType, flags, pkg.activities, userId),
6596                            userId);
6597                }
6598                if (result == null || result.size() == 0) {
6599                    // the caller wants to resolve for a particular package; however, there
6600                    // were no installed results, so, try to find an ephemeral result
6601                    addEphemeral = !ephemeralDisabled
6602                            && isInstantAppAllowed(
6603                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6604                    if (result == null) {
6605                        result = new ArrayList<>();
6606                    }
6607                }
6608            }
6609        }
6610        if (addEphemeral) {
6611            result = maybeAddInstantAppInstaller(
6612                    result, intent, resolvedType, flags, userId, resolveForStart);
6613        }
6614        if (sortResult) {
6615            Collections.sort(result, mResolvePrioritySorter);
6616        }
6617        return applyPostResolutionFilter(
6618                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6619    }
6620
6621    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6622            String resolvedType, int flags, int userId, boolean resolveForStart) {
6623        // first, check to see if we've got an instant app already installed
6624        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6625        ResolveInfo localInstantApp = null;
6626        boolean blockResolution = false;
6627        if (!alreadyResolvedLocally) {
6628            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6629                    flags
6630                        | PackageManager.GET_RESOLVED_FILTER
6631                        | PackageManager.MATCH_INSTANT
6632                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6633                    userId);
6634            for (int i = instantApps.size() - 1; i >= 0; --i) {
6635                final ResolveInfo info = instantApps.get(i);
6636                final String packageName = info.activityInfo.packageName;
6637                final PackageSetting ps = mSettings.mPackages.get(packageName);
6638                if (ps.getInstantApp(userId)) {
6639                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6640                    final int status = (int)(packedStatus >> 32);
6641                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6642                        // there's a local instant application installed, but, the user has
6643                        // chosen to never use it; skip resolution and don't acknowledge
6644                        // an instant application is even available
6645                        if (DEBUG_INSTANT) {
6646                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6647                        }
6648                        blockResolution = true;
6649                        break;
6650                    } else {
6651                        // we have a locally installed instant application; skip resolution
6652                        // but acknowledge there's an instant application available
6653                        if (DEBUG_INSTANT) {
6654                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6655                        }
6656                        localInstantApp = info;
6657                        break;
6658                    }
6659                }
6660            }
6661        }
6662        // no app installed, let's see if one's available
6663        AuxiliaryResolveInfo auxiliaryResponse = null;
6664        if (!blockResolution) {
6665            if (localInstantApp == null) {
6666                // we don't have an instant app locally, resolve externally
6667                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6668                final InstantAppRequest requestObject = new InstantAppRequest(
6669                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6670                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6671                        resolveForStart);
6672                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6673                        mInstantAppResolverConnection, requestObject);
6674                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6675            } else {
6676                // we have an instant application locally, but, we can't admit that since
6677                // callers shouldn't be able to determine prior browsing. create a dummy
6678                // auxiliary response so the downstream code behaves as if there's an
6679                // instant application available externally. when it comes time to start
6680                // the instant application, we'll do the right thing.
6681                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6682                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6683                                        ai.packageName, ai.versionCode, null /* splitName */);
6684            }
6685        }
6686        if (intent.isWebIntent() && auxiliaryResponse == null) {
6687            return result;
6688        }
6689        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6690        if (ps == null) {
6691            return result;
6692        }
6693        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6694        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6695                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6696        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6697                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6698        // add a non-generic filter
6699        ephemeralInstaller.filter = new IntentFilter();
6700        if (intent.getAction() != null) {
6701            ephemeralInstaller.filter.addAction(intent.getAction());
6702        }
6703        if (intent.getData() != null && intent.getData().getPath() != null) {
6704            ephemeralInstaller.filter.addDataPath(
6705                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6706        }
6707        ephemeralInstaller.isInstantAppAvailable = true;
6708        // make sure this resolver is the default
6709        ephemeralInstaller.isDefault = true;
6710        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6711        if (DEBUG_INSTANT) {
6712            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6713        }
6714
6715        result.add(ephemeralInstaller);
6716        return result;
6717    }
6718
6719    private static class CrossProfileDomainInfo {
6720        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6721        ResolveInfo resolveInfo;
6722        /* Best domain verification status of the activities found in the other profile */
6723        int bestDomainVerificationStatus;
6724    }
6725
6726    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6727            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6728        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6729                sourceUserId)) {
6730            return null;
6731        }
6732        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6733                resolvedType, flags, parentUserId);
6734
6735        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6736            return null;
6737        }
6738        CrossProfileDomainInfo result = null;
6739        int size = resultTargetUser.size();
6740        for (int i = 0; i < size; i++) {
6741            ResolveInfo riTargetUser = resultTargetUser.get(i);
6742            // Intent filter verification is only for filters that specify a host. So don't return
6743            // those that handle all web uris.
6744            if (riTargetUser.handleAllWebDataURI) {
6745                continue;
6746            }
6747            String packageName = riTargetUser.activityInfo.packageName;
6748            PackageSetting ps = mSettings.mPackages.get(packageName);
6749            if (ps == null) {
6750                continue;
6751            }
6752            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6753            int status = (int)(verificationState >> 32);
6754            if (result == null) {
6755                result = new CrossProfileDomainInfo();
6756                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6757                        sourceUserId, parentUserId);
6758                result.bestDomainVerificationStatus = status;
6759            } else {
6760                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6761                        result.bestDomainVerificationStatus);
6762            }
6763        }
6764        // Don't consider matches with status NEVER across profiles.
6765        if (result != null && result.bestDomainVerificationStatus
6766                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6767            return null;
6768        }
6769        return result;
6770    }
6771
6772    /**
6773     * Verification statuses are ordered from the worse to the best, except for
6774     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6775     */
6776    private int bestDomainVerificationStatus(int status1, int status2) {
6777        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6778            return status2;
6779        }
6780        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6781            return status1;
6782        }
6783        return (int) MathUtils.max(status1, status2);
6784    }
6785
6786    private boolean isUserEnabled(int userId) {
6787        long callingId = Binder.clearCallingIdentity();
6788        try {
6789            UserInfo userInfo = sUserManager.getUserInfo(userId);
6790            return userInfo != null && userInfo.isEnabled();
6791        } finally {
6792            Binder.restoreCallingIdentity(callingId);
6793        }
6794    }
6795
6796    /**
6797     * Filter out activities with systemUserOnly flag set, when current user is not System.
6798     *
6799     * @return filtered list
6800     */
6801    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6802        if (userId == UserHandle.USER_SYSTEM) {
6803            return resolveInfos;
6804        }
6805        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6806            ResolveInfo info = resolveInfos.get(i);
6807            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6808                resolveInfos.remove(i);
6809            }
6810        }
6811        return resolveInfos;
6812    }
6813
6814    /**
6815     * Filters out ephemeral activities.
6816     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6817     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6818     *
6819     * @param resolveInfos The pre-filtered list of resolved activities
6820     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6821     *          is performed.
6822     * @return A filtered list of resolved activities.
6823     */
6824    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6825            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6826        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6827            final ResolveInfo info = resolveInfos.get(i);
6828            // allow activities that are defined in the provided package
6829            if (allowDynamicSplits
6830                    && info.activityInfo != null
6831                    && info.activityInfo.splitName != null
6832                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6833                            info.activityInfo.splitName)) {
6834                if (mInstantAppInstallerActivity == null) {
6835                    if (DEBUG_INSTALL) {
6836                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6837                    }
6838                    resolveInfos.remove(i);
6839                    continue;
6840                }
6841                // requested activity is defined in a split that hasn't been installed yet.
6842                // add the installer to the resolve list
6843                if (DEBUG_INSTALL) {
6844                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6845                }
6846                final ResolveInfo installerInfo = new ResolveInfo(
6847                        mInstantAppInstallerInfo);
6848                final ComponentName installFailureActivity = findInstallFailureActivity(
6849                        info.activityInfo.packageName,  filterCallingUid, userId);
6850                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6851                        installFailureActivity,
6852                        info.activityInfo.packageName,
6853                        info.activityInfo.applicationInfo.versionCode,
6854                        info.activityInfo.splitName);
6855                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6856                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6857                // add a non-generic filter
6858                installerInfo.filter = new IntentFilter();
6859
6860                // This resolve info may appear in the chooser UI, so let us make it
6861                // look as the one it replaces as far as the user is concerned which
6862                // requires loading the correct label and icon for the resolve info.
6863                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6864                installerInfo.labelRes = info.resolveLabelResId();
6865                installerInfo.icon = info.resolveIconResId();
6866
6867                // propagate priority/preferred order/default
6868                installerInfo.priority = info.priority;
6869                installerInfo.preferredOrder = info.preferredOrder;
6870                installerInfo.isDefault = info.isDefault;
6871                installerInfo.isInstantAppAvailable = true;
6872                resolveInfos.set(i, installerInfo);
6873                continue;
6874            }
6875            // caller is a full app, don't need to apply any other filtering
6876            if (ephemeralPkgName == null) {
6877                continue;
6878            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6879                // caller is same app; don't need to apply any other filtering
6880                continue;
6881            }
6882            // allow activities that have been explicitly exposed to ephemeral apps
6883            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6884            if (!isEphemeralApp
6885                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6886                continue;
6887            }
6888            resolveInfos.remove(i);
6889        }
6890        return resolveInfos;
6891    }
6892
6893    /**
6894     * Returns the activity component that can handle install failures.
6895     * <p>By default, the instant application installer handles failures. However, an
6896     * application may want to handle failures on its own. Applications do this by
6897     * creating an activity with an intent filter that handles the action
6898     * {@link Intent#ACTION_INSTALL_FAILURE}.
6899     */
6900    private @Nullable ComponentName findInstallFailureActivity(
6901            String packageName, int filterCallingUid, int userId) {
6902        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6903        failureActivityIntent.setPackage(packageName);
6904        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6905        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6906                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6907                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6908        final int NR = result.size();
6909        if (NR > 0) {
6910            for (int i = 0; i < NR; i++) {
6911                final ResolveInfo info = result.get(i);
6912                if (info.activityInfo.splitName != null) {
6913                    continue;
6914                }
6915                return new ComponentName(packageName, info.activityInfo.name);
6916            }
6917        }
6918        return null;
6919    }
6920
6921    /**
6922     * @param resolveInfos list of resolve infos in descending priority order
6923     * @return if the list contains a resolve info with non-negative priority
6924     */
6925    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6926        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6927    }
6928
6929    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6930            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6931            int userId) {
6932        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6933
6934        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6935            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6936                    candidates.size());
6937        }
6938
6939        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6940        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6941        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6942        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6943        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6944        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6945
6946        synchronized (mPackages) {
6947            final int count = candidates.size();
6948            // First, try to use linked apps. Partition the candidates into four lists:
6949            // one for the final results, one for the "do not use ever", one for "undefined status"
6950            // and finally one for "browser app type".
6951            for (int n=0; n<count; n++) {
6952                ResolveInfo info = candidates.get(n);
6953                String packageName = info.activityInfo.packageName;
6954                PackageSetting ps = mSettings.mPackages.get(packageName);
6955                if (ps != null) {
6956                    // Add to the special match all list (Browser use case)
6957                    if (info.handleAllWebDataURI) {
6958                        matchAllList.add(info);
6959                        continue;
6960                    }
6961                    // Try to get the status from User settings first
6962                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6963                    int status = (int)(packedStatus >> 32);
6964                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6965                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6966                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6967                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6968                                    + " : linkgen=" + linkGeneration);
6969                        }
6970                        // Use link-enabled generation as preferredOrder, i.e.
6971                        // prefer newly-enabled over earlier-enabled.
6972                        info.preferredOrder = linkGeneration;
6973                        alwaysList.add(info);
6974                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6975                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6976                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6977                        }
6978                        neverList.add(info);
6979                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6980                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6981                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6982                        }
6983                        alwaysAskList.add(info);
6984                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6985                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6986                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6987                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6988                        }
6989                        undefinedList.add(info);
6990                    }
6991                }
6992            }
6993
6994            // We'll want to include browser possibilities in a few cases
6995            boolean includeBrowser = false;
6996
6997            // First try to add the "always" resolution(s) for the current user, if any
6998            if (alwaysList.size() > 0) {
6999                result.addAll(alwaysList);
7000            } else {
7001                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7002                result.addAll(undefinedList);
7003                // Maybe add one for the other profile.
7004                if (xpDomainInfo != null && (
7005                        xpDomainInfo.bestDomainVerificationStatus
7006                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7007                    result.add(xpDomainInfo.resolveInfo);
7008                }
7009                includeBrowser = true;
7010            }
7011
7012            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7013            // If there were 'always' entries their preferred order has been set, so we also
7014            // back that off to make the alternatives equivalent
7015            if (alwaysAskList.size() > 0) {
7016                for (ResolveInfo i : result) {
7017                    i.preferredOrder = 0;
7018                }
7019                result.addAll(alwaysAskList);
7020                includeBrowser = true;
7021            }
7022
7023            if (includeBrowser) {
7024                // Also add browsers (all of them or only the default one)
7025                if (DEBUG_DOMAIN_VERIFICATION) {
7026                    Slog.v(TAG, "   ...including browsers in candidate set");
7027                }
7028                if ((matchFlags & MATCH_ALL) != 0) {
7029                    result.addAll(matchAllList);
7030                } else {
7031                    // Browser/generic handling case.  If there's a default browser, go straight
7032                    // to that (but only if there is no other higher-priority match).
7033                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7034                    int maxMatchPrio = 0;
7035                    ResolveInfo defaultBrowserMatch = null;
7036                    final int numCandidates = matchAllList.size();
7037                    for (int n = 0; n < numCandidates; n++) {
7038                        ResolveInfo info = matchAllList.get(n);
7039                        // track the highest overall match priority...
7040                        if (info.priority > maxMatchPrio) {
7041                            maxMatchPrio = info.priority;
7042                        }
7043                        // ...and the highest-priority default browser match
7044                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7045                            if (defaultBrowserMatch == null
7046                                    || (defaultBrowserMatch.priority < info.priority)) {
7047                                if (debug) {
7048                                    Slog.v(TAG, "Considering default browser match " + info);
7049                                }
7050                                defaultBrowserMatch = info;
7051                            }
7052                        }
7053                    }
7054                    if (defaultBrowserMatch != null
7055                            && defaultBrowserMatch.priority >= maxMatchPrio
7056                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7057                    {
7058                        if (debug) {
7059                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7060                        }
7061                        result.add(defaultBrowserMatch);
7062                    } else {
7063                        result.addAll(matchAllList);
7064                    }
7065                }
7066
7067                // If there is nothing selected, add all candidates and remove the ones that the user
7068                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7069                if (result.size() == 0) {
7070                    result.addAll(candidates);
7071                    result.removeAll(neverList);
7072                }
7073            }
7074        }
7075        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7076            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7077                    result.size());
7078            for (ResolveInfo info : result) {
7079                Slog.v(TAG, "  + " + info.activityInfo);
7080            }
7081        }
7082        return result;
7083    }
7084
7085    // Returns a packed value as a long:
7086    //
7087    // high 'int'-sized word: link status: undefined/ask/never/always.
7088    // low 'int'-sized word: relative priority among 'always' results.
7089    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7090        long result = ps.getDomainVerificationStatusForUser(userId);
7091        // if none available, get the master status
7092        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7093            if (ps.getIntentFilterVerificationInfo() != null) {
7094                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7095            }
7096        }
7097        return result;
7098    }
7099
7100    private ResolveInfo querySkipCurrentProfileIntents(
7101            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7102            int flags, int sourceUserId) {
7103        if (matchingFilters != null) {
7104            int size = matchingFilters.size();
7105            for (int i = 0; i < size; i ++) {
7106                CrossProfileIntentFilter filter = matchingFilters.get(i);
7107                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7108                    // Checking if there are activities in the target user that can handle the
7109                    // intent.
7110                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7111                            resolvedType, flags, sourceUserId);
7112                    if (resolveInfo != null) {
7113                        return resolveInfo;
7114                    }
7115                }
7116            }
7117        }
7118        return null;
7119    }
7120
7121    // Return matching ResolveInfo in target user if any.
7122    private ResolveInfo queryCrossProfileIntents(
7123            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7124            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7125        if (matchingFilters != null) {
7126            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7127            // match the same intent. For performance reasons, it is better not to
7128            // run queryIntent twice for the same userId
7129            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7130            int size = matchingFilters.size();
7131            for (int i = 0; i < size; i++) {
7132                CrossProfileIntentFilter filter = matchingFilters.get(i);
7133                int targetUserId = filter.getTargetUserId();
7134                boolean skipCurrentProfile =
7135                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7136                boolean skipCurrentProfileIfNoMatchFound =
7137                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7138                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7139                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7140                    // Checking if there are activities in the target user that can handle the
7141                    // intent.
7142                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7143                            resolvedType, flags, sourceUserId);
7144                    if (resolveInfo != null) return resolveInfo;
7145                    alreadyTriedUserIds.put(targetUserId, true);
7146                }
7147            }
7148        }
7149        return null;
7150    }
7151
7152    /**
7153     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7154     * will forward the intent to the filter's target user.
7155     * Otherwise, returns null.
7156     */
7157    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7158            String resolvedType, int flags, int sourceUserId) {
7159        int targetUserId = filter.getTargetUserId();
7160        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7161                resolvedType, flags, targetUserId);
7162        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7163            // If all the matches in the target profile are suspended, return null.
7164            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7165                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7166                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7167                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7168                            targetUserId);
7169                }
7170            }
7171        }
7172        return null;
7173    }
7174
7175    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7176            int sourceUserId, int targetUserId) {
7177        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7178        long ident = Binder.clearCallingIdentity();
7179        boolean targetIsProfile;
7180        try {
7181            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7182        } finally {
7183            Binder.restoreCallingIdentity(ident);
7184        }
7185        String className;
7186        if (targetIsProfile) {
7187            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7188        } else {
7189            className = FORWARD_INTENT_TO_PARENT;
7190        }
7191        ComponentName forwardingActivityComponentName = new ComponentName(
7192                mAndroidApplication.packageName, className);
7193        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7194                sourceUserId);
7195        if (!targetIsProfile) {
7196            forwardingActivityInfo.showUserIcon = targetUserId;
7197            forwardingResolveInfo.noResourceId = true;
7198        }
7199        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7200        forwardingResolveInfo.priority = 0;
7201        forwardingResolveInfo.preferredOrder = 0;
7202        forwardingResolveInfo.match = 0;
7203        forwardingResolveInfo.isDefault = true;
7204        forwardingResolveInfo.filter = filter;
7205        forwardingResolveInfo.targetUserId = targetUserId;
7206        return forwardingResolveInfo;
7207    }
7208
7209    @Override
7210    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7211            Intent[] specifics, String[] specificTypes, Intent intent,
7212            String resolvedType, int flags, int userId) {
7213        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7214                specificTypes, intent, resolvedType, flags, userId));
7215    }
7216
7217    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7218            Intent[] specifics, String[] specificTypes, Intent intent,
7219            String resolvedType, int flags, int userId) {
7220        if (!sUserManager.exists(userId)) return Collections.emptyList();
7221        final int callingUid = Binder.getCallingUid();
7222        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7223                false /*includeInstantApps*/);
7224        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7225                false /*requireFullPermission*/, false /*checkShell*/,
7226                "query intent activity options");
7227        final String resultsAction = intent.getAction();
7228
7229        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7230                | PackageManager.GET_RESOLVED_FILTER, userId);
7231
7232        if (DEBUG_INTENT_MATCHING) {
7233            Log.v(TAG, "Query " + intent + ": " + results);
7234        }
7235
7236        int specificsPos = 0;
7237        int N;
7238
7239        // todo: note that the algorithm used here is O(N^2).  This
7240        // isn't a problem in our current environment, but if we start running
7241        // into situations where we have more than 5 or 10 matches then this
7242        // should probably be changed to something smarter...
7243
7244        // First we go through and resolve each of the specific items
7245        // that were supplied, taking care of removing any corresponding
7246        // duplicate items in the generic resolve list.
7247        if (specifics != null) {
7248            for (int i=0; i<specifics.length; i++) {
7249                final Intent sintent = specifics[i];
7250                if (sintent == null) {
7251                    continue;
7252                }
7253
7254                if (DEBUG_INTENT_MATCHING) {
7255                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7256                }
7257
7258                String action = sintent.getAction();
7259                if (resultsAction != null && resultsAction.equals(action)) {
7260                    // If this action was explicitly requested, then don't
7261                    // remove things that have it.
7262                    action = null;
7263                }
7264
7265                ResolveInfo ri = null;
7266                ActivityInfo ai = null;
7267
7268                ComponentName comp = sintent.getComponent();
7269                if (comp == null) {
7270                    ri = resolveIntent(
7271                        sintent,
7272                        specificTypes != null ? specificTypes[i] : null,
7273                            flags, userId);
7274                    if (ri == null) {
7275                        continue;
7276                    }
7277                    if (ri == mResolveInfo) {
7278                        // ACK!  Must do something better with this.
7279                    }
7280                    ai = ri.activityInfo;
7281                    comp = new ComponentName(ai.applicationInfo.packageName,
7282                            ai.name);
7283                } else {
7284                    ai = getActivityInfo(comp, flags, userId);
7285                    if (ai == null) {
7286                        continue;
7287                    }
7288                }
7289
7290                // Look for any generic query activities that are duplicates
7291                // of this specific one, and remove them from the results.
7292                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7293                N = results.size();
7294                int j;
7295                for (j=specificsPos; j<N; j++) {
7296                    ResolveInfo sri = results.get(j);
7297                    if ((sri.activityInfo.name.equals(comp.getClassName())
7298                            && sri.activityInfo.applicationInfo.packageName.equals(
7299                                    comp.getPackageName()))
7300                        || (action != null && sri.filter.matchAction(action))) {
7301                        results.remove(j);
7302                        if (DEBUG_INTENT_MATCHING) Log.v(
7303                            TAG, "Removing duplicate item from " + j
7304                            + " due to specific " + specificsPos);
7305                        if (ri == null) {
7306                            ri = sri;
7307                        }
7308                        j--;
7309                        N--;
7310                    }
7311                }
7312
7313                // Add this specific item to its proper place.
7314                if (ri == null) {
7315                    ri = new ResolveInfo();
7316                    ri.activityInfo = ai;
7317                }
7318                results.add(specificsPos, ri);
7319                ri.specificIndex = i;
7320                specificsPos++;
7321            }
7322        }
7323
7324        // Now we go through the remaining generic results and remove any
7325        // duplicate actions that are found here.
7326        N = results.size();
7327        for (int i=specificsPos; i<N-1; i++) {
7328            final ResolveInfo rii = results.get(i);
7329            if (rii.filter == null) {
7330                continue;
7331            }
7332
7333            // Iterate over all of the actions of this result's intent
7334            // filter...  typically this should be just one.
7335            final Iterator<String> it = rii.filter.actionsIterator();
7336            if (it == null) {
7337                continue;
7338            }
7339            while (it.hasNext()) {
7340                final String action = it.next();
7341                if (resultsAction != null && resultsAction.equals(action)) {
7342                    // If this action was explicitly requested, then don't
7343                    // remove things that have it.
7344                    continue;
7345                }
7346                for (int j=i+1; j<N; j++) {
7347                    final ResolveInfo rij = results.get(j);
7348                    if (rij.filter != null && rij.filter.hasAction(action)) {
7349                        results.remove(j);
7350                        if (DEBUG_INTENT_MATCHING) Log.v(
7351                            TAG, "Removing duplicate item from " + j
7352                            + " due to action " + action + " at " + i);
7353                        j--;
7354                        N--;
7355                    }
7356                }
7357            }
7358
7359            // If the caller didn't request filter information, drop it now
7360            // so we don't have to marshall/unmarshall it.
7361            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7362                rii.filter = null;
7363            }
7364        }
7365
7366        // Filter out the caller activity if so requested.
7367        if (caller != null) {
7368            N = results.size();
7369            for (int i=0; i<N; i++) {
7370                ActivityInfo ainfo = results.get(i).activityInfo;
7371                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7372                        && caller.getClassName().equals(ainfo.name)) {
7373                    results.remove(i);
7374                    break;
7375                }
7376            }
7377        }
7378
7379        // If the caller didn't request filter information,
7380        // drop them now so we don't have to
7381        // marshall/unmarshall it.
7382        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7383            N = results.size();
7384            for (int i=0; i<N; i++) {
7385                results.get(i).filter = null;
7386            }
7387        }
7388
7389        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7390        return results;
7391    }
7392
7393    @Override
7394    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7395            String resolvedType, int flags, int userId) {
7396        return new ParceledListSlice<>(
7397                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7398                        false /*allowDynamicSplits*/));
7399    }
7400
7401    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7402            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7403        if (!sUserManager.exists(userId)) return Collections.emptyList();
7404        final int callingUid = Binder.getCallingUid();
7405        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7406                false /*requireFullPermission*/, false /*checkShell*/,
7407                "query intent receivers");
7408        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7409        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7410                false /*includeInstantApps*/);
7411        ComponentName comp = intent.getComponent();
7412        if (comp == null) {
7413            if (intent.getSelector() != null) {
7414                intent = intent.getSelector();
7415                comp = intent.getComponent();
7416            }
7417        }
7418        if (comp != null) {
7419            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7420            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7421            if (ai != null) {
7422                // When specifying an explicit component, we prevent the activity from being
7423                // used when either 1) the calling package is normal and the activity is within
7424                // an instant application or 2) the calling package is ephemeral and the
7425                // activity is not visible to instant applications.
7426                final boolean matchInstantApp =
7427                        (flags & PackageManager.MATCH_INSTANT) != 0;
7428                final boolean matchVisibleToInstantAppOnly =
7429                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7430                final boolean matchExplicitlyVisibleOnly =
7431                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7432                final boolean isCallerInstantApp =
7433                        instantAppPkgName != null;
7434                final boolean isTargetSameInstantApp =
7435                        comp.getPackageName().equals(instantAppPkgName);
7436                final boolean isTargetInstantApp =
7437                        (ai.applicationInfo.privateFlags
7438                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7439                final boolean isTargetVisibleToInstantApp =
7440                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7441                final boolean isTargetExplicitlyVisibleToInstantApp =
7442                        isTargetVisibleToInstantApp
7443                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7444                final boolean isTargetHiddenFromInstantApp =
7445                        !isTargetVisibleToInstantApp
7446                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7447                final boolean blockResolution =
7448                        !isTargetSameInstantApp
7449                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7450                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7451                                        && isTargetHiddenFromInstantApp));
7452                if (!blockResolution) {
7453                    ResolveInfo ri = new ResolveInfo();
7454                    ri.activityInfo = ai;
7455                    list.add(ri);
7456                }
7457            }
7458            return applyPostResolutionFilter(
7459                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7460        }
7461
7462        // reader
7463        synchronized (mPackages) {
7464            String pkgName = intent.getPackage();
7465            if (pkgName == null) {
7466                final List<ResolveInfo> result =
7467                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7468                return applyPostResolutionFilter(
7469                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7470            }
7471            final PackageParser.Package pkg = mPackages.get(pkgName);
7472            if (pkg != null) {
7473                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7474                        intent, resolvedType, flags, pkg.receivers, userId);
7475                return applyPostResolutionFilter(
7476                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7477            }
7478            return Collections.emptyList();
7479        }
7480    }
7481
7482    @Override
7483    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7484        final int callingUid = Binder.getCallingUid();
7485        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7486    }
7487
7488    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7489            int userId, int callingUid) {
7490        if (!sUserManager.exists(userId)) return null;
7491        flags = updateFlagsForResolve(
7492                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7493        List<ResolveInfo> query = queryIntentServicesInternal(
7494                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7495        if (query != null) {
7496            if (query.size() >= 1) {
7497                // If there is more than one service with the same priority,
7498                // just arbitrarily pick the first one.
7499                return query.get(0);
7500            }
7501        }
7502        return null;
7503    }
7504
7505    @Override
7506    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7507            String resolvedType, int flags, int userId) {
7508        final int callingUid = Binder.getCallingUid();
7509        return new ParceledListSlice<>(queryIntentServicesInternal(
7510                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7511    }
7512
7513    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7514            String resolvedType, int flags, int userId, int callingUid,
7515            boolean includeInstantApps) {
7516        if (!sUserManager.exists(userId)) return Collections.emptyList();
7517        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7518                false /*requireFullPermission*/, false /*checkShell*/,
7519                "query intent receivers");
7520        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7521        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7522        ComponentName comp = intent.getComponent();
7523        if (comp == null) {
7524            if (intent.getSelector() != null) {
7525                intent = intent.getSelector();
7526                comp = intent.getComponent();
7527            }
7528        }
7529        if (comp != null) {
7530            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7531            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7532            if (si != null) {
7533                // When specifying an explicit component, we prevent the service from being
7534                // used when either 1) the service is in an instant application and the
7535                // caller is not the same instant application or 2) the calling package is
7536                // ephemeral and the activity is not visible to ephemeral applications.
7537                final boolean matchInstantApp =
7538                        (flags & PackageManager.MATCH_INSTANT) != 0;
7539                final boolean matchVisibleToInstantAppOnly =
7540                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7541                final boolean isCallerInstantApp =
7542                        instantAppPkgName != null;
7543                final boolean isTargetSameInstantApp =
7544                        comp.getPackageName().equals(instantAppPkgName);
7545                final boolean isTargetInstantApp =
7546                        (si.applicationInfo.privateFlags
7547                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7548                final boolean isTargetHiddenFromInstantApp =
7549                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7550                final boolean blockResolution =
7551                        !isTargetSameInstantApp
7552                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7553                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7554                                        && isTargetHiddenFromInstantApp));
7555                if (!blockResolution) {
7556                    final ResolveInfo ri = new ResolveInfo();
7557                    ri.serviceInfo = si;
7558                    list.add(ri);
7559                }
7560            }
7561            return list;
7562        }
7563
7564        // reader
7565        synchronized (mPackages) {
7566            String pkgName = intent.getPackage();
7567            if (pkgName == null) {
7568                return applyPostServiceResolutionFilter(
7569                        mServices.queryIntent(intent, resolvedType, flags, userId),
7570                        instantAppPkgName);
7571            }
7572            final PackageParser.Package pkg = mPackages.get(pkgName);
7573            if (pkg != null) {
7574                return applyPostServiceResolutionFilter(
7575                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7576                                userId),
7577                        instantAppPkgName);
7578            }
7579            return Collections.emptyList();
7580        }
7581    }
7582
7583    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7584            String instantAppPkgName) {
7585        if (instantAppPkgName == null) {
7586            return resolveInfos;
7587        }
7588        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7589            final ResolveInfo info = resolveInfos.get(i);
7590            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7591            // allow services that are defined in the provided package
7592            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7593                if (info.serviceInfo.splitName != null
7594                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7595                                info.serviceInfo.splitName)) {
7596                    // requested service is defined in a split that hasn't been installed yet.
7597                    // add the installer to the resolve list
7598                    if (DEBUG_INSTANT) {
7599                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7600                    }
7601                    final ResolveInfo installerInfo = new ResolveInfo(
7602                            mInstantAppInstallerInfo);
7603                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7604                            null /* installFailureActivity */,
7605                            info.serviceInfo.packageName,
7606                            info.serviceInfo.applicationInfo.versionCode,
7607                            info.serviceInfo.splitName);
7608                    // make sure this resolver is the default
7609                    installerInfo.isDefault = true;
7610                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7611                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7612                    // add a non-generic filter
7613                    installerInfo.filter = new IntentFilter();
7614                    // load resources from the correct package
7615                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7616                    resolveInfos.set(i, installerInfo);
7617                }
7618                continue;
7619            }
7620            // allow services that have been explicitly exposed to ephemeral apps
7621            if (!isEphemeralApp
7622                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7623                continue;
7624            }
7625            resolveInfos.remove(i);
7626        }
7627        return resolveInfos;
7628    }
7629
7630    @Override
7631    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7632            String resolvedType, int flags, int userId) {
7633        return new ParceledListSlice<>(
7634                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7635    }
7636
7637    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7638            Intent intent, String resolvedType, int flags, int userId) {
7639        if (!sUserManager.exists(userId)) return Collections.emptyList();
7640        final int callingUid = Binder.getCallingUid();
7641        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7642        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7643                false /*includeInstantApps*/);
7644        ComponentName comp = intent.getComponent();
7645        if (comp == null) {
7646            if (intent.getSelector() != null) {
7647                intent = intent.getSelector();
7648                comp = intent.getComponent();
7649            }
7650        }
7651        if (comp != null) {
7652            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7653            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7654            if (pi != null) {
7655                // When specifying an explicit component, we prevent the provider from being
7656                // used when either 1) the provider is in an instant application and the
7657                // caller is not the same instant application or 2) the calling package is an
7658                // instant application and the provider is not visible to instant applications.
7659                final boolean matchInstantApp =
7660                        (flags & PackageManager.MATCH_INSTANT) != 0;
7661                final boolean matchVisibleToInstantAppOnly =
7662                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7663                final boolean isCallerInstantApp =
7664                        instantAppPkgName != null;
7665                final boolean isTargetSameInstantApp =
7666                        comp.getPackageName().equals(instantAppPkgName);
7667                final boolean isTargetInstantApp =
7668                        (pi.applicationInfo.privateFlags
7669                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7670                final boolean isTargetHiddenFromInstantApp =
7671                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7672                final boolean blockResolution =
7673                        !isTargetSameInstantApp
7674                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7675                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7676                                        && isTargetHiddenFromInstantApp));
7677                if (!blockResolution) {
7678                    final ResolveInfo ri = new ResolveInfo();
7679                    ri.providerInfo = pi;
7680                    list.add(ri);
7681                }
7682            }
7683            return list;
7684        }
7685
7686        // reader
7687        synchronized (mPackages) {
7688            String pkgName = intent.getPackage();
7689            if (pkgName == null) {
7690                return applyPostContentProviderResolutionFilter(
7691                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7692                        instantAppPkgName);
7693            }
7694            final PackageParser.Package pkg = mPackages.get(pkgName);
7695            if (pkg != null) {
7696                return applyPostContentProviderResolutionFilter(
7697                        mProviders.queryIntentForPackage(
7698                        intent, resolvedType, flags, pkg.providers, userId),
7699                        instantAppPkgName);
7700            }
7701            return Collections.emptyList();
7702        }
7703    }
7704
7705    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7706            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7707        if (instantAppPkgName == null) {
7708            return resolveInfos;
7709        }
7710        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7711            final ResolveInfo info = resolveInfos.get(i);
7712            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7713            // allow providers that are defined in the provided package
7714            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7715                if (info.providerInfo.splitName != null
7716                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7717                                info.providerInfo.splitName)) {
7718                    // requested provider is defined in a split that hasn't been installed yet.
7719                    // add the installer to the resolve list
7720                    if (DEBUG_INSTANT) {
7721                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7722                    }
7723                    final ResolveInfo installerInfo = new ResolveInfo(
7724                            mInstantAppInstallerInfo);
7725                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7726                            null /*failureActivity*/,
7727                            info.providerInfo.packageName,
7728                            info.providerInfo.applicationInfo.versionCode,
7729                            info.providerInfo.splitName);
7730                    // make sure this resolver is the default
7731                    installerInfo.isDefault = true;
7732                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7733                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7734                    // add a non-generic filter
7735                    installerInfo.filter = new IntentFilter();
7736                    // load resources from the correct package
7737                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7738                    resolveInfos.set(i, installerInfo);
7739                }
7740                continue;
7741            }
7742            // allow providers that have been explicitly exposed to instant applications
7743            if (!isEphemeralApp
7744                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7745                continue;
7746            }
7747            resolveInfos.remove(i);
7748        }
7749        return resolveInfos;
7750    }
7751
7752    @Override
7753    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7754        final int callingUid = Binder.getCallingUid();
7755        if (getInstantAppPackageName(callingUid) != null) {
7756            return ParceledListSlice.emptyList();
7757        }
7758        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7759        flags = updateFlagsForPackage(flags, userId, null);
7760        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7761        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7762                true /* requireFullPermission */, false /* checkShell */,
7763                "get installed packages");
7764
7765        // writer
7766        synchronized (mPackages) {
7767            ArrayList<PackageInfo> list;
7768            if (listUninstalled) {
7769                list = new ArrayList<>(mSettings.mPackages.size());
7770                for (PackageSetting ps : mSettings.mPackages.values()) {
7771                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7772                        continue;
7773                    }
7774                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7775                        continue;
7776                    }
7777                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7778                    if (pi != null) {
7779                        list.add(pi);
7780                    }
7781                }
7782            } else {
7783                list = new ArrayList<>(mPackages.size());
7784                for (PackageParser.Package p : mPackages.values()) {
7785                    final PackageSetting ps = (PackageSetting) p.mExtras;
7786                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7787                        continue;
7788                    }
7789                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7790                        continue;
7791                    }
7792                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7793                            p.mExtras, flags, userId);
7794                    if (pi != null) {
7795                        list.add(pi);
7796                    }
7797                }
7798            }
7799
7800            return new ParceledListSlice<>(list);
7801        }
7802    }
7803
7804    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7805            String[] permissions, boolean[] tmp, int flags, int userId) {
7806        int numMatch = 0;
7807        final PermissionsState permissionsState = ps.getPermissionsState();
7808        for (int i=0; i<permissions.length; i++) {
7809            final String permission = permissions[i];
7810            if (permissionsState.hasPermission(permission, userId)) {
7811                tmp[i] = true;
7812                numMatch++;
7813            } else {
7814                tmp[i] = false;
7815            }
7816        }
7817        if (numMatch == 0) {
7818            return;
7819        }
7820        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7821
7822        // The above might return null in cases of uninstalled apps or install-state
7823        // skew across users/profiles.
7824        if (pi != null) {
7825            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7826                if (numMatch == permissions.length) {
7827                    pi.requestedPermissions = permissions;
7828                } else {
7829                    pi.requestedPermissions = new String[numMatch];
7830                    numMatch = 0;
7831                    for (int i=0; i<permissions.length; i++) {
7832                        if (tmp[i]) {
7833                            pi.requestedPermissions[numMatch] = permissions[i];
7834                            numMatch++;
7835                        }
7836                    }
7837                }
7838            }
7839            list.add(pi);
7840        }
7841    }
7842
7843    @Override
7844    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7845            String[] permissions, int flags, int userId) {
7846        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7847        flags = updateFlagsForPackage(flags, userId, permissions);
7848        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7849                true /* requireFullPermission */, false /* checkShell */,
7850                "get packages holding permissions");
7851        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7852
7853        // writer
7854        synchronized (mPackages) {
7855            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7856            boolean[] tmpBools = new boolean[permissions.length];
7857            if (listUninstalled) {
7858                for (PackageSetting ps : mSettings.mPackages.values()) {
7859                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7860                            userId);
7861                }
7862            } else {
7863                for (PackageParser.Package pkg : mPackages.values()) {
7864                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7865                    if (ps != null) {
7866                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7867                                userId);
7868                    }
7869                }
7870            }
7871
7872            return new ParceledListSlice<PackageInfo>(list);
7873        }
7874    }
7875
7876    @Override
7877    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7878        final int callingUid = Binder.getCallingUid();
7879        if (getInstantAppPackageName(callingUid) != null) {
7880            return ParceledListSlice.emptyList();
7881        }
7882        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7883        flags = updateFlagsForApplication(flags, userId, null);
7884        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7885
7886        // writer
7887        synchronized (mPackages) {
7888            ArrayList<ApplicationInfo> list;
7889            if (listUninstalled) {
7890                list = new ArrayList<>(mSettings.mPackages.size());
7891                for (PackageSetting ps : mSettings.mPackages.values()) {
7892                    ApplicationInfo ai;
7893                    int effectiveFlags = flags;
7894                    if (ps.isSystem()) {
7895                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7896                    }
7897                    if (ps.pkg != null) {
7898                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7899                            continue;
7900                        }
7901                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7902                            continue;
7903                        }
7904                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7905                                ps.readUserState(userId), userId);
7906                        if (ai != null) {
7907                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7908                        }
7909                    } else {
7910                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7911                        // and already converts to externally visible package name
7912                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7913                                callingUid, effectiveFlags, userId);
7914                    }
7915                    if (ai != null) {
7916                        list.add(ai);
7917                    }
7918                }
7919            } else {
7920                list = new ArrayList<>(mPackages.size());
7921                for (PackageParser.Package p : mPackages.values()) {
7922                    if (p.mExtras != null) {
7923                        PackageSetting ps = (PackageSetting) p.mExtras;
7924                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7925                            continue;
7926                        }
7927                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7928                            continue;
7929                        }
7930                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7931                                ps.readUserState(userId), userId);
7932                        if (ai != null) {
7933                            ai.packageName = resolveExternalPackageNameLPr(p);
7934                            list.add(ai);
7935                        }
7936                    }
7937                }
7938            }
7939
7940            return new ParceledListSlice<>(list);
7941        }
7942    }
7943
7944    @Override
7945    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7946        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7947            return null;
7948        }
7949        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7950            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7951                    "getEphemeralApplications");
7952        }
7953        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7954                true /* requireFullPermission */, false /* checkShell */,
7955                "getEphemeralApplications");
7956        synchronized (mPackages) {
7957            List<InstantAppInfo> instantApps = mInstantAppRegistry
7958                    .getInstantAppsLPr(userId);
7959            if (instantApps != null) {
7960                return new ParceledListSlice<>(instantApps);
7961            }
7962        }
7963        return null;
7964    }
7965
7966    @Override
7967    public boolean isInstantApp(String packageName, int userId) {
7968        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7969                true /* requireFullPermission */, false /* checkShell */,
7970                "isInstantApp");
7971        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7972            return false;
7973        }
7974
7975        synchronized (mPackages) {
7976            int callingUid = Binder.getCallingUid();
7977            if (Process.isIsolated(callingUid)) {
7978                callingUid = mIsolatedOwners.get(callingUid);
7979            }
7980            final PackageSetting ps = mSettings.mPackages.get(packageName);
7981            PackageParser.Package pkg = mPackages.get(packageName);
7982            final boolean returnAllowed =
7983                    ps != null
7984                    && (isCallerSameApp(packageName, callingUid)
7985                            || canViewInstantApps(callingUid, userId)
7986                            || mInstantAppRegistry.isInstantAccessGranted(
7987                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7988            if (returnAllowed) {
7989                return ps.getInstantApp(userId);
7990            }
7991        }
7992        return false;
7993    }
7994
7995    @Override
7996    public byte[] getInstantAppCookie(String packageName, int userId) {
7997        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7998            return null;
7999        }
8000
8001        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8002                true /* requireFullPermission */, false /* checkShell */,
8003                "getInstantAppCookie");
8004        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8005            return null;
8006        }
8007        synchronized (mPackages) {
8008            return mInstantAppRegistry.getInstantAppCookieLPw(
8009                    packageName, userId);
8010        }
8011    }
8012
8013    @Override
8014    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8015        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8016            return true;
8017        }
8018
8019        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8020                true /* requireFullPermission */, true /* checkShell */,
8021                "setInstantAppCookie");
8022        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8023            return false;
8024        }
8025        synchronized (mPackages) {
8026            return mInstantAppRegistry.setInstantAppCookieLPw(
8027                    packageName, cookie, userId);
8028        }
8029    }
8030
8031    @Override
8032    public Bitmap getInstantAppIcon(String packageName, int userId) {
8033        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8034            return null;
8035        }
8036
8037        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8038            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8039                    "getInstantAppIcon");
8040        }
8041        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8042                true /* requireFullPermission */, false /* checkShell */,
8043                "getInstantAppIcon");
8044
8045        synchronized (mPackages) {
8046            return mInstantAppRegistry.getInstantAppIconLPw(
8047                    packageName, userId);
8048        }
8049    }
8050
8051    private boolean isCallerSameApp(String packageName, int uid) {
8052        PackageParser.Package pkg = mPackages.get(packageName);
8053        return pkg != null
8054                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8055    }
8056
8057    @Override
8058    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8059        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8060            return ParceledListSlice.emptyList();
8061        }
8062        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8063    }
8064
8065    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8066        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8067
8068        // reader
8069        synchronized (mPackages) {
8070            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8071            final int userId = UserHandle.getCallingUserId();
8072            while (i.hasNext()) {
8073                final PackageParser.Package p = i.next();
8074                if (p.applicationInfo == null) continue;
8075
8076                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8077                        && !p.applicationInfo.isDirectBootAware();
8078                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8079                        && p.applicationInfo.isDirectBootAware();
8080
8081                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8082                        && (!mSafeMode || isSystemApp(p))
8083                        && (matchesUnaware || matchesAware)) {
8084                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8085                    if (ps != null) {
8086                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8087                                ps.readUserState(userId), userId);
8088                        if (ai != null) {
8089                            finalList.add(ai);
8090                        }
8091                    }
8092                }
8093            }
8094        }
8095
8096        return finalList;
8097    }
8098
8099    @Override
8100    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8101        return resolveContentProviderInternal(name, flags, userId);
8102    }
8103
8104    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8105        if (!sUserManager.exists(userId)) return null;
8106        flags = updateFlagsForComponent(flags, userId, name);
8107        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8108        // reader
8109        synchronized (mPackages) {
8110            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8111            PackageSetting ps = provider != null
8112                    ? mSettings.mPackages.get(provider.owner.packageName)
8113                    : null;
8114            if (ps != null) {
8115                final boolean isInstantApp = ps.getInstantApp(userId);
8116                // normal application; filter out instant application provider
8117                if (instantAppPkgName == null && isInstantApp) {
8118                    return null;
8119                }
8120                // instant application; filter out other instant applications
8121                if (instantAppPkgName != null
8122                        && isInstantApp
8123                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8124                    return null;
8125                }
8126                // instant application; filter out non-exposed provider
8127                if (instantAppPkgName != null
8128                        && !isInstantApp
8129                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8130                    return null;
8131                }
8132                // provider not enabled
8133                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8134                    return null;
8135                }
8136                return PackageParser.generateProviderInfo(
8137                        provider, flags, ps.readUserState(userId), userId);
8138            }
8139            return null;
8140        }
8141    }
8142
8143    /**
8144     * @deprecated
8145     */
8146    @Deprecated
8147    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8148        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8149            return;
8150        }
8151        // reader
8152        synchronized (mPackages) {
8153            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8154                    .entrySet().iterator();
8155            final int userId = UserHandle.getCallingUserId();
8156            while (i.hasNext()) {
8157                Map.Entry<String, PackageParser.Provider> entry = i.next();
8158                PackageParser.Provider p = entry.getValue();
8159                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8160
8161                if (ps != null && p.syncable
8162                        && (!mSafeMode || (p.info.applicationInfo.flags
8163                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8164                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8165                            ps.readUserState(userId), userId);
8166                    if (info != null) {
8167                        outNames.add(entry.getKey());
8168                        outInfo.add(info);
8169                    }
8170                }
8171            }
8172        }
8173    }
8174
8175    @Override
8176    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8177            int uid, int flags, String metaDataKey) {
8178        final int callingUid = Binder.getCallingUid();
8179        final int userId = processName != null ? UserHandle.getUserId(uid)
8180                : UserHandle.getCallingUserId();
8181        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8182        flags = updateFlagsForComponent(flags, userId, processName);
8183        ArrayList<ProviderInfo> finalList = null;
8184        // reader
8185        synchronized (mPackages) {
8186            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8187            while (i.hasNext()) {
8188                final PackageParser.Provider p = i.next();
8189                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8190                if (ps != null && p.info.authority != null
8191                        && (processName == null
8192                                || (p.info.processName.equals(processName)
8193                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8194                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8195
8196                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8197                    // parameter.
8198                    if (metaDataKey != null
8199                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8200                        continue;
8201                    }
8202                    final ComponentName component =
8203                            new ComponentName(p.info.packageName, p.info.name);
8204                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8205                        continue;
8206                    }
8207                    if (finalList == null) {
8208                        finalList = new ArrayList<ProviderInfo>(3);
8209                    }
8210                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8211                            ps.readUserState(userId), userId);
8212                    if (info != null) {
8213                        finalList.add(info);
8214                    }
8215                }
8216            }
8217        }
8218
8219        if (finalList != null) {
8220            Collections.sort(finalList, mProviderInitOrderSorter);
8221            return new ParceledListSlice<ProviderInfo>(finalList);
8222        }
8223
8224        return ParceledListSlice.emptyList();
8225    }
8226
8227    @Override
8228    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8229        // reader
8230        synchronized (mPackages) {
8231            final int callingUid = Binder.getCallingUid();
8232            final int callingUserId = UserHandle.getUserId(callingUid);
8233            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8234            if (ps == null) return null;
8235            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8236                return null;
8237            }
8238            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8239            return PackageParser.generateInstrumentationInfo(i, flags);
8240        }
8241    }
8242
8243    @Override
8244    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8245            String targetPackage, int flags) {
8246        final int callingUid = Binder.getCallingUid();
8247        final int callingUserId = UserHandle.getUserId(callingUid);
8248        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8249        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8250            return ParceledListSlice.emptyList();
8251        }
8252        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8253    }
8254
8255    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8256            int flags) {
8257        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8258
8259        // reader
8260        synchronized (mPackages) {
8261            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8262            while (i.hasNext()) {
8263                final PackageParser.Instrumentation p = i.next();
8264                if (targetPackage == null
8265                        || targetPackage.equals(p.info.targetPackage)) {
8266                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8267                            flags);
8268                    if (ii != null) {
8269                        finalList.add(ii);
8270                    }
8271                }
8272            }
8273        }
8274
8275        return finalList;
8276    }
8277
8278    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8279        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8280        try {
8281            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8282        } finally {
8283            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8284        }
8285    }
8286
8287    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8288        final File[] files = scanDir.listFiles();
8289        if (ArrayUtils.isEmpty(files)) {
8290            Log.d(TAG, "No files in app dir " + scanDir);
8291            return;
8292        }
8293
8294        if (DEBUG_PACKAGE_SCANNING) {
8295            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8296                    + " flags=0x" + Integer.toHexString(parseFlags));
8297        }
8298        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8299                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8300                mParallelPackageParserCallback)) {
8301            // Submit files for parsing in parallel
8302            int fileCount = 0;
8303            for (File file : files) {
8304                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8305                        && !PackageInstallerService.isStageName(file.getName());
8306                if (!isPackage) {
8307                    // Ignore entries which are not packages
8308                    continue;
8309                }
8310                parallelPackageParser.submit(file, parseFlags);
8311                fileCount++;
8312            }
8313
8314            // Process results one by one
8315            for (; fileCount > 0; fileCount--) {
8316                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8317                Throwable throwable = parseResult.throwable;
8318                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8319
8320                if (throwable == null) {
8321                    // TODO(toddke): move lower in the scan chain
8322                    // Static shared libraries have synthetic package names
8323                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8324                        renameStaticSharedLibraryPackage(parseResult.pkg);
8325                    }
8326                    try {
8327                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8328                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8329                                    currentTime, null);
8330                        }
8331                    } catch (PackageManagerException e) {
8332                        errorCode = e.error;
8333                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8334                    }
8335                } else if (throwable instanceof PackageParser.PackageParserException) {
8336                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8337                            throwable;
8338                    errorCode = e.error;
8339                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8340                } else {
8341                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8342                            + parseResult.scanFile, throwable);
8343                }
8344
8345                // Delete invalid userdata apps
8346                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8347                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8348                    logCriticalInfo(Log.WARN,
8349                            "Deleting invalid package at " + parseResult.scanFile);
8350                    removeCodePathLI(parseResult.scanFile);
8351                }
8352            }
8353        }
8354    }
8355
8356    public static void reportSettingsProblem(int priority, String msg) {
8357        logCriticalInfo(priority, msg);
8358    }
8359
8360    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8361            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8362        // When upgrading from pre-N MR1, verify the package time stamp using the package
8363        // directory and not the APK file.
8364        final long lastModifiedTime = mIsPreNMR1Upgrade
8365                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8366        if (ps != null && !forceCollect
8367                && ps.codePathString.equals(pkg.codePath)
8368                && ps.timeStamp == lastModifiedTime
8369                && !isCompatSignatureUpdateNeeded(pkg)
8370                && !isRecoverSignatureUpdateNeeded(pkg)) {
8371            if (ps.signatures.mSigningDetails.signatures != null
8372                    && ps.signatures.mSigningDetails.signatures.length != 0
8373                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8374                            != SignatureSchemeVersion.UNKNOWN) {
8375                // Optimization: reuse the existing cached signing data
8376                // if the package appears to be unchanged.
8377                pkg.mSigningDetails =
8378                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8379                return;
8380            }
8381
8382            Slog.w(TAG, "PackageSetting for " + ps.name
8383                    + " is missing signatures.  Collecting certs again to recover them.");
8384        } else {
8385            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8386                    (forceCollect ? " (forced)" : ""));
8387        }
8388
8389        try {
8390            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8391            PackageParser.collectCertificates(pkg, skipVerify);
8392        } catch (PackageParserException e) {
8393            throw PackageManagerException.from(e);
8394        } finally {
8395            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8396        }
8397    }
8398
8399    /**
8400     *  Traces a package scan.
8401     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8402     */
8403    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8404            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8405        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8406        try {
8407            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8408        } finally {
8409            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8410        }
8411    }
8412
8413    /**
8414     *  Scans a package and returns the newly parsed package.
8415     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8416     */
8417    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8418            long currentTime, UserHandle user) throws PackageManagerException {
8419        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8420        PackageParser pp = new PackageParser();
8421        pp.setSeparateProcesses(mSeparateProcesses);
8422        pp.setOnlyCoreApps(mOnlyCore);
8423        pp.setDisplayMetrics(mMetrics);
8424        pp.setCallback(mPackageParserCallback);
8425
8426        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8427        final PackageParser.Package pkg;
8428        try {
8429            pkg = pp.parsePackage(scanFile, parseFlags);
8430        } catch (PackageParserException e) {
8431            throw PackageManagerException.from(e);
8432        } finally {
8433            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8434        }
8435
8436        // Static shared libraries have synthetic package names
8437        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8438            renameStaticSharedLibraryPackage(pkg);
8439        }
8440
8441        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8442    }
8443
8444    /**
8445     *  Scans a package and returns the newly parsed package.
8446     *  @throws PackageManagerException on a parse error.
8447     */
8448    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8449            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8450            @Nullable UserHandle user)
8451                    throws PackageManagerException {
8452        // If the package has children and this is the first dive in the function
8453        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8454        // packages (parent and children) would be successfully scanned before the
8455        // actual scan since scanning mutates internal state and we want to atomically
8456        // install the package and its children.
8457        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8458            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8459                scanFlags |= SCAN_CHECK_ONLY;
8460            }
8461        } else {
8462            scanFlags &= ~SCAN_CHECK_ONLY;
8463        }
8464
8465        // Scan the parent
8466        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8467                scanFlags, currentTime, user);
8468
8469        // Scan the children
8470        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8471        for (int i = 0; i < childCount; i++) {
8472            PackageParser.Package childPackage = pkg.childPackages.get(i);
8473            addForInitLI(childPackage, parseFlags, scanFlags,
8474                    currentTime, user);
8475        }
8476
8477
8478        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8479            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8480        }
8481
8482        return scannedPkg;
8483    }
8484
8485    /**
8486     * Returns if full apk verification can be skipped for the whole package, including the splits.
8487     */
8488    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8489        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8490            return false;
8491        }
8492        // TODO: Allow base and splits to be verified individually.
8493        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8494            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8495                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8496                    return false;
8497                }
8498            }
8499        }
8500        return true;
8501    }
8502
8503    /**
8504     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8505     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8506     * match one in a trusted source, and should be done separately.
8507     */
8508    private boolean canSkipFullApkVerification(String apkPath) {
8509        byte[] rootHashObserved = null;
8510        try {
8511            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8512            if (rootHashObserved == null) {
8513                return false;  // APK does not contain Merkle tree root hash.
8514            }
8515            synchronized (mInstallLock) {
8516                // Returns whether the observed root hash matches what kernel has.
8517                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8518                return true;
8519            }
8520        } catch (InstallerException | IOException | DigestException |
8521                NoSuchAlgorithmException e) {
8522            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8523        }
8524        return false;
8525    }
8526
8527    /**
8528     * Adds a new package to the internal data structures during platform initialization.
8529     * <p>After adding, the package is known to the system and available for querying.
8530     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8531     * etc...], additional checks are performed. Basic verification [such as ensuring
8532     * matching signatures, checking version codes, etc...] occurs if the package is
8533     * identical to a previously known package. If the package fails a signature check,
8534     * the version installed on /data will be removed. If the version of the new package
8535     * is less than or equal than the version on /data, it will be ignored.
8536     * <p>Regardless of the package location, the results are applied to the internal
8537     * structures and the package is made available to the rest of the system.
8538     * <p>NOTE: The return value should be removed. It's the passed in package object.
8539     */
8540    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8541            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8542            @Nullable UserHandle user)
8543                    throws PackageManagerException {
8544        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8545        final String renamedPkgName;
8546        final PackageSetting disabledPkgSetting;
8547        final boolean isSystemPkgUpdated;
8548        final boolean pkgAlreadyExists;
8549        PackageSetting pkgSetting;
8550
8551        // NOTE: installPackageLI() has the same code to setup the package's
8552        // application info. This probably should be done lower in the call
8553        // stack [such as scanPackageOnly()]. However, we verify the application
8554        // info prior to that [in scanPackageNew()] and thus have to setup
8555        // the application info early.
8556        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8557        pkg.setApplicationInfoCodePath(pkg.codePath);
8558        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8559        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8560        pkg.setApplicationInfoResourcePath(pkg.codePath);
8561        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8562        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8563
8564        synchronized (mPackages) {
8565            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8566            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8567            if (realPkgName != null) {
8568                ensurePackageRenamed(pkg, renamedPkgName);
8569            }
8570            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8571            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8572            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8573            pkgAlreadyExists = pkgSetting != null;
8574            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8575            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8576            isSystemPkgUpdated = disabledPkgSetting != null;
8577
8578            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8579                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8580            }
8581
8582            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8583                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8584                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8585                    : null;
8586            if (DEBUG_PACKAGE_SCANNING
8587                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8588                    && sharedUserSetting != null) {
8589                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8590                        + " (uid=" + sharedUserSetting.userId + "):"
8591                        + " packages=" + sharedUserSetting.packages);
8592            }
8593
8594            if (scanSystemPartition) {
8595                // Potentially prune child packages. If the application on the /system
8596                // partition has been updated via OTA, but, is still disabled by a
8597                // version on /data, cycle through all of its children packages and
8598                // remove children that are no longer defined.
8599                if (isSystemPkgUpdated) {
8600                    final int scannedChildCount = (pkg.childPackages != null)
8601                            ? pkg.childPackages.size() : 0;
8602                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8603                            ? disabledPkgSetting.childPackageNames.size() : 0;
8604                    for (int i = 0; i < disabledChildCount; i++) {
8605                        String disabledChildPackageName =
8606                                disabledPkgSetting.childPackageNames.get(i);
8607                        boolean disabledPackageAvailable = false;
8608                        for (int j = 0; j < scannedChildCount; j++) {
8609                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8610                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8611                                disabledPackageAvailable = true;
8612                                break;
8613                            }
8614                        }
8615                        if (!disabledPackageAvailable) {
8616                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8617                        }
8618                    }
8619                    // we're updating the disabled package, so, scan it as the package setting
8620                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8621                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8622                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8623                            (pkg == mPlatformPackage), user);
8624                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8625                }
8626            }
8627        }
8628
8629        final boolean newPkgChangedPaths =
8630                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8631        final boolean newPkgVersionGreater =
8632                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8633        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8634                && newPkgChangedPaths && newPkgVersionGreater;
8635        if (isSystemPkgBetter) {
8636            // The version of the application on /system is greater than the version on
8637            // /data. Switch back to the application on /system.
8638            // It's safe to assume the application on /system will correctly scan. If not,
8639            // there won't be a working copy of the application.
8640            synchronized (mPackages) {
8641                // just remove the loaded entries from package lists
8642                mPackages.remove(pkgSetting.name);
8643            }
8644
8645            logCriticalInfo(Log.WARN,
8646                    "System package updated;"
8647                    + " name: " + pkgSetting.name
8648                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8649                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8650
8651            final InstallArgs args = createInstallArgsForExisting(
8652                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8653                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8654            args.cleanUpResourcesLI();
8655            synchronized (mPackages) {
8656                mSettings.enableSystemPackageLPw(pkgSetting.name);
8657            }
8658        }
8659
8660        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8661            // The version of the application on the /system partition is less than or
8662            // equal to the version on the /data partition. Throw an exception and use
8663            // the application already installed on the /data partition.
8664            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8665                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8666                    + " better than this " + pkg.getLongVersionCode());
8667        }
8668
8669        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8670        // force re-collecting certificate.
8671        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8672                disabledPkgSetting);
8673        // Full APK verification can be skipped during certificate collection, only if the file is
8674        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8675        // cases, only data in Signing Block is verified instead of the whole file.
8676        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8677                (forceCollect && canSkipFullPackageVerification(pkg));
8678        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8679
8680        boolean shouldHideSystemApp = false;
8681        // A new application appeared on /system, but, we already have a copy of
8682        // the application installed on /data.
8683        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8684                && !pkgSetting.isSystem()) {
8685
8686            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8687                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8688                logCriticalInfo(Log.WARN,
8689                        "System package signature mismatch;"
8690                        + " name: " + pkgSetting.name);
8691                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8692                        "scanPackageInternalLI")) {
8693                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8694                }
8695                pkgSetting = null;
8696            } else if (newPkgVersionGreater) {
8697                // The application on /system is newer than the application on /data.
8698                // Simply remove the application on /data [keeping application data]
8699                // and replace it with the version on /system.
8700                logCriticalInfo(Log.WARN,
8701                        "System package enabled;"
8702                        + " name: " + pkgSetting.name
8703                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8704                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8705                InstallArgs args = createInstallArgsForExisting(
8706                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8707                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8708                synchronized (mInstallLock) {
8709                    args.cleanUpResourcesLI();
8710                }
8711            } else {
8712                // The application on /system is older than the application on /data. Hide
8713                // the application on /system and the version on /data will be scanned later
8714                // and re-added like an update.
8715                shouldHideSystemApp = true;
8716                logCriticalInfo(Log.INFO,
8717                        "System package disabled;"
8718                        + " name: " + pkgSetting.name
8719                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8720                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8721            }
8722        }
8723
8724        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8725                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8726
8727        if (shouldHideSystemApp) {
8728            synchronized (mPackages) {
8729                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8730            }
8731        }
8732        return scannedPkg;
8733    }
8734
8735    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8736        // Derive the new package synthetic package name
8737        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8738                + pkg.staticSharedLibVersion);
8739    }
8740
8741    private static String fixProcessName(String defProcessName,
8742            String processName) {
8743        if (processName == null) {
8744            return defProcessName;
8745        }
8746        return processName;
8747    }
8748
8749    /**
8750     * Enforces that only the system UID or root's UID can call a method exposed
8751     * via Binder.
8752     *
8753     * @param message used as message if SecurityException is thrown
8754     * @throws SecurityException if the caller is not system or root
8755     */
8756    private static final void enforceSystemOrRoot(String message) {
8757        final int uid = Binder.getCallingUid();
8758        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8759            throw new SecurityException(message);
8760        }
8761    }
8762
8763    @Override
8764    public void performFstrimIfNeeded() {
8765        enforceSystemOrRoot("Only the system can request fstrim");
8766
8767        // Before everything else, see whether we need to fstrim.
8768        try {
8769            IStorageManager sm = PackageHelper.getStorageManager();
8770            if (sm != null) {
8771                boolean doTrim = false;
8772                final long interval = android.provider.Settings.Global.getLong(
8773                        mContext.getContentResolver(),
8774                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8775                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8776                if (interval > 0) {
8777                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8778                    if (timeSinceLast > interval) {
8779                        doTrim = true;
8780                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8781                                + "; running immediately");
8782                    }
8783                }
8784                if (doTrim) {
8785                    final boolean dexOptDialogShown;
8786                    synchronized (mPackages) {
8787                        dexOptDialogShown = mDexOptDialogShown;
8788                    }
8789                    if (!isFirstBoot() && dexOptDialogShown) {
8790                        try {
8791                            ActivityManager.getService().showBootMessage(
8792                                    mContext.getResources().getString(
8793                                            R.string.android_upgrading_fstrim), true);
8794                        } catch (RemoteException e) {
8795                        }
8796                    }
8797                    sm.runMaintenance();
8798                }
8799            } else {
8800                Slog.e(TAG, "storageManager service unavailable!");
8801            }
8802        } catch (RemoteException e) {
8803            // Can't happen; StorageManagerService is local
8804        }
8805    }
8806
8807    @Override
8808    public void updatePackagesIfNeeded() {
8809        enforceSystemOrRoot("Only the system can request package update");
8810
8811        // We need to re-extract after an OTA.
8812        boolean causeUpgrade = isUpgrade();
8813
8814        // First boot or factory reset.
8815        // Note: we also handle devices that are upgrading to N right now as if it is their
8816        //       first boot, as they do not have profile data.
8817        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8818
8819        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8820        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8821
8822        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8823            return;
8824        }
8825
8826        List<PackageParser.Package> pkgs;
8827        synchronized (mPackages) {
8828            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8829        }
8830
8831        final long startTime = System.nanoTime();
8832        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8833                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8834                    false /* bootComplete */);
8835
8836        final int elapsedTimeSeconds =
8837                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8838
8839        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8840        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8841        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8842        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8843        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8844    }
8845
8846    /*
8847     * Return the prebuilt profile path given a package base code path.
8848     */
8849    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8850        return pkg.baseCodePath + ".prof";
8851    }
8852
8853    /**
8854     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8855     * containing statistics about the invocation. The array consists of three elements,
8856     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8857     * and {@code numberOfPackagesFailed}.
8858     */
8859    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8860            final String compilerFilter, boolean bootComplete) {
8861
8862        int numberOfPackagesVisited = 0;
8863        int numberOfPackagesOptimized = 0;
8864        int numberOfPackagesSkipped = 0;
8865        int numberOfPackagesFailed = 0;
8866        final int numberOfPackagesToDexopt = pkgs.size();
8867
8868        for (PackageParser.Package pkg : pkgs) {
8869            numberOfPackagesVisited++;
8870
8871            boolean useProfileForDexopt = false;
8872
8873            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8874                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8875                // that are already compiled.
8876                File profileFile = new File(getPrebuildProfilePath(pkg));
8877                // Copy profile if it exists.
8878                if (profileFile.exists()) {
8879                    try {
8880                        // We could also do this lazily before calling dexopt in
8881                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8882                        // is that we don't have a good way to say "do this only once".
8883                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8884                                pkg.applicationInfo.uid, pkg.packageName,
8885                                ArtManager.getProfileName(null))) {
8886                            Log.e(TAG, "Installer failed to copy system profile!");
8887                        } else {
8888                            // Disabled as this causes speed-profile compilation during first boot
8889                            // even if things are already compiled.
8890                            // useProfileForDexopt = true;
8891                        }
8892                    } catch (Exception e) {
8893                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8894                                e);
8895                    }
8896                } else {
8897                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8898                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8899                    // minimize the number off apps being speed-profile compiled during first boot.
8900                    // The other paths will not change the filter.
8901                    if (disabledPs != null && disabledPs.pkg.isStub) {
8902                        // The package is the stub one, remove the stub suffix to get the normal
8903                        // package and APK names.
8904                        String systemProfilePath =
8905                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8906                        profileFile = new File(systemProfilePath);
8907                        // If we have a profile for a compressed APK, copy it to the reference
8908                        // location.
8909                        // Note that copying the profile here will cause it to override the
8910                        // reference profile every OTA even though the existing reference profile
8911                        // may have more data. We can't copy during decompression since the
8912                        // directories are not set up at that point.
8913                        if (profileFile.exists()) {
8914                            try {
8915                                // We could also do this lazily before calling dexopt in
8916                                // PackageDexOptimizer to prevent this happening on first boot. The
8917                                // issue is that we don't have a good way to say "do this only
8918                                // once".
8919                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8920                                        pkg.applicationInfo.uid, pkg.packageName,
8921                                        ArtManager.getProfileName(null))) {
8922                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8923                                } else {
8924                                    useProfileForDexopt = true;
8925                                }
8926                            } catch (Exception e) {
8927                                Log.e(TAG, "Failed to copy profile " +
8928                                        profileFile.getAbsolutePath() + " ", e);
8929                            }
8930                        }
8931                    }
8932                }
8933            }
8934
8935            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8936                if (DEBUG_DEXOPT) {
8937                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8938                }
8939                numberOfPackagesSkipped++;
8940                continue;
8941            }
8942
8943            if (DEBUG_DEXOPT) {
8944                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8945                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8946            }
8947
8948            if (showDialog) {
8949                try {
8950                    ActivityManager.getService().showBootMessage(
8951                            mContext.getResources().getString(R.string.android_upgrading_apk,
8952                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8953                } catch (RemoteException e) {
8954                }
8955                synchronized (mPackages) {
8956                    mDexOptDialogShown = true;
8957                }
8958            }
8959
8960            String pkgCompilerFilter = compilerFilter;
8961            if (useProfileForDexopt) {
8962                // Use background dexopt mode to try and use the profile. Note that this does not
8963                // guarantee usage of the profile.
8964                pkgCompilerFilter =
8965                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8966                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8967            }
8968
8969            // checkProfiles is false to avoid merging profiles during boot which
8970            // might interfere with background compilation (b/28612421).
8971            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8972            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8973            // trade-off worth doing to save boot time work.
8974            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8975            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8976                    pkg.packageName,
8977                    pkgCompilerFilter,
8978                    dexoptFlags));
8979
8980            switch (primaryDexOptStaus) {
8981                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8982                    numberOfPackagesOptimized++;
8983                    break;
8984                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8985                    numberOfPackagesSkipped++;
8986                    break;
8987                case PackageDexOptimizer.DEX_OPT_FAILED:
8988                    numberOfPackagesFailed++;
8989                    break;
8990                default:
8991                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8992                    break;
8993            }
8994        }
8995
8996        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8997                numberOfPackagesFailed };
8998    }
8999
9000    @Override
9001    public void notifyPackageUse(String packageName, int reason) {
9002        synchronized (mPackages) {
9003            final int callingUid = Binder.getCallingUid();
9004            final int callingUserId = UserHandle.getUserId(callingUid);
9005            if (getInstantAppPackageName(callingUid) != null) {
9006                if (!isCallerSameApp(packageName, callingUid)) {
9007                    return;
9008                }
9009            } else {
9010                if (isInstantApp(packageName, callingUserId)) {
9011                    return;
9012                }
9013            }
9014            notifyPackageUseLocked(packageName, reason);
9015        }
9016    }
9017
9018    private void notifyPackageUseLocked(String packageName, int reason) {
9019        final PackageParser.Package p = mPackages.get(packageName);
9020        if (p == null) {
9021            return;
9022        }
9023        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9024    }
9025
9026    @Override
9027    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9028            List<String> classPaths, String loaderIsa) {
9029        int userId = UserHandle.getCallingUserId();
9030        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9031        if (ai == null) {
9032            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9033                + loadingPackageName + ", user=" + userId);
9034            return;
9035        }
9036        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9037    }
9038
9039    @Override
9040    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9041            IDexModuleRegisterCallback callback) {
9042        int userId = UserHandle.getCallingUserId();
9043        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9044        DexManager.RegisterDexModuleResult result;
9045        if (ai == null) {
9046            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9047                     " calling user. package=" + packageName + ", user=" + userId);
9048            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9049        } else {
9050            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9051        }
9052
9053        if (callback != null) {
9054            mHandler.post(() -> {
9055                try {
9056                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9057                } catch (RemoteException e) {
9058                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9059                }
9060            });
9061        }
9062    }
9063
9064    /**
9065     * Ask the package manager to perform a dex-opt with the given compiler filter.
9066     *
9067     * Note: exposed only for the shell command to allow moving packages explicitly to a
9068     *       definite state.
9069     */
9070    @Override
9071    public boolean performDexOptMode(String packageName,
9072            boolean checkProfiles, String targetCompilerFilter, boolean force,
9073            boolean bootComplete, String splitName) {
9074        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9075                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9076                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9077        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9078                splitName, flags));
9079    }
9080
9081    /**
9082     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9083     * secondary dex files belonging to the given package.
9084     *
9085     * Note: exposed only for the shell command to allow moving packages explicitly to a
9086     *       definite state.
9087     */
9088    @Override
9089    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9090            boolean force) {
9091        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9092                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9093                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9094                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9095        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9096    }
9097
9098    /*package*/ boolean performDexOpt(DexoptOptions options) {
9099        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9100            return false;
9101        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9102            return false;
9103        }
9104
9105        if (options.isDexoptOnlySecondaryDex()) {
9106            return mDexManager.dexoptSecondaryDex(options);
9107        } else {
9108            int dexoptStatus = performDexOptWithStatus(options);
9109            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9110        }
9111    }
9112
9113    /**
9114     * Perform dexopt on the given package and return one of following result:
9115     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9116     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9117     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9118     */
9119    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9120        return performDexOptTraced(options);
9121    }
9122
9123    private int performDexOptTraced(DexoptOptions options) {
9124        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9125        try {
9126            return performDexOptInternal(options);
9127        } finally {
9128            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9129        }
9130    }
9131
9132    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9133    // if the package can now be considered up to date for the given filter.
9134    private int performDexOptInternal(DexoptOptions options) {
9135        PackageParser.Package p;
9136        synchronized (mPackages) {
9137            p = mPackages.get(options.getPackageName());
9138            if (p == null) {
9139                // Package could not be found. Report failure.
9140                return PackageDexOptimizer.DEX_OPT_FAILED;
9141            }
9142            mPackageUsage.maybeWriteAsync(mPackages);
9143            mCompilerStats.maybeWriteAsync();
9144        }
9145        long callingId = Binder.clearCallingIdentity();
9146        try {
9147            synchronized (mInstallLock) {
9148                return performDexOptInternalWithDependenciesLI(p, options);
9149            }
9150        } finally {
9151            Binder.restoreCallingIdentity(callingId);
9152        }
9153    }
9154
9155    public ArraySet<String> getOptimizablePackages() {
9156        ArraySet<String> pkgs = new ArraySet<String>();
9157        synchronized (mPackages) {
9158            for (PackageParser.Package p : mPackages.values()) {
9159                if (PackageDexOptimizer.canOptimizePackage(p)) {
9160                    pkgs.add(p.packageName);
9161                }
9162            }
9163        }
9164        return pkgs;
9165    }
9166
9167    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9168            DexoptOptions options) {
9169        // Select the dex optimizer based on the force parameter.
9170        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9171        //       allocate an object here.
9172        PackageDexOptimizer pdo = options.isForce()
9173                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9174                : mPackageDexOptimizer;
9175
9176        // Dexopt all dependencies first. Note: we ignore the return value and march on
9177        // on errors.
9178        // Note that we are going to call performDexOpt on those libraries as many times as
9179        // they are referenced in packages. When we do a batch of performDexOpt (for example
9180        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9181        // and the first package that uses the library will dexopt it. The
9182        // others will see that the compiled code for the library is up to date.
9183        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9184        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9185        if (!deps.isEmpty()) {
9186            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9187                    options.getCompilerFilter(), options.getSplitName(),
9188                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9189            for (PackageParser.Package depPackage : deps) {
9190                // TODO: Analyze and investigate if we (should) profile libraries.
9191                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9192                        getOrCreateCompilerPackageStats(depPackage),
9193                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9194            }
9195        }
9196        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9197                getOrCreateCompilerPackageStats(p),
9198                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9199    }
9200
9201    /**
9202     * Reconcile the information we have about the secondary dex files belonging to
9203     * {@code packagName} and the actual dex files. For all dex files that were
9204     * deleted, update the internal records and delete the generated oat files.
9205     */
9206    @Override
9207    public void reconcileSecondaryDexFiles(String packageName) {
9208        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9209            return;
9210        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9211            return;
9212        }
9213        mDexManager.reconcileSecondaryDexFiles(packageName);
9214    }
9215
9216    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9217    // a reference there.
9218    /*package*/ DexManager getDexManager() {
9219        return mDexManager;
9220    }
9221
9222    /**
9223     * Execute the background dexopt job immediately.
9224     */
9225    @Override
9226    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9227        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9228            return false;
9229        }
9230        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9231    }
9232
9233    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9234        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9235                || p.usesStaticLibraries != null) {
9236            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9237            Set<String> collectedNames = new HashSet<>();
9238            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9239
9240            retValue.remove(p);
9241
9242            return retValue;
9243        } else {
9244            return Collections.emptyList();
9245        }
9246    }
9247
9248    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9249            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9250        if (!collectedNames.contains(p.packageName)) {
9251            collectedNames.add(p.packageName);
9252            collected.add(p);
9253
9254            if (p.usesLibraries != null) {
9255                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9256                        null, collected, collectedNames);
9257            }
9258            if (p.usesOptionalLibraries != null) {
9259                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9260                        null, collected, collectedNames);
9261            }
9262            if (p.usesStaticLibraries != null) {
9263                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9264                        p.usesStaticLibrariesVersions, collected, collectedNames);
9265            }
9266        }
9267    }
9268
9269    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9270            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9271        final int libNameCount = libs.size();
9272        for (int i = 0; i < libNameCount; i++) {
9273            String libName = libs.get(i);
9274            long version = (versions != null && versions.length == libNameCount)
9275                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9276            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9277            if (libPkg != null) {
9278                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9279            }
9280        }
9281    }
9282
9283    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9284        synchronized (mPackages) {
9285            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9286            if (libEntry != null) {
9287                return mPackages.get(libEntry.apk);
9288            }
9289            return null;
9290        }
9291    }
9292
9293    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9294        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9295        if (versionedLib == null) {
9296            return null;
9297        }
9298        return versionedLib.get(version);
9299    }
9300
9301    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9302        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9303                pkg.staticSharedLibName);
9304        if (versionedLib == null) {
9305            return null;
9306        }
9307        long previousLibVersion = -1;
9308        final int versionCount = versionedLib.size();
9309        for (int i = 0; i < versionCount; i++) {
9310            final long libVersion = versionedLib.keyAt(i);
9311            if (libVersion < pkg.staticSharedLibVersion) {
9312                previousLibVersion = Math.max(previousLibVersion, libVersion);
9313            }
9314        }
9315        if (previousLibVersion >= 0) {
9316            return versionedLib.get(previousLibVersion);
9317        }
9318        return null;
9319    }
9320
9321    public void shutdown() {
9322        mPackageUsage.writeNow(mPackages);
9323        mCompilerStats.writeNow();
9324        mDexManager.writePackageDexUsageNow();
9325    }
9326
9327    @Override
9328    public void dumpProfiles(String packageName) {
9329        PackageParser.Package pkg;
9330        synchronized (mPackages) {
9331            pkg = mPackages.get(packageName);
9332            if (pkg == null) {
9333                throw new IllegalArgumentException("Unknown package: " + packageName);
9334            }
9335        }
9336        /* Only the shell, root, or the app user should be able to dump profiles. */
9337        int callingUid = Binder.getCallingUid();
9338        if (callingUid != Process.SHELL_UID &&
9339            callingUid != Process.ROOT_UID &&
9340            callingUid != pkg.applicationInfo.uid) {
9341            throw new SecurityException("dumpProfiles");
9342        }
9343
9344        synchronized (mInstallLock) {
9345            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9346            mArtManagerService.dumpProfiles(pkg);
9347            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9348        }
9349    }
9350
9351    @Override
9352    public void forceDexOpt(String packageName) {
9353        enforceSystemOrRoot("forceDexOpt");
9354
9355        PackageParser.Package pkg;
9356        synchronized (mPackages) {
9357            pkg = mPackages.get(packageName);
9358            if (pkg == null) {
9359                throw new IllegalArgumentException("Unknown package: " + packageName);
9360            }
9361        }
9362
9363        synchronized (mInstallLock) {
9364            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9365
9366            // Whoever is calling forceDexOpt wants a compiled package.
9367            // Don't use profiles since that may cause compilation to be skipped.
9368            final int res = performDexOptInternalWithDependenciesLI(
9369                    pkg,
9370                    new DexoptOptions(packageName,
9371                            getDefaultCompilerFilter(),
9372                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9373
9374            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9375            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9376                throw new IllegalStateException("Failed to dexopt: " + res);
9377            }
9378        }
9379    }
9380
9381    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9382        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9383            Slog.w(TAG, "Unable to update from " + oldPkg.name
9384                    + " to " + newPkg.packageName
9385                    + ": old package not in system partition");
9386            return false;
9387        } else if (mPackages.get(oldPkg.name) != null) {
9388            Slog.w(TAG, "Unable to update from " + oldPkg.name
9389                    + " to " + newPkg.packageName
9390                    + ": old package still exists");
9391            return false;
9392        }
9393        return true;
9394    }
9395
9396    void removeCodePathLI(File codePath) {
9397        if (codePath.isDirectory()) {
9398            try {
9399                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9400            } catch (InstallerException e) {
9401                Slog.w(TAG, "Failed to remove code path", e);
9402            }
9403        } else {
9404            codePath.delete();
9405        }
9406    }
9407
9408    private int[] resolveUserIds(int userId) {
9409        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9410    }
9411
9412    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9413        if (pkg == null) {
9414            Slog.wtf(TAG, "Package was null!", new Throwable());
9415            return;
9416        }
9417        clearAppDataLeafLIF(pkg, userId, flags);
9418        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9419        for (int i = 0; i < childCount; i++) {
9420            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9421        }
9422
9423        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9424    }
9425
9426    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9427        final PackageSetting ps;
9428        synchronized (mPackages) {
9429            ps = mSettings.mPackages.get(pkg.packageName);
9430        }
9431        for (int realUserId : resolveUserIds(userId)) {
9432            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9433            try {
9434                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9435                        ceDataInode);
9436            } catch (InstallerException e) {
9437                Slog.w(TAG, String.valueOf(e));
9438            }
9439        }
9440    }
9441
9442    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9443        if (pkg == null) {
9444            Slog.wtf(TAG, "Package was null!", new Throwable());
9445            return;
9446        }
9447        destroyAppDataLeafLIF(pkg, userId, flags);
9448        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9449        for (int i = 0; i < childCount; i++) {
9450            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9451        }
9452    }
9453
9454    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9455        final PackageSetting ps;
9456        synchronized (mPackages) {
9457            ps = mSettings.mPackages.get(pkg.packageName);
9458        }
9459        for (int realUserId : resolveUserIds(userId)) {
9460            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9461            try {
9462                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9463                        ceDataInode);
9464            } catch (InstallerException e) {
9465                Slog.w(TAG, String.valueOf(e));
9466            }
9467            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9468        }
9469    }
9470
9471    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9472        if (pkg == null) {
9473            Slog.wtf(TAG, "Package was null!", new Throwable());
9474            return;
9475        }
9476        destroyAppProfilesLeafLIF(pkg);
9477        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9478        for (int i = 0; i < childCount; i++) {
9479            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9480        }
9481    }
9482
9483    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9484        try {
9485            mInstaller.destroyAppProfiles(pkg.packageName);
9486        } catch (InstallerException e) {
9487            Slog.w(TAG, String.valueOf(e));
9488        }
9489    }
9490
9491    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9492        if (pkg == null) {
9493            Slog.wtf(TAG, "Package was null!", new Throwable());
9494            return;
9495        }
9496        mArtManagerService.clearAppProfiles(pkg);
9497        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9498        for (int i = 0; i < childCount; i++) {
9499            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9500        }
9501    }
9502
9503    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9504            long lastUpdateTime) {
9505        // Set parent install/update time
9506        PackageSetting ps = (PackageSetting) pkg.mExtras;
9507        if (ps != null) {
9508            ps.firstInstallTime = firstInstallTime;
9509            ps.lastUpdateTime = lastUpdateTime;
9510        }
9511        // Set children install/update time
9512        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9513        for (int i = 0; i < childCount; i++) {
9514            PackageParser.Package childPkg = pkg.childPackages.get(i);
9515            ps = (PackageSetting) childPkg.mExtras;
9516            if (ps != null) {
9517                ps.firstInstallTime = firstInstallTime;
9518                ps.lastUpdateTime = lastUpdateTime;
9519            }
9520        }
9521    }
9522
9523    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9524            SharedLibraryEntry file,
9525            PackageParser.Package changingLib) {
9526        if (file.path != null) {
9527            usesLibraryFiles.add(file.path);
9528            return;
9529        }
9530        PackageParser.Package p = mPackages.get(file.apk);
9531        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9532            // If we are doing this while in the middle of updating a library apk,
9533            // then we need to make sure to use that new apk for determining the
9534            // dependencies here.  (We haven't yet finished committing the new apk
9535            // to the package manager state.)
9536            if (p == null || p.packageName.equals(changingLib.packageName)) {
9537                p = changingLib;
9538            }
9539        }
9540        if (p != null) {
9541            usesLibraryFiles.addAll(p.getAllCodePaths());
9542            if (p.usesLibraryFiles != null) {
9543                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9544            }
9545        }
9546    }
9547
9548    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9549            PackageParser.Package changingLib) throws PackageManagerException {
9550        if (pkg == null) {
9551            return;
9552        }
9553        // The collection used here must maintain the order of addition (so
9554        // that libraries are searched in the correct order) and must have no
9555        // duplicates.
9556        Set<String> usesLibraryFiles = null;
9557        if (pkg.usesLibraries != null) {
9558            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9559                    null, null, pkg.packageName, changingLib, true,
9560                    pkg.applicationInfo.targetSdkVersion, null);
9561        }
9562        if (pkg.usesStaticLibraries != null) {
9563            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9564                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9565                    pkg.packageName, changingLib, true,
9566                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9567        }
9568        if (pkg.usesOptionalLibraries != null) {
9569            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9570                    null, null, pkg.packageName, changingLib, false,
9571                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9572        }
9573        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9574            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9575        } else {
9576            pkg.usesLibraryFiles = null;
9577        }
9578    }
9579
9580    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9581            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9582            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9583            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9584            throws PackageManagerException {
9585        final int libCount = requestedLibraries.size();
9586        for (int i = 0; i < libCount; i++) {
9587            final String libName = requestedLibraries.get(i);
9588            final long libVersion = requiredVersions != null ? requiredVersions[i]
9589                    : SharedLibraryInfo.VERSION_UNDEFINED;
9590            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9591            if (libEntry == null) {
9592                if (required) {
9593                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9594                            "Package " + packageName + " requires unavailable shared library "
9595                                    + libName + "; failing!");
9596                } else if (DEBUG_SHARED_LIBRARIES) {
9597                    Slog.i(TAG, "Package " + packageName
9598                            + " desires unavailable shared library "
9599                            + libName + "; ignoring!");
9600                }
9601            } else {
9602                if (requiredVersions != null && requiredCertDigests != null) {
9603                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9604                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9605                            "Package " + packageName + " requires unavailable static shared"
9606                                    + " library " + libName + " version "
9607                                    + libEntry.info.getLongVersion() + "; failing!");
9608                    }
9609
9610                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9611                    if (libPkg == null) {
9612                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9613                                "Package " + packageName + " requires unavailable static shared"
9614                                        + " library; failing!");
9615                    }
9616
9617                    final String[] expectedCertDigests = requiredCertDigests[i];
9618
9619
9620                    if (expectedCertDigests.length > 1) {
9621
9622                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9623                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9624                                ? PackageUtils.computeSignaturesSha256Digests(
9625                                libPkg.mSigningDetails.signatures)
9626                                : PackageUtils.computeSignaturesSha256Digests(
9627                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9628
9629                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9630                        // target O we don't parse the "additional-certificate" tags similarly
9631                        // how we only consider all certs only for apps targeting O (see above).
9632                        // Therefore, the size check is safe to make.
9633                        if (expectedCertDigests.length != libCertDigests.length) {
9634                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9635                                    "Package " + packageName + " requires differently signed" +
9636                                            " static shared library; failing!");
9637                        }
9638
9639                        // Use a predictable order as signature order may vary
9640                        Arrays.sort(libCertDigests);
9641                        Arrays.sort(expectedCertDigests);
9642
9643                        final int certCount = libCertDigests.length;
9644                        for (int j = 0; j < certCount; j++) {
9645                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9646                                throw new PackageManagerException(
9647                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9648                                        "Package " + packageName + " requires differently signed" +
9649                                                " static shared library; failing!");
9650                            }
9651                        }
9652                    } else {
9653
9654                        // lib signing cert could have rotated beyond the one expected, check to see
9655                        // if the new one has been blessed by the old
9656                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9657                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9658                            throw new PackageManagerException(
9659                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9660                                    "Package " + packageName + " requires differently signed" +
9661                                            " static shared library; failing!");
9662                        }
9663                    }
9664                }
9665
9666                if (outUsedLibraries == null) {
9667                    // Use LinkedHashSet to preserve the order of files added to
9668                    // usesLibraryFiles while eliminating duplicates.
9669                    outUsedLibraries = new LinkedHashSet<>();
9670                }
9671                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9672            }
9673        }
9674        return outUsedLibraries;
9675    }
9676
9677    private static boolean hasString(List<String> list, List<String> which) {
9678        if (list == null) {
9679            return false;
9680        }
9681        for (int i=list.size()-1; i>=0; i--) {
9682            for (int j=which.size()-1; j>=0; j--) {
9683                if (which.get(j).equals(list.get(i))) {
9684                    return true;
9685                }
9686            }
9687        }
9688        return false;
9689    }
9690
9691    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9692            PackageParser.Package changingPkg) {
9693        ArrayList<PackageParser.Package> res = null;
9694        for (PackageParser.Package pkg : mPackages.values()) {
9695            if (changingPkg != null
9696                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9697                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9698                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9699                            changingPkg.staticSharedLibName)) {
9700                return null;
9701            }
9702            if (res == null) {
9703                res = new ArrayList<>();
9704            }
9705            res.add(pkg);
9706            try {
9707                updateSharedLibrariesLPr(pkg, changingPkg);
9708            } catch (PackageManagerException e) {
9709                // If a system app update or an app and a required lib missing we
9710                // delete the package and for updated system apps keep the data as
9711                // it is better for the user to reinstall than to be in an limbo
9712                // state. Also libs disappearing under an app should never happen
9713                // - just in case.
9714                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9715                    final int flags = pkg.isUpdatedSystemApp()
9716                            ? PackageManager.DELETE_KEEP_DATA : 0;
9717                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9718                            flags , null, true, null);
9719                }
9720                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9721            }
9722        }
9723        return res;
9724    }
9725
9726    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9727            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9728            @Nullable UserHandle user) throws PackageManagerException {
9729        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9730        // If the package has children and this is the first dive in the function
9731        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9732        // whether all packages (parent and children) would be successfully scanned
9733        // before the actual scan since scanning mutates internal state and we want
9734        // to atomically install the package and its children.
9735        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9736            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9737                scanFlags |= SCAN_CHECK_ONLY;
9738            }
9739        } else {
9740            scanFlags &= ~SCAN_CHECK_ONLY;
9741        }
9742
9743        final PackageParser.Package scannedPkg;
9744        try {
9745            // Scan the parent
9746            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9747            // Scan the children
9748            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9749            for (int i = 0; i < childCount; i++) {
9750                PackageParser.Package childPkg = pkg.childPackages.get(i);
9751                scanPackageNewLI(childPkg, parseFlags,
9752                        scanFlags, currentTime, user);
9753            }
9754        } finally {
9755            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9756        }
9757
9758        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9759            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9760        }
9761
9762        return scannedPkg;
9763    }
9764
9765    /** The result of a package scan. */
9766    private static class ScanResult {
9767        /** Whether or not the package scan was successful */
9768        public final boolean success;
9769        /**
9770         * The final package settings. This may be the same object passed in
9771         * the {@link ScanRequest}, but, with modified values.
9772         */
9773        @Nullable public final PackageSetting pkgSetting;
9774        /** ABI code paths that have changed in the package scan */
9775        @Nullable public final List<String> changedAbiCodePath;
9776        public ScanResult(
9777                boolean success,
9778                @Nullable PackageSetting pkgSetting,
9779                @Nullable List<String> changedAbiCodePath) {
9780            this.success = success;
9781            this.pkgSetting = pkgSetting;
9782            this.changedAbiCodePath = changedAbiCodePath;
9783        }
9784    }
9785
9786    /** A package to be scanned */
9787    private static class ScanRequest {
9788        /** The parsed package */
9789        @NonNull public final PackageParser.Package pkg;
9790        /** Shared user settings, if the package has a shared user */
9791        @Nullable public final SharedUserSetting sharedUserSetting;
9792        /**
9793         * Package settings of the currently installed version.
9794         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9795         * during scan.
9796         */
9797        @Nullable public final PackageSetting pkgSetting;
9798        /** A copy of the settings for the currently installed version */
9799        @Nullable public final PackageSetting oldPkgSetting;
9800        /** Package settings for the disabled version on the /system partition */
9801        @Nullable public final PackageSetting disabledPkgSetting;
9802        /** Package settings for the installed version under its original package name */
9803        @Nullable public final PackageSetting originalPkgSetting;
9804        /** The real package name of a renamed application */
9805        @Nullable public final String realPkgName;
9806        public final @ParseFlags int parseFlags;
9807        public final @ScanFlags int scanFlags;
9808        /** The user for which the package is being scanned */
9809        @Nullable public final UserHandle user;
9810        /** Whether or not the platform package is being scanned */
9811        public final boolean isPlatformPackage;
9812        public ScanRequest(
9813                @NonNull PackageParser.Package pkg,
9814                @Nullable SharedUserSetting sharedUserSetting,
9815                @Nullable PackageSetting pkgSetting,
9816                @Nullable PackageSetting disabledPkgSetting,
9817                @Nullable PackageSetting originalPkgSetting,
9818                @Nullable String realPkgName,
9819                @ParseFlags int parseFlags,
9820                @ScanFlags int scanFlags,
9821                boolean isPlatformPackage,
9822                @Nullable UserHandle user) {
9823            this.pkg = pkg;
9824            this.pkgSetting = pkgSetting;
9825            this.sharedUserSetting = sharedUserSetting;
9826            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9827            this.disabledPkgSetting = disabledPkgSetting;
9828            this.originalPkgSetting = originalPkgSetting;
9829            this.realPkgName = realPkgName;
9830            this.parseFlags = parseFlags;
9831            this.scanFlags = scanFlags;
9832            this.isPlatformPackage = isPlatformPackage;
9833            this.user = user;
9834        }
9835    }
9836
9837    /**
9838     * Returns the actual scan flags depending upon the state of the other settings.
9839     * <p>Updated system applications will not have the following flags set
9840     * by default and need to be adjusted after the fact:
9841     * <ul>
9842     * <li>{@link #SCAN_AS_SYSTEM}</li>
9843     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9844     * <li>{@link #SCAN_AS_OEM}</li>
9845     * <li>{@link #SCAN_AS_VENDOR}</li>
9846     * <li>{@link #SCAN_AS_PRODUCT}</li>
9847     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9848     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9849     * </ul>
9850     */
9851    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9852            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9853            PackageParser.Package pkg) {
9854        if (disabledPkgSetting != null) {
9855            // updated system application, must at least have SCAN_AS_SYSTEM
9856            scanFlags |= SCAN_AS_SYSTEM;
9857            if ((disabledPkgSetting.pkgPrivateFlags
9858                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9859                scanFlags |= SCAN_AS_PRIVILEGED;
9860            }
9861            if ((disabledPkgSetting.pkgPrivateFlags
9862                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9863                scanFlags |= SCAN_AS_OEM;
9864            }
9865            if ((disabledPkgSetting.pkgPrivateFlags
9866                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9867                scanFlags |= SCAN_AS_VENDOR;
9868            }
9869            if ((disabledPkgSetting.pkgPrivateFlags
9870                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9871                scanFlags |= SCAN_AS_PRODUCT;
9872            }
9873        }
9874        if (pkgSetting != null) {
9875            final int userId = ((user == null) ? 0 : user.getIdentifier());
9876            if (pkgSetting.getInstantApp(userId)) {
9877                scanFlags |= SCAN_AS_INSTANT_APP;
9878            }
9879            if (pkgSetting.getVirtulalPreload(userId)) {
9880                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9881            }
9882        }
9883
9884        // Scan as privileged apps that share a user with a priv-app.
9885        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9886                && (pkg.mSharedUserId != null)) {
9887            SharedUserSetting sharedUserSetting = null;
9888            try {
9889                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9890            } catch (PackageManagerException ignore) {}
9891            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9892                // Exempt SharedUsers signed with the platform key.
9893                // TODO(b/72378145) Fix this exemption. Force signature apps
9894                // to whitelist their privileged permissions just like other
9895                // priv-apps.
9896                synchronized (mPackages) {
9897                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9898                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9899                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9900                        scanFlags |= SCAN_AS_PRIVILEGED;
9901                    }
9902                }
9903            }
9904        }
9905
9906        return scanFlags;
9907    }
9908
9909    @GuardedBy("mInstallLock")
9910    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9911            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9912            @Nullable UserHandle user) throws PackageManagerException {
9913
9914        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9915        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9916        if (realPkgName != null) {
9917            ensurePackageRenamed(pkg, renamedPkgName);
9918        }
9919        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9920        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9921        final PackageSetting disabledPkgSetting =
9922                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9923
9924        if (mTransferedPackages.contains(pkg.packageName)) {
9925            Slog.w(TAG, "Package " + pkg.packageName
9926                    + " was transferred to another, but its .apk remains");
9927        }
9928
9929        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9930        synchronized (mPackages) {
9931            applyPolicy(pkg, parseFlags, scanFlags);
9932            assertPackageIsValid(pkg, parseFlags, scanFlags);
9933
9934            SharedUserSetting sharedUserSetting = null;
9935            if (pkg.mSharedUserId != null) {
9936                // SIDE EFFECTS; may potentially allocate a new shared user
9937                sharedUserSetting = mSettings.getSharedUserLPw(
9938                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9939                if (DEBUG_PACKAGE_SCANNING) {
9940                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9941                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9942                                + " (uid=" + sharedUserSetting.userId + "):"
9943                                + " packages=" + sharedUserSetting.packages);
9944                }
9945            }
9946
9947            boolean scanSucceeded = false;
9948            try {
9949                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
9950                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
9951                        (pkg == mPlatformPackage), user);
9952                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
9953                if (result.success) {
9954                    commitScanResultsLocked(request, result);
9955                }
9956                scanSucceeded = true;
9957            } finally {
9958                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9959                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
9960                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9961                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9962                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9963                  }
9964            }
9965        }
9966        return pkg;
9967    }
9968
9969    /**
9970     * Commits the package scan and modifies system state.
9971     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
9972     * of committing the package, leaving the system in an inconsistent state.
9973     * This needs to be fixed so, once we get to this point, no errors are
9974     * possible and the system is not left in an inconsistent state.
9975     */
9976    @GuardedBy("mPackages")
9977    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
9978            throws PackageManagerException {
9979        final PackageParser.Package pkg = request.pkg;
9980        final @ParseFlags int parseFlags = request.parseFlags;
9981        final @ScanFlags int scanFlags = request.scanFlags;
9982        final PackageSetting oldPkgSetting = request.oldPkgSetting;
9983        final PackageSetting originalPkgSetting = request.originalPkgSetting;
9984        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
9985        final UserHandle user = request.user;
9986        final String realPkgName = request.realPkgName;
9987        final PackageSetting pkgSetting = result.pkgSetting;
9988        final List<String> changedAbiCodePath = result.changedAbiCodePath;
9989        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
9990
9991        if (newPkgSettingCreated) {
9992            if (originalPkgSetting != null) {
9993                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
9994            }
9995            // THROWS: when we can't allocate a user id. add call to check if there's
9996            // enough space to ensure we won't throw; otherwise, don't modify state
9997            mSettings.addUserToSettingLPw(pkgSetting);
9998
9999            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10000                mTransferedPackages.add(originalPkgSetting.name);
10001            }
10002        }
10003        // TODO(toddke): Consider a method specifically for modifying the Package object
10004        // post scan; or, moving this stuff out of the Package object since it has nothing
10005        // to do with the package on disk.
10006        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10007        // for creating the application ID. If we did this earlier, we would be saving the
10008        // correct ID.
10009        pkg.applicationInfo.uid = pkgSetting.appId;
10010
10011        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10012
10013        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10014            mTransferedPackages.add(pkg.packageName);
10015        }
10016
10017        // THROWS: when requested libraries that can't be found. it only changes
10018        // the state of the passed in pkg object, so, move to the top of the method
10019        // and allow it to abort
10020        if ((scanFlags & SCAN_BOOTING) == 0
10021                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10022            // Check all shared libraries and map to their actual file path.
10023            // We only do this here for apps not on a system dir, because those
10024            // are the only ones that can fail an install due to this.  We
10025            // will take care of the system apps by updating all of their
10026            // library paths after the scan is done. Also during the initial
10027            // scan don't update any libs as we do this wholesale after all
10028            // apps are scanned to avoid dependency based scanning.
10029            updateSharedLibrariesLPr(pkg, null);
10030        }
10031
10032        // All versions of a static shared library are referenced with the same
10033        // package name. Internally, we use a synthetic package name to allow
10034        // multiple versions of the same shared library to be installed. So,
10035        // we need to generate the synthetic package name of the latest shared
10036        // library in order to compare signatures.
10037        PackageSetting signatureCheckPs = pkgSetting;
10038        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10039            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10040            if (libraryEntry != null) {
10041                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10042            }
10043        }
10044
10045        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10046        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10047            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10048                // We just determined the app is signed correctly, so bring
10049                // over the latest parsed certs.
10050                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10051            } else {
10052                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10053                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10054                            "Package " + pkg.packageName + " upgrade keys do not match the "
10055                                    + "previously installed version");
10056                } else {
10057                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10058                    String msg = "System package " + pkg.packageName
10059                            + " signature changed; retaining data.";
10060                    reportSettingsProblem(Log.WARN, msg);
10061                }
10062            }
10063        } else {
10064            try {
10065                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10066                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10067                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10068                        pkg.mSigningDetails, compareCompat, compareRecover);
10069                // The new KeySets will be re-added later in the scanning process.
10070                if (compatMatch) {
10071                    synchronized (mPackages) {
10072                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10073                    }
10074                }
10075                // We just determined the app is signed correctly, so bring
10076                // over the latest parsed certs.
10077                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10078
10079
10080                // if this is is a sharedUser, check to see if the new package is signed by a newer
10081                // signing certificate than the existing one, and if so, copy over the new details
10082                if (signatureCheckPs.sharedUser != null
10083                        && pkg.mSigningDetails.hasAncestor(
10084                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10085                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10086                }
10087            } catch (PackageManagerException e) {
10088                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10089                    throw e;
10090                }
10091                // The signature has changed, but this package is in the system
10092                // image...  let's recover!
10093                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10094                // However...  if this package is part of a shared user, but it
10095                // doesn't match the signature of the shared user, let's fail.
10096                // What this means is that you can't change the signatures
10097                // associated with an overall shared user, which doesn't seem all
10098                // that unreasonable.
10099                if (signatureCheckPs.sharedUser != null) {
10100                    if (compareSignatures(
10101                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10102                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10103                        throw new PackageManagerException(
10104                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10105                                "Signature mismatch for shared user: "
10106                                        + pkgSetting.sharedUser);
10107                    }
10108                }
10109                // File a report about this.
10110                String msg = "System package " + pkg.packageName
10111                        + " signature changed; retaining data.";
10112                reportSettingsProblem(Log.WARN, msg);
10113            } catch (IllegalArgumentException e) {
10114
10115                // should never happen: certs matched when checking, but not when comparing
10116                // old to new for sharedUser
10117                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10118                        "Signing certificates comparison made on incomparable signing details"
10119                        + " but somehow passed verifySignatures!");
10120            }
10121        }
10122
10123        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10124            // This package wants to adopt ownership of permissions from
10125            // another package.
10126            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10127                final String origName = pkg.mAdoptPermissions.get(i);
10128                final PackageSetting orig = mSettings.getPackageLPr(origName);
10129                if (orig != null) {
10130                    if (verifyPackageUpdateLPr(orig, pkg)) {
10131                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10132                                + pkg.packageName);
10133                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10134                    }
10135                }
10136            }
10137        }
10138
10139        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10140            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10141                final String codePathString = changedAbiCodePath.get(i);
10142                try {
10143                    mInstaller.rmdex(codePathString,
10144                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10145                } catch (InstallerException ignored) {
10146                }
10147            }
10148        }
10149
10150        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10151            if (oldPkgSetting != null) {
10152                synchronized (mPackages) {
10153                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10154                }
10155            }
10156        } else {
10157            final int userId = user == null ? 0 : user.getIdentifier();
10158            // Modify state for the given package setting
10159            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10160                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10161            if (pkgSetting.getInstantApp(userId)) {
10162                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10163            }
10164        }
10165    }
10166
10167    /**
10168     * Returns the "real" name of the package.
10169     * <p>This may differ from the package's actual name if the application has already
10170     * been installed under one of this package's original names.
10171     */
10172    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10173            @Nullable String renamedPkgName) {
10174        if (isPackageRenamed(pkg, renamedPkgName)) {
10175            return pkg.mRealPackage;
10176        }
10177        return null;
10178    }
10179
10180    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10181    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10182            @Nullable String renamedPkgName) {
10183        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10184    }
10185
10186    /**
10187     * Returns the original package setting.
10188     * <p>A package can migrate its name during an update. In this scenario, a package
10189     * designates a set of names that it considers as one of its original names.
10190     * <p>An original package must be signed identically and it must have the same
10191     * shared user [if any].
10192     */
10193    @GuardedBy("mPackages")
10194    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10195            @Nullable String renamedPkgName) {
10196        if (!isPackageRenamed(pkg, renamedPkgName)) {
10197            return null;
10198        }
10199        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10200            final PackageSetting originalPs =
10201                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10202            if (originalPs != null) {
10203                // the package is already installed under its original name...
10204                // but, should we use it?
10205                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10206                    // the new package is incompatible with the original
10207                    continue;
10208                } else if (originalPs.sharedUser != null) {
10209                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10210                        // the shared user id is incompatible with the original
10211                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10212                                + " to " + pkg.packageName + ": old uid "
10213                                + originalPs.sharedUser.name
10214                                + " differs from " + pkg.mSharedUserId);
10215                        continue;
10216                    }
10217                    // TODO: Add case when shared user id is added [b/28144775]
10218                } else {
10219                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10220                            + pkg.packageName + " to old name " + originalPs.name);
10221                }
10222                return originalPs;
10223            }
10224        }
10225        return null;
10226    }
10227
10228    /**
10229     * Renames the package if it was installed under a different name.
10230     * <p>When we've already installed the package under an original name, update
10231     * the new package so we can continue to have the old name.
10232     */
10233    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10234            @NonNull String renamedPackageName) {
10235        if (pkg.mOriginalPackages == null
10236                || !pkg.mOriginalPackages.contains(renamedPackageName)
10237                || pkg.packageName.equals(renamedPackageName)) {
10238            return;
10239        }
10240        pkg.setPackageName(renamedPackageName);
10241    }
10242
10243    /**
10244     * Just scans the package without any side effects.
10245     * <p>Not entirely true at the moment. There is still one side effect -- this
10246     * method potentially modifies a live {@link PackageSetting} object representing
10247     * the package being scanned. This will be resolved in the future.
10248     *
10249     * @param request Information about the package to be scanned
10250     * @param isUnderFactoryTest Whether or not the device is under factory test
10251     * @param currentTime The current time, in millis
10252     * @return The results of the scan
10253     */
10254    @GuardedBy("mInstallLock")
10255    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10256            boolean isUnderFactoryTest, long currentTime)
10257                    throws PackageManagerException {
10258        final PackageParser.Package pkg = request.pkg;
10259        PackageSetting pkgSetting = request.pkgSetting;
10260        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10261        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10262        final @ParseFlags int parseFlags = request.parseFlags;
10263        final @ScanFlags int scanFlags = request.scanFlags;
10264        final String realPkgName = request.realPkgName;
10265        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10266        final UserHandle user = request.user;
10267        final boolean isPlatformPackage = request.isPlatformPackage;
10268
10269        List<String> changedAbiCodePath = null;
10270
10271        if (DEBUG_PACKAGE_SCANNING) {
10272            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10273                Log.d(TAG, "Scanning package " + pkg.packageName);
10274        }
10275
10276        if (Build.IS_DEBUGGABLE &&
10277                pkg.isPrivileged() &&
10278                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10279            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10280        }
10281
10282        // Initialize package source and resource directories
10283        final File scanFile = new File(pkg.codePath);
10284        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10285        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10286
10287        // We keep references to the derived CPU Abis from settings in oder to reuse
10288        // them in the case where we're not upgrading or booting for the first time.
10289        String primaryCpuAbiFromSettings = null;
10290        String secondaryCpuAbiFromSettings = null;
10291        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10292
10293        if (!needToDeriveAbi) {
10294            if (pkgSetting != null) {
10295                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10296                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10297            } else {
10298                // Re-scanning a system package after uninstalling updates; need to derive ABI
10299                needToDeriveAbi = true;
10300            }
10301        }
10302
10303        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10304            PackageManagerService.reportSettingsProblem(Log.WARN,
10305                    "Package " + pkg.packageName + " shared user changed from "
10306                            + (pkgSetting.sharedUser != null
10307                            ? pkgSetting.sharedUser.name : "<nothing>")
10308                            + " to "
10309                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10310                            + "; replacing with new");
10311            pkgSetting = null;
10312        }
10313
10314        String[] usesStaticLibraries = null;
10315        if (pkg.usesStaticLibraries != null) {
10316            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10317            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10318        }
10319        final boolean createNewPackage = (pkgSetting == null);
10320        if (createNewPackage) {
10321            final String parentPackageName = (pkg.parentPackage != null)
10322                    ? pkg.parentPackage.packageName : null;
10323            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10324            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10325            // REMOVE SharedUserSetting from method; update in a separate call
10326            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10327                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10328                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10329                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10330                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10331                    user, true /*allowInstall*/, instantApp, virtualPreload,
10332                    parentPackageName, pkg.getChildPackageNames(),
10333                    UserManagerService.getInstance(), usesStaticLibraries,
10334                    pkg.usesStaticLibrariesVersions);
10335        } else {
10336            // REMOVE SharedUserSetting from method; update in a separate call.
10337            //
10338            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10339            // secondaryCpuAbi are not known at this point so we always update them
10340            // to null here, only to reset them at a later point.
10341            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10342                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10343                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10344                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10345                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10346                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10347        }
10348        if (createNewPackage && originalPkgSetting != null) {
10349            // This is the initial transition from the original package, so,
10350            // fix up the new package's name now. We must do this after looking
10351            // up the package under its new name, so getPackageLP takes care of
10352            // fiddling things correctly.
10353            pkg.setPackageName(originalPkgSetting.name);
10354
10355            // File a report about this.
10356            String msg = "New package " + pkgSetting.realName
10357                    + " renamed to replace old package " + pkgSetting.name;
10358            reportSettingsProblem(Log.WARN, msg);
10359        }
10360
10361        if (disabledPkgSetting != null) {
10362            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10363        }
10364
10365        // SELinux sandboxes become more restrictive as targetSdkVersion increases.
10366        // To ensure that apps with sharedUserId are placed in the same selinux domain
10367        // without breaking any assumptions about access, put them into the least
10368        // restrictive targetSdkVersion=25 domain.
10369        // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
10370        // sharedUserSetting, instead of defaulting to the least restrictive domain.
10371        final int targetSdk = (sharedUserSetting != null) ? 25
10372                : pkg.applicationInfo.targetSdkVersion;
10373        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10374        // They currently can be if the sharedUser apps are signed with the platform key.
10375        final boolean isPrivileged = (sharedUserSetting != null) ?
10376            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10377
10378        SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
10379
10380        pkg.mExtras = pkgSetting;
10381        pkg.applicationInfo.processName = fixProcessName(
10382                pkg.applicationInfo.packageName,
10383                pkg.applicationInfo.processName);
10384
10385        if (!isPlatformPackage) {
10386            // Get all of our default paths setup
10387            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10388        }
10389
10390        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10391
10392        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10393            if (needToDeriveAbi) {
10394                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10395                final boolean extractNativeLibs = !pkg.isLibrary();
10396                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10397                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10398
10399                // Some system apps still use directory structure for native libraries
10400                // in which case we might end up not detecting abi solely based on apk
10401                // structure. Try to detect abi based on directory structure.
10402                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10403                        pkg.applicationInfo.primaryCpuAbi == null) {
10404                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10405                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10406                }
10407            } else {
10408                // This is not a first boot or an upgrade, don't bother deriving the
10409                // ABI during the scan. Instead, trust the value that was stored in the
10410                // package setting.
10411                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10412                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10413
10414                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10415
10416                if (DEBUG_ABI_SELECTION) {
10417                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10418                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10419                            pkg.applicationInfo.secondaryCpuAbi);
10420                }
10421            }
10422        } else {
10423            if ((scanFlags & SCAN_MOVE) != 0) {
10424                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10425                // but we already have this packages package info in the PackageSetting. We just
10426                // use that and derive the native library path based on the new codepath.
10427                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10428                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10429            }
10430
10431            // Set native library paths again. For moves, the path will be updated based on the
10432            // ABIs we've determined above. For non-moves, the path will be updated based on the
10433            // ABIs we determined during compilation, but the path will depend on the final
10434            // package path (after the rename away from the stage path).
10435            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10436        }
10437
10438        // This is a special case for the "system" package, where the ABI is
10439        // dictated by the zygote configuration (and init.rc). We should keep track
10440        // of this ABI so that we can deal with "normal" applications that run under
10441        // the same UID correctly.
10442        if (isPlatformPackage) {
10443            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10444                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10445        }
10446
10447        // If there's a mismatch between the abi-override in the package setting
10448        // and the abiOverride specified for the install. Warn about this because we
10449        // would've already compiled the app without taking the package setting into
10450        // account.
10451        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10452            if (cpuAbiOverride == null && pkg.packageName != null) {
10453                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10454                        " for package " + pkg.packageName);
10455            }
10456        }
10457
10458        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10459        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10460        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10461
10462        // Copy the derived override back to the parsed package, so that we can
10463        // update the package settings accordingly.
10464        pkg.cpuAbiOverride = cpuAbiOverride;
10465
10466        if (DEBUG_ABI_SELECTION) {
10467            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10468                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10469                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10470        }
10471
10472        // Push the derived path down into PackageSettings so we know what to
10473        // clean up at uninstall time.
10474        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10475
10476        if (DEBUG_ABI_SELECTION) {
10477            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10478                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10479                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10480        }
10481
10482        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10483            // We don't do this here during boot because we can do it all
10484            // at once after scanning all existing packages.
10485            //
10486            // We also do this *before* we perform dexopt on this package, so that
10487            // we can avoid redundant dexopts, and also to make sure we've got the
10488            // code and package path correct.
10489            changedAbiCodePath =
10490                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10491        }
10492
10493        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10494                android.Manifest.permission.FACTORY_TEST)) {
10495            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10496        }
10497
10498        if (isSystemApp(pkg)) {
10499            pkgSetting.isOrphaned = true;
10500        }
10501
10502        // Take care of first install / last update times.
10503        final long scanFileTime = getLastModifiedTime(pkg);
10504        if (currentTime != 0) {
10505            if (pkgSetting.firstInstallTime == 0) {
10506                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10507            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10508                pkgSetting.lastUpdateTime = currentTime;
10509            }
10510        } else if (pkgSetting.firstInstallTime == 0) {
10511            // We need *something*.  Take time time stamp of the file.
10512            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10513        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10514            if (scanFileTime != pkgSetting.timeStamp) {
10515                // A package on the system image has changed; consider this
10516                // to be an update.
10517                pkgSetting.lastUpdateTime = scanFileTime;
10518            }
10519        }
10520        pkgSetting.setTimeStamp(scanFileTime);
10521
10522        pkgSetting.pkg = pkg;
10523        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10524        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10525            pkgSetting.versionCode = pkg.getLongVersionCode();
10526        }
10527        // Update volume if needed
10528        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10529        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10530            Slog.i(PackageManagerService.TAG,
10531                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10532                    + " package " + pkg.packageName
10533                    + " volume from " + pkgSetting.volumeUuid
10534                    + " to " + volumeUuid);
10535            pkgSetting.volumeUuid = volumeUuid;
10536        }
10537
10538        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10539    }
10540
10541    /**
10542     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10543     */
10544    private static boolean apkHasCode(String fileName) {
10545        StrictJarFile jarFile = null;
10546        try {
10547            jarFile = new StrictJarFile(fileName,
10548                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10549            return jarFile.findEntry("classes.dex") != null;
10550        } catch (IOException ignore) {
10551        } finally {
10552            try {
10553                if (jarFile != null) {
10554                    jarFile.close();
10555                }
10556            } catch (IOException ignore) {}
10557        }
10558        return false;
10559    }
10560
10561    /**
10562     * Enforces code policy for the package. This ensures that if an APK has
10563     * declared hasCode="true" in its manifest that the APK actually contains
10564     * code.
10565     *
10566     * @throws PackageManagerException If bytecode could not be found when it should exist
10567     */
10568    private static void assertCodePolicy(PackageParser.Package pkg)
10569            throws PackageManagerException {
10570        final boolean shouldHaveCode =
10571                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10572        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10573            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10574                    "Package " + pkg.baseCodePath + " code is missing");
10575        }
10576
10577        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10578            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10579                final boolean splitShouldHaveCode =
10580                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10581                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10582                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10583                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10584                }
10585            }
10586        }
10587    }
10588
10589    /**
10590     * Applies policy to the parsed package based upon the given policy flags.
10591     * Ensures the package is in a good state.
10592     * <p>
10593     * Implementation detail: This method must NOT have any side effect. It would
10594     * ideally be static, but, it requires locks to read system state.
10595     */
10596    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10597            final @ScanFlags int scanFlags) {
10598        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10599            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10600            if (pkg.applicationInfo.isDirectBootAware()) {
10601                // we're direct boot aware; set for all components
10602                for (PackageParser.Service s : pkg.services) {
10603                    s.info.encryptionAware = s.info.directBootAware = true;
10604                }
10605                for (PackageParser.Provider p : pkg.providers) {
10606                    p.info.encryptionAware = p.info.directBootAware = true;
10607                }
10608                for (PackageParser.Activity a : pkg.activities) {
10609                    a.info.encryptionAware = a.info.directBootAware = true;
10610                }
10611                for (PackageParser.Activity r : pkg.receivers) {
10612                    r.info.encryptionAware = r.info.directBootAware = true;
10613                }
10614            }
10615            if (compressedFileExists(pkg.codePath)) {
10616                pkg.isStub = true;
10617            }
10618        } else {
10619            // non system apps can't be flagged as core
10620            pkg.coreApp = false;
10621            // clear flags not applicable to regular apps
10622            pkg.applicationInfo.flags &=
10623                    ~ApplicationInfo.FLAG_PERSISTENT;
10624            pkg.applicationInfo.privateFlags &=
10625                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10626            pkg.applicationInfo.privateFlags &=
10627                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10628            // clear protected broadcasts
10629            pkg.protectedBroadcasts = null;
10630            // cap permission priorities
10631            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10632                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10633                    pkg.permissionGroups.get(i).info.priority = 0;
10634                }
10635            }
10636        }
10637        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10638            // ignore export request for single user receivers
10639            if (pkg.receivers != null) {
10640                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10641                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10642                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10643                        receiver.info.exported = false;
10644                    }
10645                }
10646            }
10647            // ignore export request for single user services
10648            if (pkg.services != null) {
10649                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10650                    final PackageParser.Service service = pkg.services.get(i);
10651                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10652                        service.info.exported = false;
10653                    }
10654                }
10655            }
10656            // ignore export request for single user providers
10657            if (pkg.providers != null) {
10658                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10659                    final PackageParser.Provider provider = pkg.providers.get(i);
10660                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10661                        provider.info.exported = false;
10662                    }
10663                }
10664            }
10665        }
10666
10667        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10668            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10669        }
10670
10671        if ((scanFlags & SCAN_AS_OEM) != 0) {
10672            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10673        }
10674
10675        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10676            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10677        }
10678
10679        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10680            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10681        }
10682
10683        if (!isSystemApp(pkg)) {
10684            // Only system apps can use these features.
10685            pkg.mOriginalPackages = null;
10686            pkg.mRealPackage = null;
10687            pkg.mAdoptPermissions = null;
10688        }
10689    }
10690
10691    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10692            throws PackageManagerException {
10693        if (object == null) {
10694            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10695        }
10696        return object;
10697    }
10698
10699    /**
10700     * Asserts the parsed package is valid according to the given policy. If the
10701     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10702     * <p>
10703     * Implementation detail: This method must NOT have any side effects. It would
10704     * ideally be static, but, it requires locks to read system state.
10705     *
10706     * @throws PackageManagerException If the package fails any of the validation checks
10707     */
10708    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10709            final @ScanFlags int scanFlags)
10710                    throws PackageManagerException {
10711        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10712            assertCodePolicy(pkg);
10713        }
10714
10715        if (pkg.applicationInfo.getCodePath() == null ||
10716                pkg.applicationInfo.getResourcePath() == null) {
10717            // Bail out. The resource and code paths haven't been set.
10718            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10719                    "Code and resource paths haven't been set correctly");
10720        }
10721
10722        // Make sure we're not adding any bogus keyset info
10723        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10724        ksms.assertScannedPackageValid(pkg);
10725
10726        synchronized (mPackages) {
10727            // The special "android" package can only be defined once
10728            if (pkg.packageName.equals("android")) {
10729                if (mAndroidApplication != null) {
10730                    Slog.w(TAG, "*************************************************");
10731                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10732                    Slog.w(TAG, " codePath=" + pkg.codePath);
10733                    Slog.w(TAG, "*************************************************");
10734                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10735                            "Core android package being redefined.  Skipping.");
10736                }
10737            }
10738
10739            // A package name must be unique; don't allow duplicates
10740            if (mPackages.containsKey(pkg.packageName)) {
10741                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10742                        "Application package " + pkg.packageName
10743                        + " already installed.  Skipping duplicate.");
10744            }
10745
10746            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10747                // Static libs have a synthetic package name containing the version
10748                // but we still want the base name to be unique.
10749                if (mPackages.containsKey(pkg.manifestPackageName)) {
10750                    throw new PackageManagerException(
10751                            "Duplicate static shared lib provider package");
10752                }
10753
10754                // Static shared libraries should have at least O target SDK
10755                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10756                    throw new PackageManagerException(
10757                            "Packages declaring static-shared libs must target O SDK or higher");
10758                }
10759
10760                // Package declaring static a shared lib cannot be instant apps
10761                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10762                    throw new PackageManagerException(
10763                            "Packages declaring static-shared libs cannot be instant apps");
10764                }
10765
10766                // Package declaring static a shared lib cannot be renamed since the package
10767                // name is synthetic and apps can't code around package manager internals.
10768                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10769                    throw new PackageManagerException(
10770                            "Packages declaring static-shared libs cannot be renamed");
10771                }
10772
10773                // Package declaring static a shared lib cannot declare child packages
10774                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10775                    throw new PackageManagerException(
10776                            "Packages declaring static-shared libs cannot have child packages");
10777                }
10778
10779                // Package declaring static a shared lib cannot declare dynamic libs
10780                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10781                    throw new PackageManagerException(
10782                            "Packages declaring static-shared libs cannot declare dynamic libs");
10783                }
10784
10785                // Package declaring static a shared lib cannot declare shared users
10786                if (pkg.mSharedUserId != null) {
10787                    throw new PackageManagerException(
10788                            "Packages declaring static-shared libs cannot declare shared users");
10789                }
10790
10791                // Static shared libs cannot declare activities
10792                if (!pkg.activities.isEmpty()) {
10793                    throw new PackageManagerException(
10794                            "Static shared libs cannot declare activities");
10795                }
10796
10797                // Static shared libs cannot declare services
10798                if (!pkg.services.isEmpty()) {
10799                    throw new PackageManagerException(
10800                            "Static shared libs cannot declare services");
10801                }
10802
10803                // Static shared libs cannot declare providers
10804                if (!pkg.providers.isEmpty()) {
10805                    throw new PackageManagerException(
10806                            "Static shared libs cannot declare content providers");
10807                }
10808
10809                // Static shared libs cannot declare receivers
10810                if (!pkg.receivers.isEmpty()) {
10811                    throw new PackageManagerException(
10812                            "Static shared libs cannot declare broadcast receivers");
10813                }
10814
10815                // Static shared libs cannot declare permission groups
10816                if (!pkg.permissionGroups.isEmpty()) {
10817                    throw new PackageManagerException(
10818                            "Static shared libs cannot declare permission groups");
10819                }
10820
10821                // Static shared libs cannot declare permissions
10822                if (!pkg.permissions.isEmpty()) {
10823                    throw new PackageManagerException(
10824                            "Static shared libs cannot declare permissions");
10825                }
10826
10827                // Static shared libs cannot declare protected broadcasts
10828                if (pkg.protectedBroadcasts != null) {
10829                    throw new PackageManagerException(
10830                            "Static shared libs cannot declare protected broadcasts");
10831                }
10832
10833                // Static shared libs cannot be overlay targets
10834                if (pkg.mOverlayTarget != null) {
10835                    throw new PackageManagerException(
10836                            "Static shared libs cannot be overlay targets");
10837                }
10838
10839                // The version codes must be ordered as lib versions
10840                long minVersionCode = Long.MIN_VALUE;
10841                long maxVersionCode = Long.MAX_VALUE;
10842
10843                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10844                        pkg.staticSharedLibName);
10845                if (versionedLib != null) {
10846                    final int versionCount = versionedLib.size();
10847                    for (int i = 0; i < versionCount; i++) {
10848                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10849                        final long libVersionCode = libInfo.getDeclaringPackage()
10850                                .getLongVersionCode();
10851                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10852                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10853                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10854                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10855                        } else {
10856                            minVersionCode = maxVersionCode = libVersionCode;
10857                            break;
10858                        }
10859                    }
10860                }
10861                if (pkg.getLongVersionCode() < minVersionCode
10862                        || pkg.getLongVersionCode() > maxVersionCode) {
10863                    throw new PackageManagerException("Static shared"
10864                            + " lib version codes must be ordered as lib versions");
10865                }
10866            }
10867
10868            // Only privileged apps and updated privileged apps can add child packages.
10869            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10870                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10871                    throw new PackageManagerException("Only privileged apps can add child "
10872                            + "packages. Ignoring package " + pkg.packageName);
10873                }
10874                final int childCount = pkg.childPackages.size();
10875                for (int i = 0; i < childCount; i++) {
10876                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10877                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10878                            childPkg.packageName)) {
10879                        throw new PackageManagerException("Can't override child of "
10880                                + "another disabled app. Ignoring package " + pkg.packageName);
10881                    }
10882                }
10883            }
10884
10885            // If we're only installing presumed-existing packages, require that the
10886            // scanned APK is both already known and at the path previously established
10887            // for it.  Previously unknown packages we pick up normally, but if we have an
10888            // a priori expectation about this package's install presence, enforce it.
10889            // With a singular exception for new system packages. When an OTA contains
10890            // a new system package, we allow the codepath to change from a system location
10891            // to the user-installed location. If we don't allow this change, any newer,
10892            // user-installed version of the application will be ignored.
10893            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10894                if (mExpectingBetter.containsKey(pkg.packageName)) {
10895                    logCriticalInfo(Log.WARN,
10896                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10897                } else {
10898                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10899                    if (known != null) {
10900                        if (DEBUG_PACKAGE_SCANNING) {
10901                            Log.d(TAG, "Examining " + pkg.codePath
10902                                    + " and requiring known paths " + known.codePathString
10903                                    + " & " + known.resourcePathString);
10904                        }
10905                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10906                                || !pkg.applicationInfo.getResourcePath().equals(
10907                                        known.resourcePathString)) {
10908                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10909                                    "Application package " + pkg.packageName
10910                                    + " found at " + pkg.applicationInfo.getCodePath()
10911                                    + " but expected at " + known.codePathString
10912                                    + "; ignoring.");
10913                        }
10914                    } else {
10915                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10916                                "Application package " + pkg.packageName
10917                                + " not found; ignoring.");
10918                    }
10919                }
10920            }
10921
10922            // Verify that this new package doesn't have any content providers
10923            // that conflict with existing packages.  Only do this if the
10924            // package isn't already installed, since we don't want to break
10925            // things that are installed.
10926            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10927                final int N = pkg.providers.size();
10928                int i;
10929                for (i=0; i<N; i++) {
10930                    PackageParser.Provider p = pkg.providers.get(i);
10931                    if (p.info.authority != null) {
10932                        String names[] = p.info.authority.split(";");
10933                        for (int j = 0; j < names.length; j++) {
10934                            if (mProvidersByAuthority.containsKey(names[j])) {
10935                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10936                                final String otherPackageName =
10937                                        ((other != null && other.getComponentName() != null) ?
10938                                                other.getComponentName().getPackageName() : "?");
10939                                throw new PackageManagerException(
10940                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10941                                        "Can't install because provider name " + names[j]
10942                                                + " (in package " + pkg.applicationInfo.packageName
10943                                                + ") is already used by " + otherPackageName);
10944                            }
10945                        }
10946                    }
10947                }
10948            }
10949
10950            // Verify that packages sharing a user with a privileged app are marked as privileged.
10951            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
10952                SharedUserSetting sharedUserSetting = null;
10953                try {
10954                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10955                } catch (PackageManagerException ignore) {}
10956                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10957                    // Exempt SharedUsers signed with the platform key.
10958                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10959                    if ((platformPkgSetting.signatures.mSigningDetails
10960                            != PackageParser.SigningDetails.UNKNOWN)
10961                            && (compareSignatures(
10962                                    platformPkgSetting.signatures.mSigningDetails.signatures,
10963                                    pkg.mSigningDetails.signatures)
10964                                            != PackageManager.SIGNATURE_MATCH)) {
10965                        throw new PackageManagerException("Apps that share a user with a " +
10966                                "privileged app must themselves be marked as privileged. " +
10967                                pkg.packageName + " shares privileged user " +
10968                                pkg.mSharedUserId + ".");
10969                    }
10970                }
10971            }
10972
10973            // Apply policies specific for runtime resource overlays (RROs).
10974            if (pkg.mOverlayTarget != null) {
10975                // System overlays have some restrictions on their use of the 'static' state.
10976                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10977                    // We are scanning a system overlay. This can be the first scan of the
10978                    // system/vendor/oem partition, or an update to the system overlay.
10979                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10980                        // This must be an update to a system overlay.
10981                        final PackageSetting previousPkg = assertNotNull(
10982                                mSettings.getPackageLPr(pkg.packageName),
10983                                "previous package state not present");
10984
10985                        // Static overlays cannot be updated.
10986                        if (previousPkg.pkg.mOverlayIsStatic) {
10987                            throw new PackageManagerException("Overlay " + pkg.packageName +
10988                                    " is static and cannot be upgraded.");
10989                        // Non-static overlays cannot be converted to static overlays.
10990                        } else if (pkg.mOverlayIsStatic) {
10991                            throw new PackageManagerException("Overlay " + pkg.packageName +
10992                                    " cannot be upgraded into a static overlay.");
10993                        }
10994                    }
10995                } else {
10996                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
10997                    if (pkg.mOverlayIsStatic) {
10998                        throw new PackageManagerException("Overlay " + pkg.packageName +
10999                                " is static but not pre-installed.");
11000                    }
11001
11002                    // The only case where we allow installation of a non-system overlay is when
11003                    // its signature is signed with the platform certificate.
11004                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11005                    if ((platformPkgSetting.signatures.mSigningDetails
11006                            != PackageParser.SigningDetails.UNKNOWN)
11007                            && (compareSignatures(
11008                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11009                                    pkg.mSigningDetails.signatures)
11010                                            != PackageManager.SIGNATURE_MATCH)) {
11011                        throw new PackageManagerException("Overlay " + pkg.packageName +
11012                                " must be signed with the platform certificate.");
11013                    }
11014                }
11015            }
11016        }
11017    }
11018
11019    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11020            int type, String declaringPackageName, long declaringVersionCode) {
11021        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11022        if (versionedLib == null) {
11023            versionedLib = new LongSparseArray<>();
11024            mSharedLibraries.put(name, versionedLib);
11025            if (type == SharedLibraryInfo.TYPE_STATIC) {
11026                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11027            }
11028        } else if (versionedLib.indexOfKey(version) >= 0) {
11029            return false;
11030        }
11031        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11032                version, type, declaringPackageName, declaringVersionCode);
11033        versionedLib.put(version, libEntry);
11034        return true;
11035    }
11036
11037    private boolean removeSharedLibraryLPw(String name, long version) {
11038        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11039        if (versionedLib == null) {
11040            return false;
11041        }
11042        final int libIdx = versionedLib.indexOfKey(version);
11043        if (libIdx < 0) {
11044            return false;
11045        }
11046        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11047        versionedLib.remove(version);
11048        if (versionedLib.size() <= 0) {
11049            mSharedLibraries.remove(name);
11050            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11051                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11052                        .getPackageName());
11053            }
11054        }
11055        return true;
11056    }
11057
11058    /**
11059     * Adds a scanned package to the system. When this method is finished, the package will
11060     * be available for query, resolution, etc...
11061     */
11062    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11063            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11064        final String pkgName = pkg.packageName;
11065        if (mCustomResolverComponentName != null &&
11066                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11067            setUpCustomResolverActivity(pkg);
11068        }
11069
11070        if (pkg.packageName.equals("android")) {
11071            synchronized (mPackages) {
11072                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11073                    // Set up information for our fall-back user intent resolution activity.
11074                    mPlatformPackage = pkg;
11075                    pkg.mVersionCode = mSdkVersion;
11076                    pkg.mVersionCodeMajor = 0;
11077                    mAndroidApplication = pkg.applicationInfo;
11078                    if (!mResolverReplaced) {
11079                        mResolveActivity.applicationInfo = mAndroidApplication;
11080                        mResolveActivity.name = ResolverActivity.class.getName();
11081                        mResolveActivity.packageName = mAndroidApplication.packageName;
11082                        mResolveActivity.processName = "system:ui";
11083                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11084                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11085                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11086                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11087                        mResolveActivity.exported = true;
11088                        mResolveActivity.enabled = true;
11089                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11090                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11091                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11092                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11093                                | ActivityInfo.CONFIG_ORIENTATION
11094                                | ActivityInfo.CONFIG_KEYBOARD
11095                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11096                        mResolveInfo.activityInfo = mResolveActivity;
11097                        mResolveInfo.priority = 0;
11098                        mResolveInfo.preferredOrder = 0;
11099                        mResolveInfo.match = 0;
11100                        mResolveComponentName = new ComponentName(
11101                                mAndroidApplication.packageName, mResolveActivity.name);
11102                    }
11103                }
11104            }
11105        }
11106
11107        ArrayList<PackageParser.Package> clientLibPkgs = null;
11108        // writer
11109        synchronized (mPackages) {
11110            boolean hasStaticSharedLibs = false;
11111
11112            // Any app can add new static shared libraries
11113            if (pkg.staticSharedLibName != null) {
11114                // Static shared libs don't allow renaming as they have synthetic package
11115                // names to allow install of multiple versions, so use name from manifest.
11116                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11117                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11118                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11119                    hasStaticSharedLibs = true;
11120                } else {
11121                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11122                                + pkg.staticSharedLibName + " already exists; skipping");
11123                }
11124                // Static shared libs cannot be updated once installed since they
11125                // use synthetic package name which includes the version code, so
11126                // not need to update other packages's shared lib dependencies.
11127            }
11128
11129            if (!hasStaticSharedLibs
11130                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11131                // Only system apps can add new dynamic shared libraries.
11132                if (pkg.libraryNames != null) {
11133                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11134                        String name = pkg.libraryNames.get(i);
11135                        boolean allowed = false;
11136                        if (pkg.isUpdatedSystemApp()) {
11137                            // New library entries can only be added through the
11138                            // system image.  This is important to get rid of a lot
11139                            // of nasty edge cases: for example if we allowed a non-
11140                            // system update of the app to add a library, then uninstalling
11141                            // the update would make the library go away, and assumptions
11142                            // we made such as through app install filtering would now
11143                            // have allowed apps on the device which aren't compatible
11144                            // with it.  Better to just have the restriction here, be
11145                            // conservative, and create many fewer cases that can negatively
11146                            // impact the user experience.
11147                            final PackageSetting sysPs = mSettings
11148                                    .getDisabledSystemPkgLPr(pkg.packageName);
11149                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11150                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11151                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11152                                        allowed = true;
11153                                        break;
11154                                    }
11155                                }
11156                            }
11157                        } else {
11158                            allowed = true;
11159                        }
11160                        if (allowed) {
11161                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11162                                    SharedLibraryInfo.VERSION_UNDEFINED,
11163                                    SharedLibraryInfo.TYPE_DYNAMIC,
11164                                    pkg.packageName, pkg.getLongVersionCode())) {
11165                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11166                                        + name + " already exists; skipping");
11167                            }
11168                        } else {
11169                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11170                                    + name + " that is not declared on system image; skipping");
11171                        }
11172                    }
11173
11174                    if ((scanFlags & SCAN_BOOTING) == 0) {
11175                        // If we are not booting, we need to update any applications
11176                        // that are clients of our shared library.  If we are booting,
11177                        // this will all be done once the scan is complete.
11178                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11179                    }
11180                }
11181            }
11182        }
11183
11184        if ((scanFlags & SCAN_BOOTING) != 0) {
11185            // No apps can run during boot scan, so they don't need to be frozen
11186        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11187            // Caller asked to not kill app, so it's probably not frozen
11188        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11189            // Caller asked us to ignore frozen check for some reason; they
11190            // probably didn't know the package name
11191        } else {
11192            // We're doing major surgery on this package, so it better be frozen
11193            // right now to keep it from launching
11194            checkPackageFrozen(pkgName);
11195        }
11196
11197        // Also need to kill any apps that are dependent on the library.
11198        if (clientLibPkgs != null) {
11199            for (int i=0; i<clientLibPkgs.size(); i++) {
11200                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11201                killApplication(clientPkg.applicationInfo.packageName,
11202                        clientPkg.applicationInfo.uid, "update lib");
11203            }
11204        }
11205
11206        // writer
11207        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11208
11209        synchronized (mPackages) {
11210            // We don't expect installation to fail beyond this point
11211
11212            // Add the new setting to mSettings
11213            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11214            // Add the new setting to mPackages
11215            mPackages.put(pkg.applicationInfo.packageName, pkg);
11216            // Make sure we don't accidentally delete its data.
11217            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11218            while (iter.hasNext()) {
11219                PackageCleanItem item = iter.next();
11220                if (pkgName.equals(item.packageName)) {
11221                    iter.remove();
11222                }
11223            }
11224
11225            // Add the package's KeySets to the global KeySetManagerService
11226            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11227            ksms.addScannedPackageLPw(pkg);
11228
11229            int N = pkg.providers.size();
11230            StringBuilder r = null;
11231            int i;
11232            for (i=0; i<N; i++) {
11233                PackageParser.Provider p = pkg.providers.get(i);
11234                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11235                        p.info.processName);
11236                mProviders.addProvider(p);
11237                p.syncable = p.info.isSyncable;
11238                if (p.info.authority != null) {
11239                    String names[] = p.info.authority.split(";");
11240                    p.info.authority = null;
11241                    for (int j = 0; j < names.length; j++) {
11242                        if (j == 1 && p.syncable) {
11243                            // We only want the first authority for a provider to possibly be
11244                            // syncable, so if we already added this provider using a different
11245                            // authority clear the syncable flag. We copy the provider before
11246                            // changing it because the mProviders object contains a reference
11247                            // to a provider that we don't want to change.
11248                            // Only do this for the second authority since the resulting provider
11249                            // object can be the same for all future authorities for this provider.
11250                            p = new PackageParser.Provider(p);
11251                            p.syncable = false;
11252                        }
11253                        if (!mProvidersByAuthority.containsKey(names[j])) {
11254                            mProvidersByAuthority.put(names[j], p);
11255                            if (p.info.authority == null) {
11256                                p.info.authority = names[j];
11257                            } else {
11258                                p.info.authority = p.info.authority + ";" + names[j];
11259                            }
11260                            if (DEBUG_PACKAGE_SCANNING) {
11261                                if (chatty)
11262                                    Log.d(TAG, "Registered content provider: " + names[j]
11263                                            + ", className = " + p.info.name + ", isSyncable = "
11264                                            + p.info.isSyncable);
11265                            }
11266                        } else {
11267                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11268                            Slog.w(TAG, "Skipping provider name " + names[j] +
11269                                    " (in package " + pkg.applicationInfo.packageName +
11270                                    "): name already used by "
11271                                    + ((other != null && other.getComponentName() != null)
11272                                            ? other.getComponentName().getPackageName() : "?"));
11273                        }
11274                    }
11275                }
11276                if (chatty) {
11277                    if (r == null) {
11278                        r = new StringBuilder(256);
11279                    } else {
11280                        r.append(' ');
11281                    }
11282                    r.append(p.info.name);
11283                }
11284            }
11285            if (r != null) {
11286                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11287            }
11288
11289            N = pkg.services.size();
11290            r = null;
11291            for (i=0; i<N; i++) {
11292                PackageParser.Service s = pkg.services.get(i);
11293                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11294                        s.info.processName);
11295                mServices.addService(s);
11296                if (chatty) {
11297                    if (r == null) {
11298                        r = new StringBuilder(256);
11299                    } else {
11300                        r.append(' ');
11301                    }
11302                    r.append(s.info.name);
11303                }
11304            }
11305            if (r != null) {
11306                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11307            }
11308
11309            N = pkg.receivers.size();
11310            r = null;
11311            for (i=0; i<N; i++) {
11312                PackageParser.Activity a = pkg.receivers.get(i);
11313                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11314                        a.info.processName);
11315                mReceivers.addActivity(a, "receiver");
11316                if (chatty) {
11317                    if (r == null) {
11318                        r = new StringBuilder(256);
11319                    } else {
11320                        r.append(' ');
11321                    }
11322                    r.append(a.info.name);
11323                }
11324            }
11325            if (r != null) {
11326                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11327            }
11328
11329            N = pkg.activities.size();
11330            r = null;
11331            for (i=0; i<N; i++) {
11332                PackageParser.Activity a = pkg.activities.get(i);
11333                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11334                        a.info.processName);
11335                mActivities.addActivity(a, "activity");
11336                if (chatty) {
11337                    if (r == null) {
11338                        r = new StringBuilder(256);
11339                    } else {
11340                        r.append(' ');
11341                    }
11342                    r.append(a.info.name);
11343                }
11344            }
11345            if (r != null) {
11346                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11347            }
11348
11349            // Don't allow ephemeral applications to define new permissions groups.
11350            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11351                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11352                        + " ignored: instant apps cannot define new permission groups.");
11353            } else {
11354                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11355            }
11356
11357            // Don't allow ephemeral applications to define new permissions.
11358            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11359                Slog.w(TAG, "Permissions from package " + pkg.packageName
11360                        + " ignored: instant apps cannot define new permissions.");
11361            } else {
11362                mPermissionManager.addAllPermissions(pkg, chatty);
11363            }
11364
11365            N = pkg.instrumentation.size();
11366            r = null;
11367            for (i=0; i<N; i++) {
11368                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11369                a.info.packageName = pkg.applicationInfo.packageName;
11370                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11371                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11372                a.info.splitNames = pkg.splitNames;
11373                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11374                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11375                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11376                a.info.dataDir = pkg.applicationInfo.dataDir;
11377                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11378                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11379                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11380                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11381                mInstrumentation.put(a.getComponentName(), a);
11382                if (chatty) {
11383                    if (r == null) {
11384                        r = new StringBuilder(256);
11385                    } else {
11386                        r.append(' ');
11387                    }
11388                    r.append(a.info.name);
11389                }
11390            }
11391            if (r != null) {
11392                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11393            }
11394
11395            if (pkg.protectedBroadcasts != null) {
11396                N = pkg.protectedBroadcasts.size();
11397                synchronized (mProtectedBroadcasts) {
11398                    for (i = 0; i < N; i++) {
11399                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11400                    }
11401                }
11402            }
11403        }
11404
11405        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11406    }
11407
11408    /**
11409     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11410     * is derived purely on the basis of the contents of {@code scanFile} and
11411     * {@code cpuAbiOverride}.
11412     *
11413     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11414     */
11415    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11416            boolean extractLibs)
11417                    throws PackageManagerException {
11418        // Give ourselves some initial paths; we'll come back for another
11419        // pass once we've determined ABI below.
11420        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11421
11422        // We would never need to extract libs for forward-locked and external packages,
11423        // since the container service will do it for us. We shouldn't attempt to
11424        // extract libs from system app when it was not updated.
11425        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11426                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11427            extractLibs = false;
11428        }
11429
11430        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11431        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11432
11433        NativeLibraryHelper.Handle handle = null;
11434        try {
11435            handle = NativeLibraryHelper.Handle.create(pkg);
11436            // TODO(multiArch): This can be null for apps that didn't go through the
11437            // usual installation process. We can calculate it again, like we
11438            // do during install time.
11439            //
11440            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11441            // unnecessary.
11442            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11443
11444            // Null out the abis so that they can be recalculated.
11445            pkg.applicationInfo.primaryCpuAbi = null;
11446            pkg.applicationInfo.secondaryCpuAbi = null;
11447            if (isMultiArch(pkg.applicationInfo)) {
11448                // Warn if we've set an abiOverride for multi-lib packages..
11449                // By definition, we need to copy both 32 and 64 bit libraries for
11450                // such packages.
11451                if (pkg.cpuAbiOverride != null
11452                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11453                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11454                }
11455
11456                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11457                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11458                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11459                    if (extractLibs) {
11460                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11461                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11462                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11463                                useIsaSpecificSubdirs);
11464                    } else {
11465                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11466                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11467                    }
11468                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11469                }
11470
11471                // Shared library native code should be in the APK zip aligned
11472                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11473                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11474                            "Shared library native lib extraction not supported");
11475                }
11476
11477                maybeThrowExceptionForMultiArchCopy(
11478                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11479
11480                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11481                    if (extractLibs) {
11482                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11483                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11484                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11485                                useIsaSpecificSubdirs);
11486                    } else {
11487                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11488                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11489                    }
11490                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11491                }
11492
11493                maybeThrowExceptionForMultiArchCopy(
11494                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11495
11496                if (abi64 >= 0) {
11497                    // Shared library native libs should be in the APK zip aligned
11498                    if (extractLibs && pkg.isLibrary()) {
11499                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11500                                "Shared library native lib extraction not supported");
11501                    }
11502                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11503                }
11504
11505                if (abi32 >= 0) {
11506                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11507                    if (abi64 >= 0) {
11508                        if (pkg.use32bitAbi) {
11509                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11510                            pkg.applicationInfo.primaryCpuAbi = abi;
11511                        } else {
11512                            pkg.applicationInfo.secondaryCpuAbi = abi;
11513                        }
11514                    } else {
11515                        pkg.applicationInfo.primaryCpuAbi = abi;
11516                    }
11517                }
11518            } else {
11519                String[] abiList = (cpuAbiOverride != null) ?
11520                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11521
11522                // Enable gross and lame hacks for apps that are built with old
11523                // SDK tools. We must scan their APKs for renderscript bitcode and
11524                // not launch them if it's present. Don't bother checking on devices
11525                // that don't have 64 bit support.
11526                boolean needsRenderScriptOverride = false;
11527                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11528                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11529                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11530                    needsRenderScriptOverride = true;
11531                }
11532
11533                final int copyRet;
11534                if (extractLibs) {
11535                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11536                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11537                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11538                } else {
11539                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11540                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11541                }
11542                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11543
11544                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11545                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11546                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11547                }
11548
11549                if (copyRet >= 0) {
11550                    // Shared libraries that have native libs must be multi-architecture
11551                    if (pkg.isLibrary()) {
11552                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11553                                "Shared library with native libs must be multiarch");
11554                    }
11555                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11556                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11557                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11558                } else if (needsRenderScriptOverride) {
11559                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11560                }
11561            }
11562        } catch (IOException ioe) {
11563            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11564        } finally {
11565            IoUtils.closeQuietly(handle);
11566        }
11567
11568        // Now that we've calculated the ABIs and determined if it's an internal app,
11569        // we will go ahead and populate the nativeLibraryPath.
11570        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11571    }
11572
11573    /**
11574     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11575     * i.e, so that all packages can be run inside a single process if required.
11576     *
11577     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11578     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11579     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11580     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11581     * updating a package that belongs to a shared user.
11582     *
11583     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11584     * adds unnecessary complexity.
11585     */
11586    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11587            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11588        List<String> changedAbiCodePath = null;
11589        String requiredInstructionSet = null;
11590        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11591            requiredInstructionSet = VMRuntime.getInstructionSet(
11592                     scannedPackage.applicationInfo.primaryCpuAbi);
11593        }
11594
11595        PackageSetting requirer = null;
11596        for (PackageSetting ps : packagesForUser) {
11597            // If packagesForUser contains scannedPackage, we skip it. This will happen
11598            // when scannedPackage is an update of an existing package. Without this check,
11599            // we will never be able to change the ABI of any package belonging to a shared
11600            // user, even if it's compatible with other packages.
11601            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11602                if (ps.primaryCpuAbiString == null) {
11603                    continue;
11604                }
11605
11606                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11607                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11608                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11609                    // this but there's not much we can do.
11610                    String errorMessage = "Instruction set mismatch, "
11611                            + ((requirer == null) ? "[caller]" : requirer)
11612                            + " requires " + requiredInstructionSet + " whereas " + ps
11613                            + " requires " + instructionSet;
11614                    Slog.w(TAG, errorMessage);
11615                }
11616
11617                if (requiredInstructionSet == null) {
11618                    requiredInstructionSet = instructionSet;
11619                    requirer = ps;
11620                }
11621            }
11622        }
11623
11624        if (requiredInstructionSet != null) {
11625            String adjustedAbi;
11626            if (requirer != null) {
11627                // requirer != null implies that either scannedPackage was null or that scannedPackage
11628                // did not require an ABI, in which case we have to adjust scannedPackage to match
11629                // the ABI of the set (which is the same as requirer's ABI)
11630                adjustedAbi = requirer.primaryCpuAbiString;
11631                if (scannedPackage != null) {
11632                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11633                }
11634            } else {
11635                // requirer == null implies that we're updating all ABIs in the set to
11636                // match scannedPackage.
11637                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11638            }
11639
11640            for (PackageSetting ps : packagesForUser) {
11641                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11642                    if (ps.primaryCpuAbiString != null) {
11643                        continue;
11644                    }
11645
11646                    ps.primaryCpuAbiString = adjustedAbi;
11647                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11648                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11649                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11650                        if (DEBUG_ABI_SELECTION) {
11651                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11652                                    + " (requirer="
11653                                    + (requirer != null ? requirer.pkg : "null")
11654                                    + ", scannedPackage="
11655                                    + (scannedPackage != null ? scannedPackage : "null")
11656                                    + ")");
11657                        }
11658                        if (changedAbiCodePath == null) {
11659                            changedAbiCodePath = new ArrayList<>();
11660                        }
11661                        changedAbiCodePath.add(ps.codePathString);
11662                    }
11663                }
11664            }
11665        }
11666        return changedAbiCodePath;
11667    }
11668
11669    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11670        synchronized (mPackages) {
11671            mResolverReplaced = true;
11672            // Set up information for custom user intent resolution activity.
11673            mResolveActivity.applicationInfo = pkg.applicationInfo;
11674            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11675            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11676            mResolveActivity.processName = pkg.applicationInfo.packageName;
11677            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11678            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11679                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11680            mResolveActivity.theme = 0;
11681            mResolveActivity.exported = true;
11682            mResolveActivity.enabled = true;
11683            mResolveInfo.activityInfo = mResolveActivity;
11684            mResolveInfo.priority = 0;
11685            mResolveInfo.preferredOrder = 0;
11686            mResolveInfo.match = 0;
11687            mResolveComponentName = mCustomResolverComponentName;
11688            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11689                    mResolveComponentName);
11690        }
11691    }
11692
11693    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11694        if (installerActivity == null) {
11695            if (DEBUG_INSTANT) {
11696                Slog.d(TAG, "Clear ephemeral installer activity");
11697            }
11698            mInstantAppInstallerActivity = null;
11699            return;
11700        }
11701
11702        if (DEBUG_INSTANT) {
11703            Slog.d(TAG, "Set ephemeral installer activity: "
11704                    + installerActivity.getComponentName());
11705        }
11706        // Set up information for ephemeral installer activity
11707        mInstantAppInstallerActivity = installerActivity;
11708        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11709                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11710        mInstantAppInstallerActivity.exported = true;
11711        mInstantAppInstallerActivity.enabled = true;
11712        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11713        mInstantAppInstallerInfo.priority = 1;
11714        mInstantAppInstallerInfo.preferredOrder = 1;
11715        mInstantAppInstallerInfo.isDefault = true;
11716        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11717                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11718    }
11719
11720    private static String calculateBundledApkRoot(final String codePathString) {
11721        final File codePath = new File(codePathString);
11722        final File codeRoot;
11723        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11724            codeRoot = Environment.getRootDirectory();
11725        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11726            codeRoot = Environment.getOemDirectory();
11727        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11728            codeRoot = Environment.getVendorDirectory();
11729        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11730            codeRoot = Environment.getProductDirectory();
11731        } else {
11732            // Unrecognized code path; take its top real segment as the apk root:
11733            // e.g. /something/app/blah.apk => /something
11734            try {
11735                File f = codePath.getCanonicalFile();
11736                File parent = f.getParentFile();    // non-null because codePath is a file
11737                File tmp;
11738                while ((tmp = parent.getParentFile()) != null) {
11739                    f = parent;
11740                    parent = tmp;
11741                }
11742                codeRoot = f;
11743                Slog.w(TAG, "Unrecognized code path "
11744                        + codePath + " - using " + codeRoot);
11745            } catch (IOException e) {
11746                // Can't canonicalize the code path -- shenanigans?
11747                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11748                return Environment.getRootDirectory().getPath();
11749            }
11750        }
11751        return codeRoot.getPath();
11752    }
11753
11754    /**
11755     * Derive and set the location of native libraries for the given package,
11756     * which varies depending on where and how the package was installed.
11757     */
11758    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11759        final ApplicationInfo info = pkg.applicationInfo;
11760        final String codePath = pkg.codePath;
11761        final File codeFile = new File(codePath);
11762        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11763        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11764
11765        info.nativeLibraryRootDir = null;
11766        info.nativeLibraryRootRequiresIsa = false;
11767        info.nativeLibraryDir = null;
11768        info.secondaryNativeLibraryDir = null;
11769
11770        if (isApkFile(codeFile)) {
11771            // Monolithic install
11772            if (bundledApp) {
11773                // If "/system/lib64/apkname" exists, assume that is the per-package
11774                // native library directory to use; otherwise use "/system/lib/apkname".
11775                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11776                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11777                        getPrimaryInstructionSet(info));
11778
11779                // This is a bundled system app so choose the path based on the ABI.
11780                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11781                // is just the default path.
11782                final String apkName = deriveCodePathName(codePath);
11783                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11784                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11785                        apkName).getAbsolutePath();
11786
11787                if (info.secondaryCpuAbi != null) {
11788                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11789                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11790                            secondaryLibDir, apkName).getAbsolutePath();
11791                }
11792            } else if (asecApp) {
11793                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11794                        .getAbsolutePath();
11795            } else {
11796                final String apkName = deriveCodePathName(codePath);
11797                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11798                        .getAbsolutePath();
11799            }
11800
11801            info.nativeLibraryRootRequiresIsa = false;
11802            info.nativeLibraryDir = info.nativeLibraryRootDir;
11803        } else {
11804            // Cluster install
11805            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11806            info.nativeLibraryRootRequiresIsa = true;
11807
11808            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11809                    getPrimaryInstructionSet(info)).getAbsolutePath();
11810
11811            if (info.secondaryCpuAbi != null) {
11812                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11813                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11814            }
11815        }
11816    }
11817
11818    /**
11819     * Calculate the abis and roots for a bundled app. These can uniquely
11820     * be determined from the contents of the system partition, i.e whether
11821     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11822     * of this information, and instead assume that the system was built
11823     * sensibly.
11824     */
11825    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11826                                           PackageSetting pkgSetting) {
11827        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11828
11829        // If "/system/lib64/apkname" exists, assume that is the per-package
11830        // native library directory to use; otherwise use "/system/lib/apkname".
11831        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11832        setBundledAppAbi(pkg, apkRoot, apkName);
11833        // pkgSetting might be null during rescan following uninstall of updates
11834        // to a bundled app, so accommodate that possibility.  The settings in
11835        // that case will be established later from the parsed package.
11836        //
11837        // If the settings aren't null, sync them up with what we've just derived.
11838        // note that apkRoot isn't stored in the package settings.
11839        if (pkgSetting != null) {
11840            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11841            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11842        }
11843    }
11844
11845    /**
11846     * Deduces the ABI of a bundled app and sets the relevant fields on the
11847     * parsed pkg object.
11848     *
11849     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11850     *        under which system libraries are installed.
11851     * @param apkName the name of the installed package.
11852     */
11853    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11854        final File codeFile = new File(pkg.codePath);
11855
11856        final boolean has64BitLibs;
11857        final boolean has32BitLibs;
11858        if (isApkFile(codeFile)) {
11859            // Monolithic install
11860            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11861            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11862        } else {
11863            // Cluster install
11864            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11865            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11866                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11867                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11868                has64BitLibs = (new File(rootDir, isa)).exists();
11869            } else {
11870                has64BitLibs = false;
11871            }
11872            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11873                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11874                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11875                has32BitLibs = (new File(rootDir, isa)).exists();
11876            } else {
11877                has32BitLibs = false;
11878            }
11879        }
11880
11881        if (has64BitLibs && !has32BitLibs) {
11882            // The package has 64 bit libs, but not 32 bit libs. Its primary
11883            // ABI should be 64 bit. We can safely assume here that the bundled
11884            // native libraries correspond to the most preferred ABI in the list.
11885
11886            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11887            pkg.applicationInfo.secondaryCpuAbi = null;
11888        } else if (has32BitLibs && !has64BitLibs) {
11889            // The package has 32 bit libs but not 64 bit libs. Its primary
11890            // ABI should be 32 bit.
11891
11892            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11893            pkg.applicationInfo.secondaryCpuAbi = null;
11894        } else if (has32BitLibs && has64BitLibs) {
11895            // The application has both 64 and 32 bit bundled libraries. We check
11896            // here that the app declares multiArch support, and warn if it doesn't.
11897            //
11898            // We will be lenient here and record both ABIs. The primary will be the
11899            // ABI that's higher on the list, i.e, a device that's configured to prefer
11900            // 64 bit apps will see a 64 bit primary ABI,
11901
11902            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11903                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11904            }
11905
11906            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11907                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11908                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11909            } else {
11910                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11911                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11912            }
11913        } else {
11914            pkg.applicationInfo.primaryCpuAbi = null;
11915            pkg.applicationInfo.secondaryCpuAbi = null;
11916        }
11917    }
11918
11919    private void killApplication(String pkgName, int appId, String reason) {
11920        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11921    }
11922
11923    private void killApplication(String pkgName, int appId, int userId, String reason) {
11924        // Request the ActivityManager to kill the process(only for existing packages)
11925        // so that we do not end up in a confused state while the user is still using the older
11926        // version of the application while the new one gets installed.
11927        final long token = Binder.clearCallingIdentity();
11928        try {
11929            IActivityManager am = ActivityManager.getService();
11930            if (am != null) {
11931                try {
11932                    am.killApplication(pkgName, appId, userId, reason);
11933                } catch (RemoteException e) {
11934                }
11935            }
11936        } finally {
11937            Binder.restoreCallingIdentity(token);
11938        }
11939    }
11940
11941    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11942        // Remove the parent package setting
11943        PackageSetting ps = (PackageSetting) pkg.mExtras;
11944        if (ps != null) {
11945            removePackageLI(ps, chatty);
11946        }
11947        // Remove the child package setting
11948        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11949        for (int i = 0; i < childCount; i++) {
11950            PackageParser.Package childPkg = pkg.childPackages.get(i);
11951            ps = (PackageSetting) childPkg.mExtras;
11952            if (ps != null) {
11953                removePackageLI(ps, chatty);
11954            }
11955        }
11956    }
11957
11958    void removePackageLI(PackageSetting ps, boolean chatty) {
11959        if (DEBUG_INSTALL) {
11960            if (chatty)
11961                Log.d(TAG, "Removing package " + ps.name);
11962        }
11963
11964        // writer
11965        synchronized (mPackages) {
11966            mPackages.remove(ps.name);
11967            final PackageParser.Package pkg = ps.pkg;
11968            if (pkg != null) {
11969                cleanPackageDataStructuresLILPw(pkg, chatty);
11970            }
11971        }
11972    }
11973
11974    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11975        if (DEBUG_INSTALL) {
11976            if (chatty)
11977                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11978        }
11979
11980        // writer
11981        synchronized (mPackages) {
11982            // Remove the parent package
11983            mPackages.remove(pkg.applicationInfo.packageName);
11984            cleanPackageDataStructuresLILPw(pkg, chatty);
11985
11986            // Remove the child packages
11987            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11988            for (int i = 0; i < childCount; i++) {
11989                PackageParser.Package childPkg = pkg.childPackages.get(i);
11990                mPackages.remove(childPkg.applicationInfo.packageName);
11991                cleanPackageDataStructuresLILPw(childPkg, chatty);
11992            }
11993        }
11994    }
11995
11996    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11997        int N = pkg.providers.size();
11998        StringBuilder r = null;
11999        int i;
12000        for (i=0; i<N; i++) {
12001            PackageParser.Provider p = pkg.providers.get(i);
12002            mProviders.removeProvider(p);
12003            if (p.info.authority == null) {
12004
12005                /* There was another ContentProvider with this authority when
12006                 * this app was installed so this authority is null,
12007                 * Ignore it as we don't have to unregister the provider.
12008                 */
12009                continue;
12010            }
12011            String names[] = p.info.authority.split(";");
12012            for (int j = 0; j < names.length; j++) {
12013                if (mProvidersByAuthority.get(names[j]) == p) {
12014                    mProvidersByAuthority.remove(names[j]);
12015                    if (DEBUG_REMOVE) {
12016                        if (chatty)
12017                            Log.d(TAG, "Unregistered content provider: " + names[j]
12018                                    + ", className = " + p.info.name + ", isSyncable = "
12019                                    + p.info.isSyncable);
12020                    }
12021                }
12022            }
12023            if (DEBUG_REMOVE && chatty) {
12024                if (r == null) {
12025                    r = new StringBuilder(256);
12026                } else {
12027                    r.append(' ');
12028                }
12029                r.append(p.info.name);
12030            }
12031        }
12032        if (r != null) {
12033            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12034        }
12035
12036        N = pkg.services.size();
12037        r = null;
12038        for (i=0; i<N; i++) {
12039            PackageParser.Service s = pkg.services.get(i);
12040            mServices.removeService(s);
12041            if (chatty) {
12042                if (r == null) {
12043                    r = new StringBuilder(256);
12044                } else {
12045                    r.append(' ');
12046                }
12047                r.append(s.info.name);
12048            }
12049        }
12050        if (r != null) {
12051            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12052        }
12053
12054        N = pkg.receivers.size();
12055        r = null;
12056        for (i=0; i<N; i++) {
12057            PackageParser.Activity a = pkg.receivers.get(i);
12058            mReceivers.removeActivity(a, "receiver");
12059            if (DEBUG_REMOVE && chatty) {
12060                if (r == null) {
12061                    r = new StringBuilder(256);
12062                } else {
12063                    r.append(' ');
12064                }
12065                r.append(a.info.name);
12066            }
12067        }
12068        if (r != null) {
12069            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12070        }
12071
12072        N = pkg.activities.size();
12073        r = null;
12074        for (i=0; i<N; i++) {
12075            PackageParser.Activity a = pkg.activities.get(i);
12076            mActivities.removeActivity(a, "activity");
12077            if (DEBUG_REMOVE && chatty) {
12078                if (r == null) {
12079                    r = new StringBuilder(256);
12080                } else {
12081                    r.append(' ');
12082                }
12083                r.append(a.info.name);
12084            }
12085        }
12086        if (r != null) {
12087            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12088        }
12089
12090        mPermissionManager.removeAllPermissions(pkg, chatty);
12091
12092        N = pkg.instrumentation.size();
12093        r = null;
12094        for (i=0; i<N; i++) {
12095            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12096            mInstrumentation.remove(a.getComponentName());
12097            if (DEBUG_REMOVE && chatty) {
12098                if (r == null) {
12099                    r = new StringBuilder(256);
12100                } else {
12101                    r.append(' ');
12102                }
12103                r.append(a.info.name);
12104            }
12105        }
12106        if (r != null) {
12107            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12108        }
12109
12110        r = null;
12111        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12112            // Only system apps can hold shared libraries.
12113            if (pkg.libraryNames != null) {
12114                for (i = 0; i < pkg.libraryNames.size(); i++) {
12115                    String name = pkg.libraryNames.get(i);
12116                    if (removeSharedLibraryLPw(name, 0)) {
12117                        if (DEBUG_REMOVE && chatty) {
12118                            if (r == null) {
12119                                r = new StringBuilder(256);
12120                            } else {
12121                                r.append(' ');
12122                            }
12123                            r.append(name);
12124                        }
12125                    }
12126                }
12127            }
12128        }
12129
12130        r = null;
12131
12132        // Any package can hold static shared libraries.
12133        if (pkg.staticSharedLibName != null) {
12134            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12135                if (DEBUG_REMOVE && chatty) {
12136                    if (r == null) {
12137                        r = new StringBuilder(256);
12138                    } else {
12139                        r.append(' ');
12140                    }
12141                    r.append(pkg.staticSharedLibName);
12142                }
12143            }
12144        }
12145
12146        if (r != null) {
12147            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12148        }
12149    }
12150
12151
12152    final class ActivityIntentResolver
12153            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12154        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12155                boolean defaultOnly, int userId) {
12156            if (!sUserManager.exists(userId)) return null;
12157            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12158            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12159        }
12160
12161        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12162                int userId) {
12163            if (!sUserManager.exists(userId)) return null;
12164            mFlags = flags;
12165            return super.queryIntent(intent, resolvedType,
12166                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12167                    userId);
12168        }
12169
12170        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12171                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12172            if (!sUserManager.exists(userId)) return null;
12173            if (packageActivities == null) {
12174                return null;
12175            }
12176            mFlags = flags;
12177            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12178            final int N = packageActivities.size();
12179            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12180                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12181
12182            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12183            for (int i = 0; i < N; ++i) {
12184                intentFilters = packageActivities.get(i).intents;
12185                if (intentFilters != null && intentFilters.size() > 0) {
12186                    PackageParser.ActivityIntentInfo[] array =
12187                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12188                    intentFilters.toArray(array);
12189                    listCut.add(array);
12190                }
12191            }
12192            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12193        }
12194
12195        /**
12196         * Finds a privileged activity that matches the specified activity names.
12197         */
12198        private PackageParser.Activity findMatchingActivity(
12199                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12200            for (PackageParser.Activity sysActivity : activityList) {
12201                if (sysActivity.info.name.equals(activityInfo.name)) {
12202                    return sysActivity;
12203                }
12204                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12205                    return sysActivity;
12206                }
12207                if (sysActivity.info.targetActivity != null) {
12208                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12209                        return sysActivity;
12210                    }
12211                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12212                        return sysActivity;
12213                    }
12214                }
12215            }
12216            return null;
12217        }
12218
12219        public class IterGenerator<E> {
12220            public Iterator<E> generate(ActivityIntentInfo info) {
12221                return null;
12222            }
12223        }
12224
12225        public class ActionIterGenerator extends IterGenerator<String> {
12226            @Override
12227            public Iterator<String> generate(ActivityIntentInfo info) {
12228                return info.actionsIterator();
12229            }
12230        }
12231
12232        public class CategoriesIterGenerator extends IterGenerator<String> {
12233            @Override
12234            public Iterator<String> generate(ActivityIntentInfo info) {
12235                return info.categoriesIterator();
12236            }
12237        }
12238
12239        public class SchemesIterGenerator extends IterGenerator<String> {
12240            @Override
12241            public Iterator<String> generate(ActivityIntentInfo info) {
12242                return info.schemesIterator();
12243            }
12244        }
12245
12246        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12247            @Override
12248            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12249                return info.authoritiesIterator();
12250            }
12251        }
12252
12253        /**
12254         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12255         * MODIFIED. Do not pass in a list that should not be changed.
12256         */
12257        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12258                IterGenerator<T> generator, Iterator<T> searchIterator) {
12259            // loop through the set of actions; every one must be found in the intent filter
12260            while (searchIterator.hasNext()) {
12261                // we must have at least one filter in the list to consider a match
12262                if (intentList.size() == 0) {
12263                    break;
12264                }
12265
12266                final T searchAction = searchIterator.next();
12267
12268                // loop through the set of intent filters
12269                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12270                while (intentIter.hasNext()) {
12271                    final ActivityIntentInfo intentInfo = intentIter.next();
12272                    boolean selectionFound = false;
12273
12274                    // loop through the intent filter's selection criteria; at least one
12275                    // of them must match the searched criteria
12276                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12277                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12278                        final T intentSelection = intentSelectionIter.next();
12279                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12280                            selectionFound = true;
12281                            break;
12282                        }
12283                    }
12284
12285                    // the selection criteria wasn't found in this filter's set; this filter
12286                    // is not a potential match
12287                    if (!selectionFound) {
12288                        intentIter.remove();
12289                    }
12290                }
12291            }
12292        }
12293
12294        private boolean isProtectedAction(ActivityIntentInfo filter) {
12295            final Iterator<String> actionsIter = filter.actionsIterator();
12296            while (actionsIter != null && actionsIter.hasNext()) {
12297                final String filterAction = actionsIter.next();
12298                if (PROTECTED_ACTIONS.contains(filterAction)) {
12299                    return true;
12300                }
12301            }
12302            return false;
12303        }
12304
12305        /**
12306         * Adjusts the priority of the given intent filter according to policy.
12307         * <p>
12308         * <ul>
12309         * <li>The priority for non privileged applications is capped to '0'</li>
12310         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12311         * <li>The priority for unbundled updates to privileged applications is capped to the
12312         *      priority defined on the system partition</li>
12313         * </ul>
12314         * <p>
12315         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12316         * allowed to obtain any priority on any action.
12317         */
12318        private void adjustPriority(
12319                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12320            // nothing to do; priority is fine as-is
12321            if (intent.getPriority() <= 0) {
12322                return;
12323            }
12324
12325            final ActivityInfo activityInfo = intent.activity.info;
12326            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12327
12328            final boolean privilegedApp =
12329                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12330            if (!privilegedApp) {
12331                // non-privileged applications can never define a priority >0
12332                if (DEBUG_FILTERS) {
12333                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12334                            + " package: " + applicationInfo.packageName
12335                            + " activity: " + intent.activity.className
12336                            + " origPrio: " + intent.getPriority());
12337                }
12338                intent.setPriority(0);
12339                return;
12340            }
12341
12342            if (systemActivities == null) {
12343                // the system package is not disabled; we're parsing the system partition
12344                if (isProtectedAction(intent)) {
12345                    if (mDeferProtectedFilters) {
12346                        // We can't deal with these just yet. No component should ever obtain a
12347                        // >0 priority for a protected actions, with ONE exception -- the setup
12348                        // wizard. The setup wizard, however, cannot be known until we're able to
12349                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12350                        // until all intent filters have been processed. Chicken, meet egg.
12351                        // Let the filter temporarily have a high priority and rectify the
12352                        // priorities after all system packages have been scanned.
12353                        mProtectedFilters.add(intent);
12354                        if (DEBUG_FILTERS) {
12355                            Slog.i(TAG, "Protected action; save for later;"
12356                                    + " package: " + applicationInfo.packageName
12357                                    + " activity: " + intent.activity.className
12358                                    + " origPrio: " + intent.getPriority());
12359                        }
12360                        return;
12361                    } else {
12362                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12363                            Slog.i(TAG, "No setup wizard;"
12364                                + " All protected intents capped to priority 0");
12365                        }
12366                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12367                            if (DEBUG_FILTERS) {
12368                                Slog.i(TAG, "Found setup wizard;"
12369                                    + " allow priority " + intent.getPriority() + ";"
12370                                    + " package: " + intent.activity.info.packageName
12371                                    + " activity: " + intent.activity.className
12372                                    + " priority: " + intent.getPriority());
12373                            }
12374                            // setup wizard gets whatever it wants
12375                            return;
12376                        }
12377                        if (DEBUG_FILTERS) {
12378                            Slog.i(TAG, "Protected action; cap priority to 0;"
12379                                    + " package: " + intent.activity.info.packageName
12380                                    + " activity: " + intent.activity.className
12381                                    + " origPrio: " + intent.getPriority());
12382                        }
12383                        intent.setPriority(0);
12384                        return;
12385                    }
12386                }
12387                // privileged apps on the system image get whatever priority they request
12388                return;
12389            }
12390
12391            // privileged app unbundled update ... try to find the same activity
12392            final PackageParser.Activity foundActivity =
12393                    findMatchingActivity(systemActivities, activityInfo);
12394            if (foundActivity == null) {
12395                // this is a new activity; it cannot obtain >0 priority
12396                if (DEBUG_FILTERS) {
12397                    Slog.i(TAG, "New activity; cap priority to 0;"
12398                            + " package: " + applicationInfo.packageName
12399                            + " activity: " + intent.activity.className
12400                            + " origPrio: " + intent.getPriority());
12401                }
12402                intent.setPriority(0);
12403                return;
12404            }
12405
12406            // found activity, now check for filter equivalence
12407
12408            // a shallow copy is enough; we modify the list, not its contents
12409            final List<ActivityIntentInfo> intentListCopy =
12410                    new ArrayList<>(foundActivity.intents);
12411            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12412
12413            // find matching action subsets
12414            final Iterator<String> actionsIterator = intent.actionsIterator();
12415            if (actionsIterator != null) {
12416                getIntentListSubset(
12417                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12418                if (intentListCopy.size() == 0) {
12419                    // no more intents to match; we're not equivalent
12420                    if (DEBUG_FILTERS) {
12421                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12422                                + " package: " + applicationInfo.packageName
12423                                + " activity: " + intent.activity.className
12424                                + " origPrio: " + intent.getPriority());
12425                    }
12426                    intent.setPriority(0);
12427                    return;
12428                }
12429            }
12430
12431            // find matching category subsets
12432            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12433            if (categoriesIterator != null) {
12434                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12435                        categoriesIterator);
12436                if (intentListCopy.size() == 0) {
12437                    // no more intents to match; we're not equivalent
12438                    if (DEBUG_FILTERS) {
12439                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12440                                + " package: " + applicationInfo.packageName
12441                                + " activity: " + intent.activity.className
12442                                + " origPrio: " + intent.getPriority());
12443                    }
12444                    intent.setPriority(0);
12445                    return;
12446                }
12447            }
12448
12449            // find matching schemes subsets
12450            final Iterator<String> schemesIterator = intent.schemesIterator();
12451            if (schemesIterator != null) {
12452                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12453                        schemesIterator);
12454                if (intentListCopy.size() == 0) {
12455                    // no more intents to match; we're not equivalent
12456                    if (DEBUG_FILTERS) {
12457                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12458                                + " package: " + applicationInfo.packageName
12459                                + " activity: " + intent.activity.className
12460                                + " origPrio: " + intent.getPriority());
12461                    }
12462                    intent.setPriority(0);
12463                    return;
12464                }
12465            }
12466
12467            // find matching authorities subsets
12468            final Iterator<IntentFilter.AuthorityEntry>
12469                    authoritiesIterator = intent.authoritiesIterator();
12470            if (authoritiesIterator != null) {
12471                getIntentListSubset(intentListCopy,
12472                        new AuthoritiesIterGenerator(),
12473                        authoritiesIterator);
12474                if (intentListCopy.size() == 0) {
12475                    // no more intents to match; we're not equivalent
12476                    if (DEBUG_FILTERS) {
12477                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12478                                + " package: " + applicationInfo.packageName
12479                                + " activity: " + intent.activity.className
12480                                + " origPrio: " + intent.getPriority());
12481                    }
12482                    intent.setPriority(0);
12483                    return;
12484                }
12485            }
12486
12487            // we found matching filter(s); app gets the max priority of all intents
12488            int cappedPriority = 0;
12489            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12490                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12491            }
12492            if (intent.getPriority() > cappedPriority) {
12493                if (DEBUG_FILTERS) {
12494                    Slog.i(TAG, "Found matching filter(s);"
12495                            + " cap priority to " + cappedPriority + ";"
12496                            + " package: " + applicationInfo.packageName
12497                            + " activity: " + intent.activity.className
12498                            + " origPrio: " + intent.getPriority());
12499                }
12500                intent.setPriority(cappedPriority);
12501                return;
12502            }
12503            // all this for nothing; the requested priority was <= what was on the system
12504        }
12505
12506        public final void addActivity(PackageParser.Activity a, String type) {
12507            mActivities.put(a.getComponentName(), a);
12508            if (DEBUG_SHOW_INFO)
12509                Log.v(
12510                TAG, "  " + type + " " +
12511                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12512            if (DEBUG_SHOW_INFO)
12513                Log.v(TAG, "    Class=" + a.info.name);
12514            final int NI = a.intents.size();
12515            for (int j=0; j<NI; j++) {
12516                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12517                if ("activity".equals(type)) {
12518                    final PackageSetting ps =
12519                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12520                    final List<PackageParser.Activity> systemActivities =
12521                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12522                    adjustPriority(systemActivities, intent);
12523                }
12524                if (DEBUG_SHOW_INFO) {
12525                    Log.v(TAG, "    IntentFilter:");
12526                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12527                }
12528                if (!intent.debugCheck()) {
12529                    Log.w(TAG, "==> For Activity " + a.info.name);
12530                }
12531                addFilter(intent);
12532            }
12533        }
12534
12535        public final void removeActivity(PackageParser.Activity a, String type) {
12536            mActivities.remove(a.getComponentName());
12537            if (DEBUG_SHOW_INFO) {
12538                Log.v(TAG, "  " + type + " "
12539                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12540                                : a.info.name) + ":");
12541                Log.v(TAG, "    Class=" + a.info.name);
12542            }
12543            final int NI = a.intents.size();
12544            for (int j=0; j<NI; j++) {
12545                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12546                if (DEBUG_SHOW_INFO) {
12547                    Log.v(TAG, "    IntentFilter:");
12548                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12549                }
12550                removeFilter(intent);
12551            }
12552        }
12553
12554        @Override
12555        protected boolean allowFilterResult(
12556                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12557            ActivityInfo filterAi = filter.activity.info;
12558            for (int i=dest.size()-1; i>=0; i--) {
12559                ActivityInfo destAi = dest.get(i).activityInfo;
12560                if (destAi.name == filterAi.name
12561                        && destAi.packageName == filterAi.packageName) {
12562                    return false;
12563                }
12564            }
12565            return true;
12566        }
12567
12568        @Override
12569        protected ActivityIntentInfo[] newArray(int size) {
12570            return new ActivityIntentInfo[size];
12571        }
12572
12573        @Override
12574        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12575            if (!sUserManager.exists(userId)) return true;
12576            PackageParser.Package p = filter.activity.owner;
12577            if (p != null) {
12578                PackageSetting ps = (PackageSetting)p.mExtras;
12579                if (ps != null) {
12580                    // System apps are never considered stopped for purposes of
12581                    // filtering, because there may be no way for the user to
12582                    // actually re-launch them.
12583                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12584                            && ps.getStopped(userId);
12585                }
12586            }
12587            return false;
12588        }
12589
12590        @Override
12591        protected boolean isPackageForFilter(String packageName,
12592                PackageParser.ActivityIntentInfo info) {
12593            return packageName.equals(info.activity.owner.packageName);
12594        }
12595
12596        @Override
12597        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12598                int match, int userId) {
12599            if (!sUserManager.exists(userId)) return null;
12600            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12601                return null;
12602            }
12603            final PackageParser.Activity activity = info.activity;
12604            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12605            if (ps == null) {
12606                return null;
12607            }
12608            final PackageUserState userState = ps.readUserState(userId);
12609            ActivityInfo ai =
12610                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12611            if (ai == null) {
12612                return null;
12613            }
12614            final boolean matchExplicitlyVisibleOnly =
12615                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12616            final boolean matchVisibleToInstantApp =
12617                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12618            final boolean componentVisible =
12619                    matchVisibleToInstantApp
12620                    && info.isVisibleToInstantApp()
12621                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12622            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12623            // throw out filters that aren't visible to ephemeral apps
12624            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12625                return null;
12626            }
12627            // throw out instant app filters if we're not explicitly requesting them
12628            if (!matchInstantApp && userState.instantApp) {
12629                return null;
12630            }
12631            // throw out instant app filters if updates are available; will trigger
12632            // instant app resolution
12633            if (userState.instantApp && ps.isUpdateAvailable()) {
12634                return null;
12635            }
12636            final ResolveInfo res = new ResolveInfo();
12637            res.activityInfo = ai;
12638            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12639                res.filter = info;
12640            }
12641            if (info != null) {
12642                res.handleAllWebDataURI = info.handleAllWebDataURI();
12643            }
12644            res.priority = info.getPriority();
12645            res.preferredOrder = activity.owner.mPreferredOrder;
12646            //System.out.println("Result: " + res.activityInfo.className +
12647            //                   " = " + res.priority);
12648            res.match = match;
12649            res.isDefault = info.hasDefault;
12650            res.labelRes = info.labelRes;
12651            res.nonLocalizedLabel = info.nonLocalizedLabel;
12652            if (userNeedsBadging(userId)) {
12653                res.noResourceId = true;
12654            } else {
12655                res.icon = info.icon;
12656            }
12657            res.iconResourceId = info.icon;
12658            res.system = res.activityInfo.applicationInfo.isSystemApp();
12659            res.isInstantAppAvailable = userState.instantApp;
12660            return res;
12661        }
12662
12663        @Override
12664        protected void sortResults(List<ResolveInfo> results) {
12665            Collections.sort(results, mResolvePrioritySorter);
12666        }
12667
12668        @Override
12669        protected void dumpFilter(PrintWriter out, String prefix,
12670                PackageParser.ActivityIntentInfo filter) {
12671            out.print(prefix); out.print(
12672                    Integer.toHexString(System.identityHashCode(filter.activity)));
12673                    out.print(' ');
12674                    filter.activity.printComponentShortName(out);
12675                    out.print(" filter ");
12676                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12677        }
12678
12679        @Override
12680        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12681            return filter.activity;
12682        }
12683
12684        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12685            PackageParser.Activity activity = (PackageParser.Activity)label;
12686            out.print(prefix); out.print(
12687                    Integer.toHexString(System.identityHashCode(activity)));
12688                    out.print(' ');
12689                    activity.printComponentShortName(out);
12690            if (count > 1) {
12691                out.print(" ("); out.print(count); out.print(" filters)");
12692            }
12693            out.println();
12694        }
12695
12696        // Keys are String (activity class name), values are Activity.
12697        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12698                = new ArrayMap<ComponentName, PackageParser.Activity>();
12699        private int mFlags;
12700    }
12701
12702    private final class ServiceIntentResolver
12703            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12704        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12705                boolean defaultOnly, int userId) {
12706            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12707            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12708        }
12709
12710        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12711                int userId) {
12712            if (!sUserManager.exists(userId)) return null;
12713            mFlags = flags;
12714            return super.queryIntent(intent, resolvedType,
12715                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12716                    userId);
12717        }
12718
12719        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12720                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12721            if (!sUserManager.exists(userId)) return null;
12722            if (packageServices == null) {
12723                return null;
12724            }
12725            mFlags = flags;
12726            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12727            final int N = packageServices.size();
12728            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12729                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12730
12731            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12732            for (int i = 0; i < N; ++i) {
12733                intentFilters = packageServices.get(i).intents;
12734                if (intentFilters != null && intentFilters.size() > 0) {
12735                    PackageParser.ServiceIntentInfo[] array =
12736                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12737                    intentFilters.toArray(array);
12738                    listCut.add(array);
12739                }
12740            }
12741            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12742        }
12743
12744        public final void addService(PackageParser.Service s) {
12745            mServices.put(s.getComponentName(), s);
12746            if (DEBUG_SHOW_INFO) {
12747                Log.v(TAG, "  "
12748                        + (s.info.nonLocalizedLabel != null
12749                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12750                Log.v(TAG, "    Class=" + s.info.name);
12751            }
12752            final int NI = s.intents.size();
12753            int j;
12754            for (j=0; j<NI; j++) {
12755                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12756                if (DEBUG_SHOW_INFO) {
12757                    Log.v(TAG, "    IntentFilter:");
12758                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12759                }
12760                if (!intent.debugCheck()) {
12761                    Log.w(TAG, "==> For Service " + s.info.name);
12762                }
12763                addFilter(intent);
12764            }
12765        }
12766
12767        public final void removeService(PackageParser.Service s) {
12768            mServices.remove(s.getComponentName());
12769            if (DEBUG_SHOW_INFO) {
12770                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12771                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12772                Log.v(TAG, "    Class=" + s.info.name);
12773            }
12774            final int NI = s.intents.size();
12775            int j;
12776            for (j=0; j<NI; j++) {
12777                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12778                if (DEBUG_SHOW_INFO) {
12779                    Log.v(TAG, "    IntentFilter:");
12780                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12781                }
12782                removeFilter(intent);
12783            }
12784        }
12785
12786        @Override
12787        protected boolean allowFilterResult(
12788                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12789            ServiceInfo filterSi = filter.service.info;
12790            for (int i=dest.size()-1; i>=0; i--) {
12791                ServiceInfo destAi = dest.get(i).serviceInfo;
12792                if (destAi.name == filterSi.name
12793                        && destAi.packageName == filterSi.packageName) {
12794                    return false;
12795                }
12796            }
12797            return true;
12798        }
12799
12800        @Override
12801        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12802            return new PackageParser.ServiceIntentInfo[size];
12803        }
12804
12805        @Override
12806        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12807            if (!sUserManager.exists(userId)) return true;
12808            PackageParser.Package p = filter.service.owner;
12809            if (p != null) {
12810                PackageSetting ps = (PackageSetting)p.mExtras;
12811                if (ps != null) {
12812                    // System apps are never considered stopped for purposes of
12813                    // filtering, because there may be no way for the user to
12814                    // actually re-launch them.
12815                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12816                            && ps.getStopped(userId);
12817                }
12818            }
12819            return false;
12820        }
12821
12822        @Override
12823        protected boolean isPackageForFilter(String packageName,
12824                PackageParser.ServiceIntentInfo info) {
12825            return packageName.equals(info.service.owner.packageName);
12826        }
12827
12828        @Override
12829        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12830                int match, int userId) {
12831            if (!sUserManager.exists(userId)) return null;
12832            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12833            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12834                return null;
12835            }
12836            final PackageParser.Service service = info.service;
12837            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12838            if (ps == null) {
12839                return null;
12840            }
12841            final PackageUserState userState = ps.readUserState(userId);
12842            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12843                    userState, userId);
12844            if (si == null) {
12845                return null;
12846            }
12847            final boolean matchVisibleToInstantApp =
12848                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12849            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12850            // throw out filters that aren't visible to ephemeral apps
12851            if (matchVisibleToInstantApp
12852                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12853                return null;
12854            }
12855            // throw out ephemeral filters if we're not explicitly requesting them
12856            if (!isInstantApp && userState.instantApp) {
12857                return null;
12858            }
12859            // throw out instant app filters if updates are available; will trigger
12860            // instant app resolution
12861            if (userState.instantApp && ps.isUpdateAvailable()) {
12862                return null;
12863            }
12864            final ResolveInfo res = new ResolveInfo();
12865            res.serviceInfo = si;
12866            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12867                res.filter = filter;
12868            }
12869            res.priority = info.getPriority();
12870            res.preferredOrder = service.owner.mPreferredOrder;
12871            res.match = match;
12872            res.isDefault = info.hasDefault;
12873            res.labelRes = info.labelRes;
12874            res.nonLocalizedLabel = info.nonLocalizedLabel;
12875            res.icon = info.icon;
12876            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12877            return res;
12878        }
12879
12880        @Override
12881        protected void sortResults(List<ResolveInfo> results) {
12882            Collections.sort(results, mResolvePrioritySorter);
12883        }
12884
12885        @Override
12886        protected void dumpFilter(PrintWriter out, String prefix,
12887                PackageParser.ServiceIntentInfo filter) {
12888            out.print(prefix); out.print(
12889                    Integer.toHexString(System.identityHashCode(filter.service)));
12890                    out.print(' ');
12891                    filter.service.printComponentShortName(out);
12892                    out.print(" filter ");
12893                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12894                    if (filter.service.info.permission != null) {
12895                        out.print(" permission "); out.println(filter.service.info.permission);
12896                    } else {
12897                        out.println();
12898                    }
12899        }
12900
12901        @Override
12902        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12903            return filter.service;
12904        }
12905
12906        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12907            PackageParser.Service service = (PackageParser.Service)label;
12908            out.print(prefix); out.print(
12909                    Integer.toHexString(System.identityHashCode(service)));
12910                    out.print(' ');
12911                    service.printComponentShortName(out);
12912            if (count > 1) {
12913                out.print(" ("); out.print(count); out.print(" filters)");
12914            }
12915            out.println();
12916        }
12917
12918//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12919//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12920//            final List<ResolveInfo> retList = Lists.newArrayList();
12921//            while (i.hasNext()) {
12922//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12923//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12924//                    retList.add(resolveInfo);
12925//                }
12926//            }
12927//            return retList;
12928//        }
12929
12930        // Keys are String (activity class name), values are Activity.
12931        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12932                = new ArrayMap<ComponentName, PackageParser.Service>();
12933        private int mFlags;
12934    }
12935
12936    private final class ProviderIntentResolver
12937            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12938        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12939                boolean defaultOnly, int userId) {
12940            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12941            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12942        }
12943
12944        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12945                int userId) {
12946            if (!sUserManager.exists(userId))
12947                return null;
12948            mFlags = flags;
12949            return super.queryIntent(intent, resolvedType,
12950                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12951                    userId);
12952        }
12953
12954        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12955                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12956            if (!sUserManager.exists(userId))
12957                return null;
12958            if (packageProviders == null) {
12959                return null;
12960            }
12961            mFlags = flags;
12962            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12963            final int N = packageProviders.size();
12964            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12965                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12966
12967            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12968            for (int i = 0; i < N; ++i) {
12969                intentFilters = packageProviders.get(i).intents;
12970                if (intentFilters != null && intentFilters.size() > 0) {
12971                    PackageParser.ProviderIntentInfo[] array =
12972                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12973                    intentFilters.toArray(array);
12974                    listCut.add(array);
12975                }
12976            }
12977            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12978        }
12979
12980        public final void addProvider(PackageParser.Provider p) {
12981            if (mProviders.containsKey(p.getComponentName())) {
12982                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12983                return;
12984            }
12985
12986            mProviders.put(p.getComponentName(), p);
12987            if (DEBUG_SHOW_INFO) {
12988                Log.v(TAG, "  "
12989                        + (p.info.nonLocalizedLabel != null
12990                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12991                Log.v(TAG, "    Class=" + p.info.name);
12992            }
12993            final int NI = p.intents.size();
12994            int j;
12995            for (j = 0; j < NI; j++) {
12996                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12997                if (DEBUG_SHOW_INFO) {
12998                    Log.v(TAG, "    IntentFilter:");
12999                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13000                }
13001                if (!intent.debugCheck()) {
13002                    Log.w(TAG, "==> For Provider " + p.info.name);
13003                }
13004                addFilter(intent);
13005            }
13006        }
13007
13008        public final void removeProvider(PackageParser.Provider p) {
13009            mProviders.remove(p.getComponentName());
13010            if (DEBUG_SHOW_INFO) {
13011                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13012                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13013                Log.v(TAG, "    Class=" + p.info.name);
13014            }
13015            final int NI = p.intents.size();
13016            int j;
13017            for (j = 0; j < NI; j++) {
13018                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13019                if (DEBUG_SHOW_INFO) {
13020                    Log.v(TAG, "    IntentFilter:");
13021                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13022                }
13023                removeFilter(intent);
13024            }
13025        }
13026
13027        @Override
13028        protected boolean allowFilterResult(
13029                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13030            ProviderInfo filterPi = filter.provider.info;
13031            for (int i = dest.size() - 1; i >= 0; i--) {
13032                ProviderInfo destPi = dest.get(i).providerInfo;
13033                if (destPi.name == filterPi.name
13034                        && destPi.packageName == filterPi.packageName) {
13035                    return false;
13036                }
13037            }
13038            return true;
13039        }
13040
13041        @Override
13042        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13043            return new PackageParser.ProviderIntentInfo[size];
13044        }
13045
13046        @Override
13047        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13048            if (!sUserManager.exists(userId))
13049                return true;
13050            PackageParser.Package p = filter.provider.owner;
13051            if (p != null) {
13052                PackageSetting ps = (PackageSetting) p.mExtras;
13053                if (ps != null) {
13054                    // System apps are never considered stopped for purposes of
13055                    // filtering, because there may be no way for the user to
13056                    // actually re-launch them.
13057                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13058                            && ps.getStopped(userId);
13059                }
13060            }
13061            return false;
13062        }
13063
13064        @Override
13065        protected boolean isPackageForFilter(String packageName,
13066                PackageParser.ProviderIntentInfo info) {
13067            return packageName.equals(info.provider.owner.packageName);
13068        }
13069
13070        @Override
13071        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13072                int match, int userId) {
13073            if (!sUserManager.exists(userId))
13074                return null;
13075            final PackageParser.ProviderIntentInfo info = filter;
13076            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13077                return null;
13078            }
13079            final PackageParser.Provider provider = info.provider;
13080            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13081            if (ps == null) {
13082                return null;
13083            }
13084            final PackageUserState userState = ps.readUserState(userId);
13085            final boolean matchVisibleToInstantApp =
13086                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13087            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13088            // throw out filters that aren't visible to instant applications
13089            if (matchVisibleToInstantApp
13090                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13091                return null;
13092            }
13093            // throw out instant application filters if we're not explicitly requesting them
13094            if (!isInstantApp && userState.instantApp) {
13095                return null;
13096            }
13097            // throw out instant application filters if updates are available; will trigger
13098            // instant application resolution
13099            if (userState.instantApp && ps.isUpdateAvailable()) {
13100                return null;
13101            }
13102            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13103                    userState, userId);
13104            if (pi == null) {
13105                return null;
13106            }
13107            final ResolveInfo res = new ResolveInfo();
13108            res.providerInfo = pi;
13109            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13110                res.filter = filter;
13111            }
13112            res.priority = info.getPriority();
13113            res.preferredOrder = provider.owner.mPreferredOrder;
13114            res.match = match;
13115            res.isDefault = info.hasDefault;
13116            res.labelRes = info.labelRes;
13117            res.nonLocalizedLabel = info.nonLocalizedLabel;
13118            res.icon = info.icon;
13119            res.system = res.providerInfo.applicationInfo.isSystemApp();
13120            return res;
13121        }
13122
13123        @Override
13124        protected void sortResults(List<ResolveInfo> results) {
13125            Collections.sort(results, mResolvePrioritySorter);
13126        }
13127
13128        @Override
13129        protected void dumpFilter(PrintWriter out, String prefix,
13130                PackageParser.ProviderIntentInfo filter) {
13131            out.print(prefix);
13132            out.print(
13133                    Integer.toHexString(System.identityHashCode(filter.provider)));
13134            out.print(' ');
13135            filter.provider.printComponentShortName(out);
13136            out.print(" filter ");
13137            out.println(Integer.toHexString(System.identityHashCode(filter)));
13138        }
13139
13140        @Override
13141        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13142            return filter.provider;
13143        }
13144
13145        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13146            PackageParser.Provider provider = (PackageParser.Provider)label;
13147            out.print(prefix); out.print(
13148                    Integer.toHexString(System.identityHashCode(provider)));
13149                    out.print(' ');
13150                    provider.printComponentShortName(out);
13151            if (count > 1) {
13152                out.print(" ("); out.print(count); out.print(" filters)");
13153            }
13154            out.println();
13155        }
13156
13157        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13158                = new ArrayMap<ComponentName, PackageParser.Provider>();
13159        private int mFlags;
13160    }
13161
13162    static final class InstantAppIntentResolver
13163            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13164            AuxiliaryResolveInfo.AuxiliaryFilter> {
13165        /**
13166         * The result that has the highest defined order. Ordering applies on a
13167         * per-package basis. Mapping is from package name to Pair of order and
13168         * EphemeralResolveInfo.
13169         * <p>
13170         * NOTE: This is implemented as a field variable for convenience and efficiency.
13171         * By having a field variable, we're able to track filter ordering as soon as
13172         * a non-zero order is defined. Otherwise, multiple loops across the result set
13173         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13174         * this needs to be contained entirely within {@link #filterResults}.
13175         */
13176        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13177
13178        @Override
13179        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13180            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13181        }
13182
13183        @Override
13184        protected boolean isPackageForFilter(String packageName,
13185                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13186            return true;
13187        }
13188
13189        @Override
13190        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13191                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13192            if (!sUserManager.exists(userId)) {
13193                return null;
13194            }
13195            final String packageName = responseObj.resolveInfo.getPackageName();
13196            final Integer order = responseObj.getOrder();
13197            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13198                    mOrderResult.get(packageName);
13199            // ordering is enabled and this item's order isn't high enough
13200            if (lastOrderResult != null && lastOrderResult.first >= order) {
13201                return null;
13202            }
13203            final InstantAppResolveInfo res = responseObj.resolveInfo;
13204            if (order > 0) {
13205                // non-zero order, enable ordering
13206                mOrderResult.put(packageName, new Pair<>(order, res));
13207            }
13208            return responseObj;
13209        }
13210
13211        @Override
13212        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13213            // only do work if ordering is enabled [most of the time it won't be]
13214            if (mOrderResult.size() == 0) {
13215                return;
13216            }
13217            int resultSize = results.size();
13218            for (int i = 0; i < resultSize; i++) {
13219                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13220                final String packageName = info.getPackageName();
13221                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13222                if (savedInfo == null) {
13223                    // package doesn't having ordering
13224                    continue;
13225                }
13226                if (savedInfo.second == info) {
13227                    // circled back to the highest ordered item; remove from order list
13228                    mOrderResult.remove(packageName);
13229                    if (mOrderResult.size() == 0) {
13230                        // no more ordered items
13231                        break;
13232                    }
13233                    continue;
13234                }
13235                // item has a worse order, remove it from the result list
13236                results.remove(i);
13237                resultSize--;
13238                i--;
13239            }
13240        }
13241    }
13242
13243    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13244            new Comparator<ResolveInfo>() {
13245        public int compare(ResolveInfo r1, ResolveInfo r2) {
13246            int v1 = r1.priority;
13247            int v2 = r2.priority;
13248            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13249            if (v1 != v2) {
13250                return (v1 > v2) ? -1 : 1;
13251            }
13252            v1 = r1.preferredOrder;
13253            v2 = r2.preferredOrder;
13254            if (v1 != v2) {
13255                return (v1 > v2) ? -1 : 1;
13256            }
13257            if (r1.isDefault != r2.isDefault) {
13258                return r1.isDefault ? -1 : 1;
13259            }
13260            v1 = r1.match;
13261            v2 = r2.match;
13262            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13263            if (v1 != v2) {
13264                return (v1 > v2) ? -1 : 1;
13265            }
13266            if (r1.system != r2.system) {
13267                return r1.system ? -1 : 1;
13268            }
13269            if (r1.activityInfo != null) {
13270                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13271            }
13272            if (r1.serviceInfo != null) {
13273                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13274            }
13275            if (r1.providerInfo != null) {
13276                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13277            }
13278            return 0;
13279        }
13280    };
13281
13282    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13283            new Comparator<ProviderInfo>() {
13284        public int compare(ProviderInfo p1, ProviderInfo p2) {
13285            final int v1 = p1.initOrder;
13286            final int v2 = p2.initOrder;
13287            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13288        }
13289    };
13290
13291    @Override
13292    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13293            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13294            final int[] userIds, int[] instantUserIds) {
13295        mHandler.post(new Runnable() {
13296            @Override
13297            public void run() {
13298                try {
13299                    final IActivityManager am = ActivityManager.getService();
13300                    if (am == null) return;
13301                    final int[] resolvedUserIds;
13302                    if (userIds == null) {
13303                        resolvedUserIds = am.getRunningUserIds();
13304                    } else {
13305                        resolvedUserIds = userIds;
13306                    }
13307                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13308                            resolvedUserIds, false);
13309                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13310                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13311                                instantUserIds, true);
13312                    }
13313                } catch (RemoteException ex) {
13314                }
13315            }
13316        });
13317    }
13318
13319    @Override
13320    public void notifyPackageAdded(String packageName) {
13321        final PackageListObserver[] observers;
13322        synchronized (mPackages) {
13323            if (mPackageListObservers.size() == 0) {
13324                return;
13325            }
13326            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13327        }
13328        for (int i = observers.length - 1; i >= 0; --i) {
13329            observers[i].onPackageAdded(packageName);
13330        }
13331    }
13332
13333    @Override
13334    public void notifyPackageRemoved(String packageName) {
13335        final PackageListObserver[] observers;
13336        synchronized (mPackages) {
13337            if (mPackageListObservers.size() == 0) {
13338                return;
13339            }
13340            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13341        }
13342        for (int i = observers.length - 1; i >= 0; --i) {
13343            observers[i].onPackageRemoved(packageName);
13344        }
13345    }
13346
13347    /**
13348     * Sends a broadcast for the given action.
13349     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13350     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13351     * the system and applications allowed to see instant applications to receive package
13352     * lifecycle events for instant applications.
13353     */
13354    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13355            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13356            int[] userIds, boolean isInstantApp)
13357                    throws RemoteException {
13358        for (int id : userIds) {
13359            final Intent intent = new Intent(action,
13360                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13361            final String[] requiredPermissions =
13362                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13363            if (extras != null) {
13364                intent.putExtras(extras);
13365            }
13366            if (targetPkg != null) {
13367                intent.setPackage(targetPkg);
13368            }
13369            // Modify the UID when posting to other users
13370            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13371            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13372                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13373                intent.putExtra(Intent.EXTRA_UID, uid);
13374            }
13375            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13376            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13377            if (DEBUG_BROADCASTS) {
13378                RuntimeException here = new RuntimeException("here");
13379                here.fillInStackTrace();
13380                Slog.d(TAG, "Sending to user " + id + ": "
13381                        + intent.toShortString(false, true, false, false)
13382                        + " " + intent.getExtras(), here);
13383            }
13384            am.broadcastIntent(null, intent, null, finishedReceiver,
13385                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13386                    null, finishedReceiver != null, false, id);
13387        }
13388    }
13389
13390    /**
13391     * Check if the external storage media is available. This is true if there
13392     * is a mounted external storage medium or if the external storage is
13393     * emulated.
13394     */
13395    private boolean isExternalMediaAvailable() {
13396        return mMediaMounted || Environment.isExternalStorageEmulated();
13397    }
13398
13399    @Override
13400    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13401        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13402            return null;
13403        }
13404        if (!isExternalMediaAvailable()) {
13405                // If the external storage is no longer mounted at this point,
13406                // the caller may not have been able to delete all of this
13407                // packages files and can not delete any more.  Bail.
13408            return null;
13409        }
13410        synchronized (mPackages) {
13411            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13412            if (lastPackage != null) {
13413                pkgs.remove(lastPackage);
13414            }
13415            if (pkgs.size() > 0) {
13416                return pkgs.get(0);
13417            }
13418        }
13419        return null;
13420    }
13421
13422    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13423        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13424                userId, andCode ? 1 : 0, packageName);
13425        if (mSystemReady) {
13426            msg.sendToTarget();
13427        } else {
13428            if (mPostSystemReadyMessages == null) {
13429                mPostSystemReadyMessages = new ArrayList<>();
13430            }
13431            mPostSystemReadyMessages.add(msg);
13432        }
13433    }
13434
13435    void startCleaningPackages() {
13436        // reader
13437        if (!isExternalMediaAvailable()) {
13438            return;
13439        }
13440        synchronized (mPackages) {
13441            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13442                return;
13443            }
13444        }
13445        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13446        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13447        IActivityManager am = ActivityManager.getService();
13448        if (am != null) {
13449            int dcsUid = -1;
13450            synchronized (mPackages) {
13451                if (!mDefaultContainerWhitelisted) {
13452                    mDefaultContainerWhitelisted = true;
13453                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13454                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13455                }
13456            }
13457            try {
13458                if (dcsUid > 0) {
13459                    am.backgroundWhitelistUid(dcsUid);
13460                }
13461                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13462                        UserHandle.USER_SYSTEM);
13463            } catch (RemoteException e) {
13464            }
13465        }
13466    }
13467
13468    /**
13469     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13470     * it is acting on behalf on an enterprise or the user).
13471     *
13472     * Note that the ordering of the conditionals in this method is important. The checks we perform
13473     * are as follows, in this order:
13474     *
13475     * 1) If the install is being performed by a system app, we can trust the app to have set the
13476     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13477     *    what it is.
13478     * 2) If the install is being performed by a device or profile owner app, the install reason
13479     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13480     *    set the install reason correctly. If the app targets an older SDK version where install
13481     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13482     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13483     * 3) In all other cases, the install is being performed by a regular app that is neither part
13484     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13485     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13486     *    set to enterprise policy and if so, change it to unknown instead.
13487     */
13488    private int fixUpInstallReason(String installerPackageName, int installerUid,
13489            int installReason) {
13490        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13491                == PERMISSION_GRANTED) {
13492            // If the install is being performed by a system app, we trust that app to have set the
13493            // install reason correctly.
13494            return installReason;
13495        }
13496
13497        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13498            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13499        if (dpm != null) {
13500            ComponentName owner = null;
13501            try {
13502                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13503                if (owner == null) {
13504                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13505                }
13506            } catch (RemoteException e) {
13507            }
13508            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13509                // If the install is being performed by a device or profile owner, the install
13510                // reason should be enterprise policy.
13511                return PackageManager.INSTALL_REASON_POLICY;
13512            }
13513        }
13514
13515        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13516            // If the install is being performed by a regular app (i.e. neither system app nor
13517            // device or profile owner), we have no reason to believe that the app is acting on
13518            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13519            // change it to unknown instead.
13520            return PackageManager.INSTALL_REASON_UNKNOWN;
13521        }
13522
13523        // If the install is being performed by a regular app and the install reason was set to any
13524        // value but enterprise policy, leave the install reason unchanged.
13525        return installReason;
13526    }
13527
13528    void installStage(String packageName, File stagedDir,
13529            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13530            String installerPackageName, int installerUid, UserHandle user,
13531            PackageParser.SigningDetails signingDetails) {
13532        if (DEBUG_INSTANT) {
13533            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13534                Slog.d(TAG, "Ephemeral install of " + packageName);
13535            }
13536        }
13537        final VerificationInfo verificationInfo = new VerificationInfo(
13538                sessionParams.originatingUri, sessionParams.referrerUri,
13539                sessionParams.originatingUid, installerUid);
13540
13541        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13542
13543        final Message msg = mHandler.obtainMessage(INIT_COPY);
13544        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13545                sessionParams.installReason);
13546        final InstallParams params = new InstallParams(origin, null, observer,
13547                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13548                verificationInfo, user, sessionParams.abiOverride,
13549                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13550        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13551        msg.obj = params;
13552
13553        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13554                System.identityHashCode(msg.obj));
13555        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13556                System.identityHashCode(msg.obj));
13557
13558        mHandler.sendMessage(msg);
13559    }
13560
13561    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13562            int userId) {
13563        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13564        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13565        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13566        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13567        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13568                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13569
13570        // Send a session commit broadcast
13571        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13572        info.installReason = pkgSetting.getInstallReason(userId);
13573        info.appPackageName = packageName;
13574        sendSessionCommitBroadcast(info, userId);
13575    }
13576
13577    @Override
13578    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13579            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13580        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13581            return;
13582        }
13583        Bundle extras = new Bundle(1);
13584        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13585        final int uid = UserHandle.getUid(
13586                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13587        extras.putInt(Intent.EXTRA_UID, uid);
13588
13589        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13590                packageName, extras, 0, null, null, userIds, instantUserIds);
13591        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13592            mHandler.post(() -> {
13593                        for (int userId : userIds) {
13594                            sendBootCompletedBroadcastToSystemApp(
13595                                    packageName, includeStopped, userId);
13596                        }
13597                    }
13598            );
13599        }
13600    }
13601
13602    /**
13603     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13604     * automatically without needing an explicit launch.
13605     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13606     */
13607    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13608            int userId) {
13609        // If user is not running, the app didn't miss any broadcast
13610        if (!mUserManagerInternal.isUserRunning(userId)) {
13611            return;
13612        }
13613        final IActivityManager am = ActivityManager.getService();
13614        try {
13615            // Deliver LOCKED_BOOT_COMPLETED first
13616            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13617                    .setPackage(packageName);
13618            if (includeStopped) {
13619                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13620            }
13621            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13622            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13623                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13624
13625            // Deliver BOOT_COMPLETED only if user is unlocked
13626            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13627                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13628                if (includeStopped) {
13629                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13630                }
13631                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13632                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13633            }
13634        } catch (RemoteException e) {
13635            throw e.rethrowFromSystemServer();
13636        }
13637    }
13638
13639    @Override
13640    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13641            int userId) {
13642        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13643        PackageSetting pkgSetting;
13644        final int callingUid = Binder.getCallingUid();
13645        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13646                true /* requireFullPermission */, true /* checkShell */,
13647                "setApplicationHiddenSetting for user " + userId);
13648
13649        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13650            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13651            return false;
13652        }
13653
13654        long callingId = Binder.clearCallingIdentity();
13655        try {
13656            boolean sendAdded = false;
13657            boolean sendRemoved = false;
13658            // writer
13659            synchronized (mPackages) {
13660                pkgSetting = mSettings.mPackages.get(packageName);
13661                if (pkgSetting == null) {
13662                    return false;
13663                }
13664                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13665                    return false;
13666                }
13667                // Do not allow "android" is being disabled
13668                if ("android".equals(packageName)) {
13669                    Slog.w(TAG, "Cannot hide package: android");
13670                    return false;
13671                }
13672                // Cannot hide static shared libs as they are considered
13673                // a part of the using app (emulating static linking). Also
13674                // static libs are installed always on internal storage.
13675                PackageParser.Package pkg = mPackages.get(packageName);
13676                if (pkg != null && pkg.staticSharedLibName != null) {
13677                    Slog.w(TAG, "Cannot hide package: " + packageName
13678                            + " providing static shared library: "
13679                            + pkg.staticSharedLibName);
13680                    return false;
13681                }
13682                // Only allow protected packages to hide themselves.
13683                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13684                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13685                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13686                    return false;
13687                }
13688
13689                if (pkgSetting.getHidden(userId) != hidden) {
13690                    pkgSetting.setHidden(hidden, userId);
13691                    mSettings.writePackageRestrictionsLPr(userId);
13692                    if (hidden) {
13693                        sendRemoved = true;
13694                    } else {
13695                        sendAdded = true;
13696                    }
13697                }
13698            }
13699            if (sendAdded) {
13700                sendPackageAddedForUser(packageName, pkgSetting, userId);
13701                return true;
13702            }
13703            if (sendRemoved) {
13704                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13705                        "hiding pkg");
13706                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13707                return true;
13708            }
13709        } finally {
13710            Binder.restoreCallingIdentity(callingId);
13711        }
13712        return false;
13713    }
13714
13715    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13716            int userId) {
13717        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13718        info.removedPackage = packageName;
13719        info.installerPackageName = pkgSetting.installerPackageName;
13720        info.removedUsers = new int[] {userId};
13721        info.broadcastUsers = new int[] {userId};
13722        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13723        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13724    }
13725
13726    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13727        if (pkgList.length > 0) {
13728            Bundle extras = new Bundle(1);
13729            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13730
13731            sendPackageBroadcast(
13732                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13733                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13734                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13735                    new int[] {userId}, null);
13736        }
13737    }
13738
13739    /**
13740     * Returns true if application is not found or there was an error. Otherwise it returns
13741     * the hidden state of the package for the given user.
13742     */
13743    @Override
13744    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13745        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13746        final int callingUid = Binder.getCallingUid();
13747        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13748                true /* requireFullPermission */, false /* checkShell */,
13749                "getApplicationHidden for user " + userId);
13750        PackageSetting ps;
13751        long callingId = Binder.clearCallingIdentity();
13752        try {
13753            // writer
13754            synchronized (mPackages) {
13755                ps = mSettings.mPackages.get(packageName);
13756                if (ps == null) {
13757                    return true;
13758                }
13759                if (filterAppAccessLPr(ps, callingUid, userId)) {
13760                    return true;
13761                }
13762                return ps.getHidden(userId);
13763            }
13764        } finally {
13765            Binder.restoreCallingIdentity(callingId);
13766        }
13767    }
13768
13769    /**
13770     * @hide
13771     */
13772    @Override
13773    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13774            int installReason) {
13775        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13776                null);
13777        PackageSetting pkgSetting;
13778        final int callingUid = Binder.getCallingUid();
13779        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13780                true /* requireFullPermission */, true /* checkShell */,
13781                "installExistingPackage for user " + userId);
13782        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13783            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13784        }
13785
13786        long callingId = Binder.clearCallingIdentity();
13787        try {
13788            boolean installed = false;
13789            final boolean instantApp =
13790                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13791            final boolean fullApp =
13792                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13793
13794            // writer
13795            synchronized (mPackages) {
13796                pkgSetting = mSettings.mPackages.get(packageName);
13797                if (pkgSetting == null) {
13798                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13799                }
13800                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13801                    // only allow the existing package to be used if it's installed as a full
13802                    // application for at least one user
13803                    boolean installAllowed = false;
13804                    for (int checkUserId : sUserManager.getUserIds()) {
13805                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13806                        if (installAllowed) {
13807                            break;
13808                        }
13809                    }
13810                    if (!installAllowed) {
13811                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13812                    }
13813                }
13814                if (!pkgSetting.getInstalled(userId)) {
13815                    pkgSetting.setInstalled(true, userId);
13816                    pkgSetting.setHidden(false, userId);
13817                    pkgSetting.setInstallReason(installReason, userId);
13818                    mSettings.writePackageRestrictionsLPr(userId);
13819                    mSettings.writeKernelMappingLPr(pkgSetting);
13820                    installed = true;
13821                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13822                    // upgrade app from instant to full; we don't allow app downgrade
13823                    installed = true;
13824                }
13825                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13826            }
13827
13828            if (installed) {
13829                if (pkgSetting.pkg != null) {
13830                    synchronized (mInstallLock) {
13831                        // We don't need to freeze for a brand new install
13832                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13833                    }
13834                }
13835                sendPackageAddedForUser(packageName, pkgSetting, userId);
13836                synchronized (mPackages) {
13837                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13838                }
13839            }
13840        } finally {
13841            Binder.restoreCallingIdentity(callingId);
13842        }
13843
13844        return PackageManager.INSTALL_SUCCEEDED;
13845    }
13846
13847    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13848            boolean instantApp, boolean fullApp) {
13849        // no state specified; do nothing
13850        if (!instantApp && !fullApp) {
13851            return;
13852        }
13853        if (userId != UserHandle.USER_ALL) {
13854            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13855                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13856            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13857                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13858            }
13859        } else {
13860            for (int currentUserId : sUserManager.getUserIds()) {
13861                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13862                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13863                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13864                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13865                }
13866            }
13867        }
13868    }
13869
13870    boolean isUserRestricted(int userId, String restrictionKey) {
13871        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13872        if (restrictions.getBoolean(restrictionKey, false)) {
13873            Log.w(TAG, "User is restricted: " + restrictionKey);
13874            return true;
13875        }
13876        return false;
13877    }
13878
13879    @Override
13880    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13881            int userId) {
13882        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13883        final int callingUid = Binder.getCallingUid();
13884        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13885                true /* requireFullPermission */, true /* checkShell */,
13886                "setPackagesSuspended for user " + userId);
13887
13888        if (ArrayUtils.isEmpty(packageNames)) {
13889            return packageNames;
13890        }
13891
13892        // List of package names for whom the suspended state has changed.
13893        List<String> changedPackages = new ArrayList<>(packageNames.length);
13894        // List of package names for whom the suspended state is not set as requested in this
13895        // method.
13896        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13897        long callingId = Binder.clearCallingIdentity();
13898        try {
13899            for (int i = 0; i < packageNames.length; i++) {
13900                String packageName = packageNames[i];
13901                boolean changed = false;
13902                final int appId;
13903                synchronized (mPackages) {
13904                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13905                    if (pkgSetting == null
13906                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13907                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13908                                + "\". Skipping suspending/un-suspending.");
13909                        unactionedPackages.add(packageName);
13910                        continue;
13911                    }
13912                    appId = pkgSetting.appId;
13913                    if (pkgSetting.getSuspended(userId) != suspended) {
13914                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13915                            unactionedPackages.add(packageName);
13916                            continue;
13917                        }
13918                        pkgSetting.setSuspended(suspended, userId);
13919                        mSettings.writePackageRestrictionsLPr(userId);
13920                        changed = true;
13921                        changedPackages.add(packageName);
13922                    }
13923                }
13924
13925                if (changed && suspended) {
13926                    killApplication(packageName, UserHandle.getUid(userId, appId),
13927                            "suspending package");
13928                }
13929            }
13930        } finally {
13931            Binder.restoreCallingIdentity(callingId);
13932        }
13933
13934        if (!changedPackages.isEmpty()) {
13935            sendPackagesSuspendedForUser(changedPackages.toArray(
13936                    new String[changedPackages.size()]), userId, suspended);
13937        }
13938
13939        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13940    }
13941
13942    @Override
13943    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13944        final int callingUid = Binder.getCallingUid();
13945        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13946                true /* requireFullPermission */, false /* checkShell */,
13947                "isPackageSuspendedForUser for user " + userId);
13948        synchronized (mPackages) {
13949            final PackageSetting ps = mSettings.mPackages.get(packageName);
13950            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13951                throw new IllegalArgumentException("Unknown target package: " + packageName);
13952            }
13953            return ps.getSuspended(userId);
13954        }
13955    }
13956
13957    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13958        if (isPackageDeviceAdmin(packageName, userId)) {
13959            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13960                    + "\": has an active device admin");
13961            return false;
13962        }
13963
13964        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13965        if (packageName.equals(activeLauncherPackageName)) {
13966            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13967                    + "\": contains the active launcher");
13968            return false;
13969        }
13970
13971        if (packageName.equals(mRequiredInstallerPackage)) {
13972            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13973                    + "\": required for package installation");
13974            return false;
13975        }
13976
13977        if (packageName.equals(mRequiredUninstallerPackage)) {
13978            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13979                    + "\": required for package uninstallation");
13980            return false;
13981        }
13982
13983        if (packageName.equals(mRequiredVerifierPackage)) {
13984            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13985                    + "\": required for package verification");
13986            return false;
13987        }
13988
13989        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13990            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13991                    + "\": is the default dialer");
13992            return false;
13993        }
13994
13995        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13996            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13997                    + "\": protected package");
13998            return false;
13999        }
14000
14001        // Cannot suspend static shared libs as they are considered
14002        // a part of the using app (emulating static linking). Also
14003        // static libs are installed always on internal storage.
14004        PackageParser.Package pkg = mPackages.get(packageName);
14005        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14006            Slog.w(TAG, "Cannot suspend package: " + packageName
14007                    + " providing static shared library: "
14008                    + pkg.staticSharedLibName);
14009            return false;
14010        }
14011
14012        return true;
14013    }
14014
14015    private String getActiveLauncherPackageName(int userId) {
14016        Intent intent = new Intent(Intent.ACTION_MAIN);
14017        intent.addCategory(Intent.CATEGORY_HOME);
14018        ResolveInfo resolveInfo = resolveIntent(
14019                intent,
14020                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14021                PackageManager.MATCH_DEFAULT_ONLY,
14022                userId);
14023
14024        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14025    }
14026
14027    private String getDefaultDialerPackageName(int userId) {
14028        synchronized (mPackages) {
14029            return mSettings.getDefaultDialerPackageNameLPw(userId);
14030        }
14031    }
14032
14033    @Override
14034    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14035        mContext.enforceCallingOrSelfPermission(
14036                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14037                "Only package verification agents can verify applications");
14038
14039        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14040        final PackageVerificationResponse response = new PackageVerificationResponse(
14041                verificationCode, Binder.getCallingUid());
14042        msg.arg1 = id;
14043        msg.obj = response;
14044        mHandler.sendMessage(msg);
14045    }
14046
14047    @Override
14048    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14049            long millisecondsToDelay) {
14050        mContext.enforceCallingOrSelfPermission(
14051                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14052                "Only package verification agents can extend verification timeouts");
14053
14054        final PackageVerificationState state = mPendingVerification.get(id);
14055        final PackageVerificationResponse response = new PackageVerificationResponse(
14056                verificationCodeAtTimeout, Binder.getCallingUid());
14057
14058        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14059            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14060        }
14061        if (millisecondsToDelay < 0) {
14062            millisecondsToDelay = 0;
14063        }
14064        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14065                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14066            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14067        }
14068
14069        if ((state != null) && !state.timeoutExtended()) {
14070            state.extendTimeout();
14071
14072            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14073            msg.arg1 = id;
14074            msg.obj = response;
14075            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14076        }
14077    }
14078
14079    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14080            int verificationCode, UserHandle user) {
14081        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14082        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14083        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14084        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14085        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14086
14087        mContext.sendBroadcastAsUser(intent, user,
14088                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14089    }
14090
14091    private ComponentName matchComponentForVerifier(String packageName,
14092            List<ResolveInfo> receivers) {
14093        ActivityInfo targetReceiver = null;
14094
14095        final int NR = receivers.size();
14096        for (int i = 0; i < NR; i++) {
14097            final ResolveInfo info = receivers.get(i);
14098            if (info.activityInfo == null) {
14099                continue;
14100            }
14101
14102            if (packageName.equals(info.activityInfo.packageName)) {
14103                targetReceiver = info.activityInfo;
14104                break;
14105            }
14106        }
14107
14108        if (targetReceiver == null) {
14109            return null;
14110        }
14111
14112        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14113    }
14114
14115    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14116            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14117        if (pkgInfo.verifiers.length == 0) {
14118            return null;
14119        }
14120
14121        final int N = pkgInfo.verifiers.length;
14122        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14123        for (int i = 0; i < N; i++) {
14124            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14125
14126            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14127                    receivers);
14128            if (comp == null) {
14129                continue;
14130            }
14131
14132            final int verifierUid = getUidForVerifier(verifierInfo);
14133            if (verifierUid == -1) {
14134                continue;
14135            }
14136
14137            if (DEBUG_VERIFY) {
14138                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14139                        + " with the correct signature");
14140            }
14141            sufficientVerifiers.add(comp);
14142            verificationState.addSufficientVerifier(verifierUid);
14143        }
14144
14145        return sufficientVerifiers;
14146    }
14147
14148    private int getUidForVerifier(VerifierInfo verifierInfo) {
14149        synchronized (mPackages) {
14150            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14151            if (pkg == null) {
14152                return -1;
14153            } else if (pkg.mSigningDetails.signatures.length != 1) {
14154                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14155                        + " has more than one signature; ignoring");
14156                return -1;
14157            }
14158
14159            /*
14160             * If the public key of the package's signature does not match
14161             * our expected public key, then this is a different package and
14162             * we should skip.
14163             */
14164
14165            final byte[] expectedPublicKey;
14166            try {
14167                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14168                final PublicKey publicKey = verifierSig.getPublicKey();
14169                expectedPublicKey = publicKey.getEncoded();
14170            } catch (CertificateException e) {
14171                return -1;
14172            }
14173
14174            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14175
14176            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14177                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14178                        + " does not have the expected public key; ignoring");
14179                return -1;
14180            }
14181
14182            return pkg.applicationInfo.uid;
14183        }
14184    }
14185
14186    @Override
14187    public void finishPackageInstall(int token, boolean didLaunch) {
14188        enforceSystemOrRoot("Only the system is allowed to finish installs");
14189
14190        if (DEBUG_INSTALL) {
14191            Slog.v(TAG, "BM finishing package install for " + token);
14192        }
14193        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14194
14195        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14196        mHandler.sendMessage(msg);
14197    }
14198
14199    /**
14200     * Get the verification agent timeout.  Used for both the APK verifier and the
14201     * intent filter verifier.
14202     *
14203     * @return verification timeout in milliseconds
14204     */
14205    private long getVerificationTimeout() {
14206        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14207                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14208                DEFAULT_VERIFICATION_TIMEOUT);
14209    }
14210
14211    /**
14212     * Get the default verification agent response code.
14213     *
14214     * @return default verification response code
14215     */
14216    private int getDefaultVerificationResponse(UserHandle user) {
14217        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14218            return PackageManager.VERIFICATION_REJECT;
14219        }
14220        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14221                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14222                DEFAULT_VERIFICATION_RESPONSE);
14223    }
14224
14225    /**
14226     * Check whether or not package verification has been enabled.
14227     *
14228     * @return true if verification should be performed
14229     */
14230    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14231        if (!DEFAULT_VERIFY_ENABLE) {
14232            return false;
14233        }
14234
14235        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14236
14237        // Check if installing from ADB
14238        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14239            // Do not run verification in a test harness environment
14240            if (ActivityManager.isRunningInTestHarness()) {
14241                return false;
14242            }
14243            if (ensureVerifyAppsEnabled) {
14244                return true;
14245            }
14246            // Check if the developer does not want package verification for ADB installs
14247            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14248                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14249                return false;
14250            }
14251        } else {
14252            // only when not installed from ADB, skip verification for instant apps when
14253            // the installer and verifier are the same.
14254            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14255                if (mInstantAppInstallerActivity != null
14256                        && mInstantAppInstallerActivity.packageName.equals(
14257                                mRequiredVerifierPackage)) {
14258                    try {
14259                        mContext.getSystemService(AppOpsManager.class)
14260                                .checkPackage(installerUid, mRequiredVerifierPackage);
14261                        if (DEBUG_VERIFY) {
14262                            Slog.i(TAG, "disable verification for instant app");
14263                        }
14264                        return false;
14265                    } catch (SecurityException ignore) { }
14266                }
14267            }
14268        }
14269
14270        if (ensureVerifyAppsEnabled) {
14271            return true;
14272        }
14273
14274        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14275                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14276    }
14277
14278    @Override
14279    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14280            throws RemoteException {
14281        mContext.enforceCallingOrSelfPermission(
14282                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14283                "Only intentfilter verification agents can verify applications");
14284
14285        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14286        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14287                Binder.getCallingUid(), verificationCode, failedDomains);
14288        msg.arg1 = id;
14289        msg.obj = response;
14290        mHandler.sendMessage(msg);
14291    }
14292
14293    @Override
14294    public int getIntentVerificationStatus(String packageName, int userId) {
14295        final int callingUid = Binder.getCallingUid();
14296        if (UserHandle.getUserId(callingUid) != userId) {
14297            mContext.enforceCallingOrSelfPermission(
14298                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14299                    "getIntentVerificationStatus" + userId);
14300        }
14301        if (getInstantAppPackageName(callingUid) != null) {
14302            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14303        }
14304        synchronized (mPackages) {
14305            final PackageSetting ps = mSettings.mPackages.get(packageName);
14306            if (ps == null
14307                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14308                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14309            }
14310            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14311        }
14312    }
14313
14314    @Override
14315    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14316        mContext.enforceCallingOrSelfPermission(
14317                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14318
14319        boolean result = false;
14320        synchronized (mPackages) {
14321            final PackageSetting ps = mSettings.mPackages.get(packageName);
14322            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14323                return false;
14324            }
14325            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14326        }
14327        if (result) {
14328            scheduleWritePackageRestrictionsLocked(userId);
14329        }
14330        return result;
14331    }
14332
14333    @Override
14334    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14335            String packageName) {
14336        final int callingUid = Binder.getCallingUid();
14337        if (getInstantAppPackageName(callingUid) != null) {
14338            return ParceledListSlice.emptyList();
14339        }
14340        synchronized (mPackages) {
14341            final PackageSetting ps = mSettings.mPackages.get(packageName);
14342            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14343                return ParceledListSlice.emptyList();
14344            }
14345            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14346        }
14347    }
14348
14349    @Override
14350    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14351        if (TextUtils.isEmpty(packageName)) {
14352            return ParceledListSlice.emptyList();
14353        }
14354        final int callingUid = Binder.getCallingUid();
14355        final int callingUserId = UserHandle.getUserId(callingUid);
14356        synchronized (mPackages) {
14357            PackageParser.Package pkg = mPackages.get(packageName);
14358            if (pkg == null || pkg.activities == null) {
14359                return ParceledListSlice.emptyList();
14360            }
14361            if (pkg.mExtras == null) {
14362                return ParceledListSlice.emptyList();
14363            }
14364            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14365            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14366                return ParceledListSlice.emptyList();
14367            }
14368            final int count = pkg.activities.size();
14369            ArrayList<IntentFilter> result = new ArrayList<>();
14370            for (int n=0; n<count; n++) {
14371                PackageParser.Activity activity = pkg.activities.get(n);
14372                if (activity.intents != null && activity.intents.size() > 0) {
14373                    result.addAll(activity.intents);
14374                }
14375            }
14376            return new ParceledListSlice<>(result);
14377        }
14378    }
14379
14380    @Override
14381    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14382        mContext.enforceCallingOrSelfPermission(
14383                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14384        if (UserHandle.getCallingUserId() != userId) {
14385            mContext.enforceCallingOrSelfPermission(
14386                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14387        }
14388
14389        synchronized (mPackages) {
14390            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14391            if (packageName != null) {
14392                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14393                        packageName, userId);
14394            }
14395            return result;
14396        }
14397    }
14398
14399    @Override
14400    public String getDefaultBrowserPackageName(int userId) {
14401        if (UserHandle.getCallingUserId() != userId) {
14402            mContext.enforceCallingOrSelfPermission(
14403                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14404        }
14405        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14406            return null;
14407        }
14408        synchronized (mPackages) {
14409            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14410        }
14411    }
14412
14413    /**
14414     * Get the "allow unknown sources" setting.
14415     *
14416     * @return the current "allow unknown sources" setting
14417     */
14418    private int getUnknownSourcesSettings() {
14419        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14420                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14421                -1);
14422    }
14423
14424    @Override
14425    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14426        final int callingUid = Binder.getCallingUid();
14427        if (getInstantAppPackageName(callingUid) != null) {
14428            return;
14429        }
14430        // writer
14431        synchronized (mPackages) {
14432            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14433            if (targetPackageSetting == null
14434                    || filterAppAccessLPr(
14435                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14436                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14437            }
14438
14439            PackageSetting installerPackageSetting;
14440            if (installerPackageName != null) {
14441                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14442                if (installerPackageSetting == null) {
14443                    throw new IllegalArgumentException("Unknown installer package: "
14444                            + installerPackageName);
14445                }
14446            } else {
14447                installerPackageSetting = null;
14448            }
14449
14450            Signature[] callerSignature;
14451            Object obj = mSettings.getUserIdLPr(callingUid);
14452            if (obj != null) {
14453                if (obj instanceof SharedUserSetting) {
14454                    callerSignature =
14455                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14456                } else if (obj instanceof PackageSetting) {
14457                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14458                } else {
14459                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14460                }
14461            } else {
14462                throw new SecurityException("Unknown calling UID: " + callingUid);
14463            }
14464
14465            // Verify: can't set installerPackageName to a package that is
14466            // not signed with the same cert as the caller.
14467            if (installerPackageSetting != null) {
14468                if (compareSignatures(callerSignature,
14469                        installerPackageSetting.signatures.mSigningDetails.signatures)
14470                        != PackageManager.SIGNATURE_MATCH) {
14471                    throw new SecurityException(
14472                            "Caller does not have same cert as new installer package "
14473                            + installerPackageName);
14474                }
14475            }
14476
14477            // Verify: if target already has an installer package, it must
14478            // be signed with the same cert as the caller.
14479            if (targetPackageSetting.installerPackageName != null) {
14480                PackageSetting setting = mSettings.mPackages.get(
14481                        targetPackageSetting.installerPackageName);
14482                // If the currently set package isn't valid, then it's always
14483                // okay to change it.
14484                if (setting != null) {
14485                    if (compareSignatures(callerSignature,
14486                            setting.signatures.mSigningDetails.signatures)
14487                            != PackageManager.SIGNATURE_MATCH) {
14488                        throw new SecurityException(
14489                                "Caller does not have same cert as old installer package "
14490                                + targetPackageSetting.installerPackageName);
14491                    }
14492                }
14493            }
14494
14495            // Okay!
14496            targetPackageSetting.installerPackageName = installerPackageName;
14497            if (installerPackageName != null) {
14498                mSettings.mInstallerPackages.add(installerPackageName);
14499            }
14500            scheduleWriteSettingsLocked();
14501        }
14502    }
14503
14504    @Override
14505    public void setApplicationCategoryHint(String packageName, int categoryHint,
14506            String callerPackageName) {
14507        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14508            throw new SecurityException("Instant applications don't have access to this method");
14509        }
14510        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14511                callerPackageName);
14512        synchronized (mPackages) {
14513            PackageSetting ps = mSettings.mPackages.get(packageName);
14514            if (ps == null) {
14515                throw new IllegalArgumentException("Unknown target package " + packageName);
14516            }
14517            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14518                throw new IllegalArgumentException("Unknown target package " + packageName);
14519            }
14520            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14521                throw new IllegalArgumentException("Calling package " + callerPackageName
14522                        + " is not installer for " + packageName);
14523            }
14524
14525            if (ps.categoryHint != categoryHint) {
14526                ps.categoryHint = categoryHint;
14527                scheduleWriteSettingsLocked();
14528            }
14529        }
14530    }
14531
14532    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14533        // Queue up an async operation since the package installation may take a little while.
14534        mHandler.post(new Runnable() {
14535            public void run() {
14536                mHandler.removeCallbacks(this);
14537                 // Result object to be returned
14538                PackageInstalledInfo res = new PackageInstalledInfo();
14539                res.setReturnCode(currentStatus);
14540                res.uid = -1;
14541                res.pkg = null;
14542                res.removedInfo = null;
14543                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14544                    args.doPreInstall(res.returnCode);
14545                    synchronized (mInstallLock) {
14546                        installPackageTracedLI(args, res);
14547                    }
14548                    args.doPostInstall(res.returnCode, res.uid);
14549                }
14550
14551                // A restore should be performed at this point if (a) the install
14552                // succeeded, (b) the operation is not an update, and (c) the new
14553                // package has not opted out of backup participation.
14554                final boolean update = res.removedInfo != null
14555                        && res.removedInfo.removedPackage != null;
14556                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14557                boolean doRestore = !update
14558                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14559
14560                // Set up the post-install work request bookkeeping.  This will be used
14561                // and cleaned up by the post-install event handling regardless of whether
14562                // there's a restore pass performed.  Token values are >= 1.
14563                int token;
14564                if (mNextInstallToken < 0) mNextInstallToken = 1;
14565                token = mNextInstallToken++;
14566
14567                PostInstallData data = new PostInstallData(args, res);
14568                mRunningInstalls.put(token, data);
14569                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14570
14571                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14572                    // Pass responsibility to the Backup Manager.  It will perform a
14573                    // restore if appropriate, then pass responsibility back to the
14574                    // Package Manager to run the post-install observer callbacks
14575                    // and broadcasts.
14576                    IBackupManager bm = IBackupManager.Stub.asInterface(
14577                            ServiceManager.getService(Context.BACKUP_SERVICE));
14578                    if (bm != null) {
14579                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14580                                + " to BM for possible restore");
14581                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14582                        try {
14583                            // TODO: http://b/22388012
14584                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14585                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14586                            } else {
14587                                doRestore = false;
14588                            }
14589                        } catch (RemoteException e) {
14590                            // can't happen; the backup manager is local
14591                        } catch (Exception e) {
14592                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14593                            doRestore = false;
14594                        }
14595                    } else {
14596                        Slog.e(TAG, "Backup Manager not found!");
14597                        doRestore = false;
14598                    }
14599                }
14600
14601                if (!doRestore) {
14602                    // No restore possible, or the Backup Manager was mysteriously not
14603                    // available -- just fire the post-install work request directly.
14604                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14605
14606                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14607
14608                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14609                    mHandler.sendMessage(msg);
14610                }
14611            }
14612        });
14613    }
14614
14615    /**
14616     * Callback from PackageSettings whenever an app is first transitioned out of the
14617     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14618     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14619     * here whether the app is the target of an ongoing install, and only send the
14620     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14621     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14622     * handling.
14623     */
14624    void notifyFirstLaunch(final String packageName, final String installerPackage,
14625            final int userId) {
14626        // Serialize this with the rest of the install-process message chain.  In the
14627        // restore-at-install case, this Runnable will necessarily run before the
14628        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14629        // are coherent.  In the non-restore case, the app has already completed install
14630        // and been launched through some other means, so it is not in a problematic
14631        // state for observers to see the FIRST_LAUNCH signal.
14632        mHandler.post(new Runnable() {
14633            @Override
14634            public void run() {
14635                for (int i = 0; i < mRunningInstalls.size(); i++) {
14636                    final PostInstallData data = mRunningInstalls.valueAt(i);
14637                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14638                        continue;
14639                    }
14640                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14641                        // right package; but is it for the right user?
14642                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14643                            if (userId == data.res.newUsers[uIndex]) {
14644                                if (DEBUG_BACKUP) {
14645                                    Slog.i(TAG, "Package " + packageName
14646                                            + " being restored so deferring FIRST_LAUNCH");
14647                                }
14648                                return;
14649                            }
14650                        }
14651                    }
14652                }
14653                // didn't find it, so not being restored
14654                if (DEBUG_BACKUP) {
14655                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14656                }
14657                final boolean isInstantApp = isInstantApp(packageName, userId);
14658                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14659                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14660                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14661            }
14662        });
14663    }
14664
14665    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14666            int[] userIds, int[] instantUserIds) {
14667        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14668                installerPkg, null, userIds, instantUserIds);
14669    }
14670
14671    private abstract class HandlerParams {
14672        private static final int MAX_RETRIES = 4;
14673
14674        /**
14675         * Number of times startCopy() has been attempted and had a non-fatal
14676         * error.
14677         */
14678        private int mRetries = 0;
14679
14680        /** User handle for the user requesting the information or installation. */
14681        private final UserHandle mUser;
14682        String traceMethod;
14683        int traceCookie;
14684
14685        HandlerParams(UserHandle user) {
14686            mUser = user;
14687        }
14688
14689        UserHandle getUser() {
14690            return mUser;
14691        }
14692
14693        HandlerParams setTraceMethod(String traceMethod) {
14694            this.traceMethod = traceMethod;
14695            return this;
14696        }
14697
14698        HandlerParams setTraceCookie(int traceCookie) {
14699            this.traceCookie = traceCookie;
14700            return this;
14701        }
14702
14703        final boolean startCopy() {
14704            boolean res;
14705            try {
14706                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14707
14708                if (++mRetries > MAX_RETRIES) {
14709                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14710                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14711                    handleServiceError();
14712                    return false;
14713                } else {
14714                    handleStartCopy();
14715                    res = true;
14716                }
14717            } catch (RemoteException e) {
14718                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14719                mHandler.sendEmptyMessage(MCS_RECONNECT);
14720                res = false;
14721            }
14722            handleReturnCode();
14723            return res;
14724        }
14725
14726        final void serviceError() {
14727            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14728            handleServiceError();
14729            handleReturnCode();
14730        }
14731
14732        abstract void handleStartCopy() throws RemoteException;
14733        abstract void handleServiceError();
14734        abstract void handleReturnCode();
14735    }
14736
14737    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14738        for (File path : paths) {
14739            try {
14740                mcs.clearDirectory(path.getAbsolutePath());
14741            } catch (RemoteException e) {
14742            }
14743        }
14744    }
14745
14746    static class OriginInfo {
14747        /**
14748         * Location where install is coming from, before it has been
14749         * copied/renamed into place. This could be a single monolithic APK
14750         * file, or a cluster directory. This location may be untrusted.
14751         */
14752        final File file;
14753
14754        /**
14755         * Flag indicating that {@link #file} or {@link #cid} has already been
14756         * staged, meaning downstream users don't need to defensively copy the
14757         * contents.
14758         */
14759        final boolean staged;
14760
14761        /**
14762         * Flag indicating that {@link #file} or {@link #cid} is an already
14763         * installed app that is being moved.
14764         */
14765        final boolean existing;
14766
14767        final String resolvedPath;
14768        final File resolvedFile;
14769
14770        static OriginInfo fromNothing() {
14771            return new OriginInfo(null, false, false);
14772        }
14773
14774        static OriginInfo fromUntrustedFile(File file) {
14775            return new OriginInfo(file, false, false);
14776        }
14777
14778        static OriginInfo fromExistingFile(File file) {
14779            return new OriginInfo(file, false, true);
14780        }
14781
14782        static OriginInfo fromStagedFile(File file) {
14783            return new OriginInfo(file, true, false);
14784        }
14785
14786        private OriginInfo(File file, boolean staged, boolean existing) {
14787            this.file = file;
14788            this.staged = staged;
14789            this.existing = existing;
14790
14791            if (file != null) {
14792                resolvedPath = file.getAbsolutePath();
14793                resolvedFile = file;
14794            } else {
14795                resolvedPath = null;
14796                resolvedFile = null;
14797            }
14798        }
14799    }
14800
14801    static class MoveInfo {
14802        final int moveId;
14803        final String fromUuid;
14804        final String toUuid;
14805        final String packageName;
14806        final String dataAppName;
14807        final int appId;
14808        final String seinfo;
14809        final int targetSdkVersion;
14810
14811        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14812                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14813            this.moveId = moveId;
14814            this.fromUuid = fromUuid;
14815            this.toUuid = toUuid;
14816            this.packageName = packageName;
14817            this.dataAppName = dataAppName;
14818            this.appId = appId;
14819            this.seinfo = seinfo;
14820            this.targetSdkVersion = targetSdkVersion;
14821        }
14822    }
14823
14824    static class VerificationInfo {
14825        /** A constant used to indicate that a uid value is not present. */
14826        public static final int NO_UID = -1;
14827
14828        /** URI referencing where the package was downloaded from. */
14829        final Uri originatingUri;
14830
14831        /** HTTP referrer URI associated with the originatingURI. */
14832        final Uri referrer;
14833
14834        /** UID of the application that the install request originated from. */
14835        final int originatingUid;
14836
14837        /** UID of application requesting the install */
14838        final int installerUid;
14839
14840        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14841            this.originatingUri = originatingUri;
14842            this.referrer = referrer;
14843            this.originatingUid = originatingUid;
14844            this.installerUid = installerUid;
14845        }
14846    }
14847
14848    class InstallParams extends HandlerParams {
14849        final OriginInfo origin;
14850        final MoveInfo move;
14851        final IPackageInstallObserver2 observer;
14852        int installFlags;
14853        final String installerPackageName;
14854        final String volumeUuid;
14855        private InstallArgs mArgs;
14856        private int mRet;
14857        final String packageAbiOverride;
14858        final String[] grantedRuntimePermissions;
14859        final VerificationInfo verificationInfo;
14860        final PackageParser.SigningDetails signingDetails;
14861        final int installReason;
14862
14863        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14864                int installFlags, String installerPackageName, String volumeUuid,
14865                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14866                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14867            super(user);
14868            this.origin = origin;
14869            this.move = move;
14870            this.observer = observer;
14871            this.installFlags = installFlags;
14872            this.installerPackageName = installerPackageName;
14873            this.volumeUuid = volumeUuid;
14874            this.verificationInfo = verificationInfo;
14875            this.packageAbiOverride = packageAbiOverride;
14876            this.grantedRuntimePermissions = grantedPermissions;
14877            this.signingDetails = signingDetails;
14878            this.installReason = installReason;
14879        }
14880
14881        @Override
14882        public String toString() {
14883            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14884                    + " file=" + origin.file + "}";
14885        }
14886
14887        private int installLocationPolicy(PackageInfoLite pkgLite) {
14888            String packageName = pkgLite.packageName;
14889            int installLocation = pkgLite.installLocation;
14890            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14891            // reader
14892            synchronized (mPackages) {
14893                // Currently installed package which the new package is attempting to replace or
14894                // null if no such package is installed.
14895                PackageParser.Package installedPkg = mPackages.get(packageName);
14896                // Package which currently owns the data which the new package will own if installed.
14897                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14898                // will be null whereas dataOwnerPkg will contain information about the package
14899                // which was uninstalled while keeping its data.
14900                PackageParser.Package dataOwnerPkg = installedPkg;
14901                if (dataOwnerPkg  == null) {
14902                    PackageSetting ps = mSettings.mPackages.get(packageName);
14903                    if (ps != null) {
14904                        dataOwnerPkg = ps.pkg;
14905                    }
14906                }
14907
14908                if (dataOwnerPkg != null) {
14909                    // If installed, the package will get access to data left on the device by its
14910                    // predecessor. As a security measure, this is permited only if this is not a
14911                    // version downgrade or if the predecessor package is marked as debuggable and
14912                    // a downgrade is explicitly requested.
14913                    //
14914                    // On debuggable platform builds, downgrades are permitted even for
14915                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14916                    // not offer security guarantees and thus it's OK to disable some security
14917                    // mechanisms to make debugging/testing easier on those builds. However, even on
14918                    // debuggable builds downgrades of packages are permitted only if requested via
14919                    // installFlags. This is because we aim to keep the behavior of debuggable
14920                    // platform builds as close as possible to the behavior of non-debuggable
14921                    // platform builds.
14922                    final boolean downgradeRequested =
14923                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14924                    final boolean packageDebuggable =
14925                                (dataOwnerPkg.applicationInfo.flags
14926                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14927                    final boolean downgradePermitted =
14928                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14929                    if (!downgradePermitted) {
14930                        try {
14931                            checkDowngrade(dataOwnerPkg, pkgLite);
14932                        } catch (PackageManagerException e) {
14933                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14934                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14935                        }
14936                    }
14937                }
14938
14939                if (installedPkg != null) {
14940                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14941                        // Check for updated system application.
14942                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14943                            if (onSd) {
14944                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14945                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14946                            }
14947                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14948                        } else {
14949                            if (onSd) {
14950                                // Install flag overrides everything.
14951                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14952                            }
14953                            // If current upgrade specifies particular preference
14954                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14955                                // Application explicitly specified internal.
14956                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14957                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14958                                // App explictly prefers external. Let policy decide
14959                            } else {
14960                                // Prefer previous location
14961                                if (isExternal(installedPkg)) {
14962                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14963                                }
14964                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14965                            }
14966                        }
14967                    } else {
14968                        // Invalid install. Return error code
14969                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14970                    }
14971                }
14972            }
14973            // All the special cases have been taken care of.
14974            // Return result based on recommended install location.
14975            if (onSd) {
14976                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14977            }
14978            return pkgLite.recommendedInstallLocation;
14979        }
14980
14981        /*
14982         * Invoke remote method to get package information and install
14983         * location values. Override install location based on default
14984         * policy if needed and then create install arguments based
14985         * on the install location.
14986         */
14987        public void handleStartCopy() throws RemoteException {
14988            int ret = PackageManager.INSTALL_SUCCEEDED;
14989
14990            // If we're already staged, we've firmly committed to an install location
14991            if (origin.staged) {
14992                if (origin.file != null) {
14993                    installFlags |= PackageManager.INSTALL_INTERNAL;
14994                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14995                } else {
14996                    throw new IllegalStateException("Invalid stage location");
14997                }
14998            }
14999
15000            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15001            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15002            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15003            PackageInfoLite pkgLite = null;
15004
15005            if (onInt && onSd) {
15006                // Check if both bits are set.
15007                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15008                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15009            } else if (onSd && ephemeral) {
15010                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15011                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15012            } else {
15013                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15014                        packageAbiOverride);
15015
15016                if (DEBUG_INSTANT && ephemeral) {
15017                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15018                }
15019
15020                /*
15021                 * If we have too little free space, try to free cache
15022                 * before giving up.
15023                 */
15024                if (!origin.staged && pkgLite.recommendedInstallLocation
15025                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15026                    // TODO: focus freeing disk space on the target device
15027                    final StorageManager storage = StorageManager.from(mContext);
15028                    final long lowThreshold = storage.getStorageLowBytes(
15029                            Environment.getDataDirectory());
15030
15031                    final long sizeBytes = mContainerService.calculateInstalledSize(
15032                            origin.resolvedPath, packageAbiOverride);
15033
15034                    try {
15035                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15036                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15037                                installFlags, packageAbiOverride);
15038                    } catch (InstallerException e) {
15039                        Slog.w(TAG, "Failed to free cache", e);
15040                    }
15041
15042                    /*
15043                     * The cache free must have deleted the file we
15044                     * downloaded to install.
15045                     *
15046                     * TODO: fix the "freeCache" call to not delete
15047                     *       the file we care about.
15048                     */
15049                    if (pkgLite.recommendedInstallLocation
15050                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15051                        pkgLite.recommendedInstallLocation
15052                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15053                    }
15054                }
15055            }
15056
15057            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15058                int loc = pkgLite.recommendedInstallLocation;
15059                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15060                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15061                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15062                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15063                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15064                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15065                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15066                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15067                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15068                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15069                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15070                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15071                } else {
15072                    // Override with defaults if needed.
15073                    loc = installLocationPolicy(pkgLite);
15074                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15075                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15076                    } else if (!onSd && !onInt) {
15077                        // Override install location with flags
15078                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15079                            // Set the flag to install on external media.
15080                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15081                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15082                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15083                            if (DEBUG_INSTANT) {
15084                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15085                            }
15086                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15087                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15088                                    |PackageManager.INSTALL_INTERNAL);
15089                        } else {
15090                            // Make sure the flag for installing on external
15091                            // media is unset
15092                            installFlags |= PackageManager.INSTALL_INTERNAL;
15093                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15094                        }
15095                    }
15096                }
15097            }
15098
15099            final InstallArgs args = createInstallArgs(this);
15100            mArgs = args;
15101
15102            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15103                // TODO: http://b/22976637
15104                // Apps installed for "all" users use the device owner to verify the app
15105                UserHandle verifierUser = getUser();
15106                if (verifierUser == UserHandle.ALL) {
15107                    verifierUser = UserHandle.SYSTEM;
15108                }
15109
15110                /*
15111                 * Determine if we have any installed package verifiers. If we
15112                 * do, then we'll defer to them to verify the packages.
15113                 */
15114                final int requiredUid = mRequiredVerifierPackage == null ? -1
15115                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15116                                verifierUser.getIdentifier());
15117                final int installerUid =
15118                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15119                if (!origin.existing && requiredUid != -1
15120                        && isVerificationEnabled(
15121                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15122                    final Intent verification = new Intent(
15123                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15124                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15125                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15126                            PACKAGE_MIME_TYPE);
15127                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15128
15129                    // Query all live verifiers based on current user state
15130                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15131                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15132                            false /*allowDynamicSplits*/);
15133
15134                    if (DEBUG_VERIFY) {
15135                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15136                                + verification.toString() + " with " + pkgLite.verifiers.length
15137                                + " optional verifiers");
15138                    }
15139
15140                    final int verificationId = mPendingVerificationToken++;
15141
15142                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15143
15144                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15145                            installerPackageName);
15146
15147                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15148                            installFlags);
15149
15150                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15151                            pkgLite.packageName);
15152
15153                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15154                            pkgLite.versionCode);
15155
15156                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15157                            pkgLite.getLongVersionCode());
15158
15159                    if (verificationInfo != null) {
15160                        if (verificationInfo.originatingUri != null) {
15161                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15162                                    verificationInfo.originatingUri);
15163                        }
15164                        if (verificationInfo.referrer != null) {
15165                            verification.putExtra(Intent.EXTRA_REFERRER,
15166                                    verificationInfo.referrer);
15167                        }
15168                        if (verificationInfo.originatingUid >= 0) {
15169                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15170                                    verificationInfo.originatingUid);
15171                        }
15172                        if (verificationInfo.installerUid >= 0) {
15173                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15174                                    verificationInfo.installerUid);
15175                        }
15176                    }
15177
15178                    final PackageVerificationState verificationState = new PackageVerificationState(
15179                            requiredUid, args);
15180
15181                    mPendingVerification.append(verificationId, verificationState);
15182
15183                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15184                            receivers, verificationState);
15185
15186                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15187                    final long idleDuration = getVerificationTimeout();
15188
15189                    /*
15190                     * If any sufficient verifiers were listed in the package
15191                     * manifest, attempt to ask them.
15192                     */
15193                    if (sufficientVerifiers != null) {
15194                        final int N = sufficientVerifiers.size();
15195                        if (N == 0) {
15196                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15197                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15198                        } else {
15199                            for (int i = 0; i < N; i++) {
15200                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15201                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15202                                        verifierComponent.getPackageName(), idleDuration,
15203                                        verifierUser.getIdentifier(), false, "package verifier");
15204
15205                                final Intent sufficientIntent = new Intent(verification);
15206                                sufficientIntent.setComponent(verifierComponent);
15207                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15208                            }
15209                        }
15210                    }
15211
15212                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15213                            mRequiredVerifierPackage, receivers);
15214                    if (ret == PackageManager.INSTALL_SUCCEEDED
15215                            && mRequiredVerifierPackage != null) {
15216                        Trace.asyncTraceBegin(
15217                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15218                        /*
15219                         * Send the intent to the required verification agent,
15220                         * but only start the verification timeout after the
15221                         * target BroadcastReceivers have run.
15222                         */
15223                        verification.setComponent(requiredVerifierComponent);
15224                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15225                                mRequiredVerifierPackage, idleDuration,
15226                                verifierUser.getIdentifier(), false, "package verifier");
15227                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15228                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15229                                new BroadcastReceiver() {
15230                                    @Override
15231                                    public void onReceive(Context context, Intent intent) {
15232                                        final Message msg = mHandler
15233                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15234                                        msg.arg1 = verificationId;
15235                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15236                                    }
15237                                }, null, 0, null, null);
15238
15239                        /*
15240                         * We don't want the copy to proceed until verification
15241                         * succeeds, so null out this field.
15242                         */
15243                        mArgs = null;
15244                    }
15245                } else {
15246                    /*
15247                     * No package verification is enabled, so immediately start
15248                     * the remote call to initiate copy using temporary file.
15249                     */
15250                    ret = args.copyApk(mContainerService, true);
15251                }
15252            }
15253
15254            mRet = ret;
15255        }
15256
15257        @Override
15258        void handleReturnCode() {
15259            // If mArgs is null, then MCS couldn't be reached. When it
15260            // reconnects, it will try again to install. At that point, this
15261            // will succeed.
15262            if (mArgs != null) {
15263                processPendingInstall(mArgs, mRet);
15264            }
15265        }
15266
15267        @Override
15268        void handleServiceError() {
15269            mArgs = createInstallArgs(this);
15270            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15271        }
15272    }
15273
15274    private InstallArgs createInstallArgs(InstallParams params) {
15275        if (params.move != null) {
15276            return new MoveInstallArgs(params);
15277        } else {
15278            return new FileInstallArgs(params);
15279        }
15280    }
15281
15282    /**
15283     * Create args that describe an existing installed package. Typically used
15284     * when cleaning up old installs, or used as a move source.
15285     */
15286    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15287            String resourcePath, String[] instructionSets) {
15288        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15289    }
15290
15291    static abstract class InstallArgs {
15292        /** @see InstallParams#origin */
15293        final OriginInfo origin;
15294        /** @see InstallParams#move */
15295        final MoveInfo move;
15296
15297        final IPackageInstallObserver2 observer;
15298        // Always refers to PackageManager flags only
15299        final int installFlags;
15300        final String installerPackageName;
15301        final String volumeUuid;
15302        final UserHandle user;
15303        final String abiOverride;
15304        final String[] installGrantPermissions;
15305        /** If non-null, drop an async trace when the install completes */
15306        final String traceMethod;
15307        final int traceCookie;
15308        final PackageParser.SigningDetails signingDetails;
15309        final int installReason;
15310
15311        // The list of instruction sets supported by this app. This is currently
15312        // only used during the rmdex() phase to clean up resources. We can get rid of this
15313        // if we move dex files under the common app path.
15314        /* nullable */ String[] instructionSets;
15315
15316        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15317                int installFlags, String installerPackageName, String volumeUuid,
15318                UserHandle user, String[] instructionSets,
15319                String abiOverride, String[] installGrantPermissions,
15320                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15321                int installReason) {
15322            this.origin = origin;
15323            this.move = move;
15324            this.installFlags = installFlags;
15325            this.observer = observer;
15326            this.installerPackageName = installerPackageName;
15327            this.volumeUuid = volumeUuid;
15328            this.user = user;
15329            this.instructionSets = instructionSets;
15330            this.abiOverride = abiOverride;
15331            this.installGrantPermissions = installGrantPermissions;
15332            this.traceMethod = traceMethod;
15333            this.traceCookie = traceCookie;
15334            this.signingDetails = signingDetails;
15335            this.installReason = installReason;
15336        }
15337
15338        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15339        abstract int doPreInstall(int status);
15340
15341        /**
15342         * Rename package into final resting place. All paths on the given
15343         * scanned package should be updated to reflect the rename.
15344         */
15345        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15346        abstract int doPostInstall(int status, int uid);
15347
15348        /** @see PackageSettingBase#codePathString */
15349        abstract String getCodePath();
15350        /** @see PackageSettingBase#resourcePathString */
15351        abstract String getResourcePath();
15352
15353        // Need installer lock especially for dex file removal.
15354        abstract void cleanUpResourcesLI();
15355        abstract boolean doPostDeleteLI(boolean delete);
15356
15357        /**
15358         * Called before the source arguments are copied. This is used mostly
15359         * for MoveParams when it needs to read the source file to put it in the
15360         * destination.
15361         */
15362        int doPreCopy() {
15363            return PackageManager.INSTALL_SUCCEEDED;
15364        }
15365
15366        /**
15367         * Called after the source arguments are copied. This is used mostly for
15368         * MoveParams when it needs to read the source file to put it in the
15369         * destination.
15370         */
15371        int doPostCopy(int uid) {
15372            return PackageManager.INSTALL_SUCCEEDED;
15373        }
15374
15375        protected boolean isFwdLocked() {
15376            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15377        }
15378
15379        protected boolean isExternalAsec() {
15380            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15381        }
15382
15383        protected boolean isEphemeral() {
15384            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15385        }
15386
15387        UserHandle getUser() {
15388            return user;
15389        }
15390    }
15391
15392    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15393        if (!allCodePaths.isEmpty()) {
15394            if (instructionSets == null) {
15395                throw new IllegalStateException("instructionSet == null");
15396            }
15397            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15398            for (String codePath : allCodePaths) {
15399                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15400                    try {
15401                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15402                    } catch (InstallerException ignored) {
15403                    }
15404                }
15405            }
15406        }
15407    }
15408
15409    /**
15410     * Logic to handle installation of non-ASEC applications, including copying
15411     * and renaming logic.
15412     */
15413    class FileInstallArgs extends InstallArgs {
15414        private File codeFile;
15415        private File resourceFile;
15416
15417        // Example topology:
15418        // /data/app/com.example/base.apk
15419        // /data/app/com.example/split_foo.apk
15420        // /data/app/com.example/lib/arm/libfoo.so
15421        // /data/app/com.example/lib/arm64/libfoo.so
15422        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15423
15424        /** New install */
15425        FileInstallArgs(InstallParams params) {
15426            super(params.origin, params.move, params.observer, params.installFlags,
15427                    params.installerPackageName, params.volumeUuid,
15428                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15429                    params.grantedRuntimePermissions,
15430                    params.traceMethod, params.traceCookie, params.signingDetails,
15431                    params.installReason);
15432            if (isFwdLocked()) {
15433                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15434            }
15435        }
15436
15437        /** Existing install */
15438        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15439            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15440                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15441                    PackageManager.INSTALL_REASON_UNKNOWN);
15442            this.codeFile = (codePath != null) ? new File(codePath) : null;
15443            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15444        }
15445
15446        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15447            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15448            try {
15449                return doCopyApk(imcs, temp);
15450            } finally {
15451                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15452            }
15453        }
15454
15455        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15456            if (origin.staged) {
15457                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15458                codeFile = origin.file;
15459                resourceFile = origin.file;
15460                return PackageManager.INSTALL_SUCCEEDED;
15461            }
15462
15463            try {
15464                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15465                final File tempDir =
15466                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15467                codeFile = tempDir;
15468                resourceFile = tempDir;
15469            } catch (IOException e) {
15470                Slog.w(TAG, "Failed to create copy file: " + e);
15471                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15472            }
15473
15474            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15475                @Override
15476                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15477                    if (!FileUtils.isValidExtFilename(name)) {
15478                        throw new IllegalArgumentException("Invalid filename: " + name);
15479                    }
15480                    try {
15481                        final File file = new File(codeFile, name);
15482                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15483                                O_RDWR | O_CREAT, 0644);
15484                        Os.chmod(file.getAbsolutePath(), 0644);
15485                        return new ParcelFileDescriptor(fd);
15486                    } catch (ErrnoException e) {
15487                        throw new RemoteException("Failed to open: " + e.getMessage());
15488                    }
15489                }
15490            };
15491
15492            int ret = PackageManager.INSTALL_SUCCEEDED;
15493            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15494            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15495                Slog.e(TAG, "Failed to copy package");
15496                return ret;
15497            }
15498
15499            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15500            NativeLibraryHelper.Handle handle = null;
15501            try {
15502                handle = NativeLibraryHelper.Handle.create(codeFile);
15503                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15504                        abiOverride);
15505            } catch (IOException e) {
15506                Slog.e(TAG, "Copying native libraries failed", e);
15507                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15508            } finally {
15509                IoUtils.closeQuietly(handle);
15510            }
15511
15512            return ret;
15513        }
15514
15515        int doPreInstall(int status) {
15516            if (status != PackageManager.INSTALL_SUCCEEDED) {
15517                cleanUp();
15518            }
15519            return status;
15520        }
15521
15522        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15523            if (status != PackageManager.INSTALL_SUCCEEDED) {
15524                cleanUp();
15525                return false;
15526            }
15527
15528            final File targetDir = codeFile.getParentFile();
15529            final File beforeCodeFile = codeFile;
15530            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15531
15532            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15533            try {
15534                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15535            } catch (ErrnoException e) {
15536                Slog.w(TAG, "Failed to rename", e);
15537                return false;
15538            }
15539
15540            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15541                Slog.w(TAG, "Failed to restorecon");
15542                return false;
15543            }
15544
15545            // Reflect the rename internally
15546            codeFile = afterCodeFile;
15547            resourceFile = afterCodeFile;
15548
15549            // Reflect the rename in scanned details
15550            try {
15551                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15552            } catch (IOException e) {
15553                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15554                return false;
15555            }
15556            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15557                    afterCodeFile, pkg.baseCodePath));
15558            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15559                    afterCodeFile, pkg.splitCodePaths));
15560
15561            // Reflect the rename in app info
15562            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15563            pkg.setApplicationInfoCodePath(pkg.codePath);
15564            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15565            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15566            pkg.setApplicationInfoResourcePath(pkg.codePath);
15567            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15568            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15569
15570            return true;
15571        }
15572
15573        int doPostInstall(int status, int uid) {
15574            if (status != PackageManager.INSTALL_SUCCEEDED) {
15575                cleanUp();
15576            }
15577            return status;
15578        }
15579
15580        @Override
15581        String getCodePath() {
15582            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15583        }
15584
15585        @Override
15586        String getResourcePath() {
15587            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15588        }
15589
15590        private boolean cleanUp() {
15591            if (codeFile == null || !codeFile.exists()) {
15592                return false;
15593            }
15594
15595            removeCodePathLI(codeFile);
15596
15597            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15598                resourceFile.delete();
15599            }
15600
15601            return true;
15602        }
15603
15604        void cleanUpResourcesLI() {
15605            // Try enumerating all code paths before deleting
15606            List<String> allCodePaths = Collections.EMPTY_LIST;
15607            if (codeFile != null && codeFile.exists()) {
15608                try {
15609                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15610                    allCodePaths = pkg.getAllCodePaths();
15611                } catch (PackageParserException e) {
15612                    // Ignored; we tried our best
15613                }
15614            }
15615
15616            cleanUp();
15617            removeDexFiles(allCodePaths, instructionSets);
15618        }
15619
15620        boolean doPostDeleteLI(boolean delete) {
15621            // XXX err, shouldn't we respect the delete flag?
15622            cleanUpResourcesLI();
15623            return true;
15624        }
15625    }
15626
15627    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15628            PackageManagerException {
15629        if (copyRet < 0) {
15630            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15631                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15632                throw new PackageManagerException(copyRet, message);
15633            }
15634        }
15635    }
15636
15637    /**
15638     * Extract the StorageManagerService "container ID" from the full code path of an
15639     * .apk.
15640     */
15641    static String cidFromCodePath(String fullCodePath) {
15642        int eidx = fullCodePath.lastIndexOf("/");
15643        String subStr1 = fullCodePath.substring(0, eidx);
15644        int sidx = subStr1.lastIndexOf("/");
15645        return subStr1.substring(sidx+1, eidx);
15646    }
15647
15648    /**
15649     * Logic to handle movement of existing installed applications.
15650     */
15651    class MoveInstallArgs extends InstallArgs {
15652        private File codeFile;
15653        private File resourceFile;
15654
15655        /** New install */
15656        MoveInstallArgs(InstallParams params) {
15657            super(params.origin, params.move, params.observer, params.installFlags,
15658                    params.installerPackageName, params.volumeUuid,
15659                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15660                    params.grantedRuntimePermissions,
15661                    params.traceMethod, params.traceCookie, params.signingDetails,
15662                    params.installReason);
15663        }
15664
15665        int copyApk(IMediaContainerService imcs, boolean temp) {
15666            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15667                    + move.fromUuid + " to " + move.toUuid);
15668            synchronized (mInstaller) {
15669                try {
15670                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15671                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15672                } catch (InstallerException e) {
15673                    Slog.w(TAG, "Failed to move app", e);
15674                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15675                }
15676            }
15677
15678            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15679            resourceFile = codeFile;
15680            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15681
15682            return PackageManager.INSTALL_SUCCEEDED;
15683        }
15684
15685        int doPreInstall(int status) {
15686            if (status != PackageManager.INSTALL_SUCCEEDED) {
15687                cleanUp(move.toUuid);
15688            }
15689            return status;
15690        }
15691
15692        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15693            if (status != PackageManager.INSTALL_SUCCEEDED) {
15694                cleanUp(move.toUuid);
15695                return false;
15696            }
15697
15698            // Reflect the move in app info
15699            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15700            pkg.setApplicationInfoCodePath(pkg.codePath);
15701            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15702            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15703            pkg.setApplicationInfoResourcePath(pkg.codePath);
15704            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15705            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15706
15707            return true;
15708        }
15709
15710        int doPostInstall(int status, int uid) {
15711            if (status == PackageManager.INSTALL_SUCCEEDED) {
15712                cleanUp(move.fromUuid);
15713            } else {
15714                cleanUp(move.toUuid);
15715            }
15716            return status;
15717        }
15718
15719        @Override
15720        String getCodePath() {
15721            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15722        }
15723
15724        @Override
15725        String getResourcePath() {
15726            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15727        }
15728
15729        private boolean cleanUp(String volumeUuid) {
15730            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15731                    move.dataAppName);
15732            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15733            final int[] userIds = sUserManager.getUserIds();
15734            synchronized (mInstallLock) {
15735                // Clean up both app data and code
15736                // All package moves are frozen until finished
15737                for (int userId : userIds) {
15738                    try {
15739                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15740                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15741                    } catch (InstallerException e) {
15742                        Slog.w(TAG, String.valueOf(e));
15743                    }
15744                }
15745                removeCodePathLI(codeFile);
15746            }
15747            return true;
15748        }
15749
15750        void cleanUpResourcesLI() {
15751            throw new UnsupportedOperationException();
15752        }
15753
15754        boolean doPostDeleteLI(boolean delete) {
15755            throw new UnsupportedOperationException();
15756        }
15757    }
15758
15759    static String getAsecPackageName(String packageCid) {
15760        int idx = packageCid.lastIndexOf("-");
15761        if (idx == -1) {
15762            return packageCid;
15763        }
15764        return packageCid.substring(0, idx);
15765    }
15766
15767    // Utility method used to create code paths based on package name and available index.
15768    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15769        String idxStr = "";
15770        int idx = 1;
15771        // Fall back to default value of idx=1 if prefix is not
15772        // part of oldCodePath
15773        if (oldCodePath != null) {
15774            String subStr = oldCodePath;
15775            // Drop the suffix right away
15776            if (suffix != null && subStr.endsWith(suffix)) {
15777                subStr = subStr.substring(0, subStr.length() - suffix.length());
15778            }
15779            // If oldCodePath already contains prefix find out the
15780            // ending index to either increment or decrement.
15781            int sidx = subStr.lastIndexOf(prefix);
15782            if (sidx != -1) {
15783                subStr = subStr.substring(sidx + prefix.length());
15784                if (subStr != null) {
15785                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15786                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15787                    }
15788                    try {
15789                        idx = Integer.parseInt(subStr);
15790                        if (idx <= 1) {
15791                            idx++;
15792                        } else {
15793                            idx--;
15794                        }
15795                    } catch(NumberFormatException e) {
15796                    }
15797                }
15798            }
15799        }
15800        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15801        return prefix + idxStr;
15802    }
15803
15804    private File getNextCodePath(File targetDir, String packageName) {
15805        File result;
15806        SecureRandom random = new SecureRandom();
15807        byte[] bytes = new byte[16];
15808        do {
15809            random.nextBytes(bytes);
15810            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15811            result = new File(targetDir, packageName + "-" + suffix);
15812        } while (result.exists());
15813        return result;
15814    }
15815
15816    // Utility method that returns the relative package path with respect
15817    // to the installation directory. Like say for /data/data/com.test-1.apk
15818    // string com.test-1 is returned.
15819    static String deriveCodePathName(String codePath) {
15820        if (codePath == null) {
15821            return null;
15822        }
15823        final File codeFile = new File(codePath);
15824        final String name = codeFile.getName();
15825        if (codeFile.isDirectory()) {
15826            return name;
15827        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15828            final int lastDot = name.lastIndexOf('.');
15829            return name.substring(0, lastDot);
15830        } else {
15831            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15832            return null;
15833        }
15834    }
15835
15836    static class PackageInstalledInfo {
15837        String name;
15838        int uid;
15839        // The set of users that originally had this package installed.
15840        int[] origUsers;
15841        // The set of users that now have this package installed.
15842        int[] newUsers;
15843        PackageParser.Package pkg;
15844        int returnCode;
15845        String returnMsg;
15846        String installerPackageName;
15847        PackageRemovedInfo removedInfo;
15848        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15849
15850        public void setError(int code, String msg) {
15851            setReturnCode(code);
15852            setReturnMessage(msg);
15853            Slog.w(TAG, msg);
15854        }
15855
15856        public void setError(String msg, PackageParserException e) {
15857            setReturnCode(e.error);
15858            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15859            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15860            for (int i = 0; i < childCount; i++) {
15861                addedChildPackages.valueAt(i).setError(msg, e);
15862            }
15863            Slog.w(TAG, msg, e);
15864        }
15865
15866        public void setError(String msg, PackageManagerException e) {
15867            returnCode = e.error;
15868            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15869            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15870            for (int i = 0; i < childCount; i++) {
15871                addedChildPackages.valueAt(i).setError(msg, e);
15872            }
15873            Slog.w(TAG, msg, e);
15874        }
15875
15876        public void setReturnCode(int returnCode) {
15877            this.returnCode = returnCode;
15878            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15879            for (int i = 0; i < childCount; i++) {
15880                addedChildPackages.valueAt(i).returnCode = returnCode;
15881            }
15882        }
15883
15884        private void setReturnMessage(String returnMsg) {
15885            this.returnMsg = returnMsg;
15886            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15887            for (int i = 0; i < childCount; i++) {
15888                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15889            }
15890        }
15891
15892        // In some error cases we want to convey more info back to the observer
15893        String origPackage;
15894        String origPermission;
15895    }
15896
15897    /*
15898     * Install a non-existing package.
15899     */
15900    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15901            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15902            String volumeUuid, PackageInstalledInfo res, int installReason) {
15903        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15904
15905        // Remember this for later, in case we need to rollback this install
15906        String pkgName = pkg.packageName;
15907
15908        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15909
15910        synchronized(mPackages) {
15911            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15912            if (renamedPackage != null) {
15913                // A package with the same name is already installed, though
15914                // it has been renamed to an older name.  The package we
15915                // are trying to install should be installed as an update to
15916                // the existing one, but that has not been requested, so bail.
15917                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15918                        + " without first uninstalling package running as "
15919                        + renamedPackage);
15920                return;
15921            }
15922            if (mPackages.containsKey(pkgName)) {
15923                // Don't allow installation over an existing package with the same name.
15924                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15925                        + " without first uninstalling.");
15926                return;
15927            }
15928        }
15929
15930        try {
15931            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15932                    System.currentTimeMillis(), user);
15933
15934            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15935
15936            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15937                prepareAppDataAfterInstallLIF(newPackage);
15938
15939            } else {
15940                // Remove package from internal structures, but keep around any
15941                // data that might have already existed
15942                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15943                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15944            }
15945        } catch (PackageManagerException e) {
15946            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15947        }
15948
15949        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15950    }
15951
15952    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15953        try (DigestInputStream digestStream =
15954                new DigestInputStream(new FileInputStream(file), digest)) {
15955            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15956        }
15957    }
15958
15959    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15960            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15961            PackageInstalledInfo res, int installReason) {
15962        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15963
15964        final PackageParser.Package oldPackage;
15965        final PackageSetting ps;
15966        final String pkgName = pkg.packageName;
15967        final int[] allUsers;
15968        final int[] installedUsers;
15969
15970        synchronized(mPackages) {
15971            oldPackage = mPackages.get(pkgName);
15972            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15973
15974            // don't allow upgrade to target a release SDK from a pre-release SDK
15975            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15976                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15977            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15978                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15979            if (oldTargetsPreRelease
15980                    && !newTargetsPreRelease
15981                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15982                Slog.w(TAG, "Can't install package targeting released sdk");
15983                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15984                return;
15985            }
15986
15987            ps = mSettings.mPackages.get(pkgName);
15988
15989            // verify signatures are valid
15990            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15991            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15992                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15993                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15994                            "New package not signed by keys specified by upgrade-keysets: "
15995                                    + pkgName);
15996                    return;
15997                }
15998            } else {
15999
16000                // default to original signature matching
16001                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16002                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16003                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16004                            "New package has a different signature: " + pkgName);
16005                    return;
16006                }
16007            }
16008
16009            // don't allow a system upgrade unless the upgrade hash matches
16010            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16011                byte[] digestBytes = null;
16012                try {
16013                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16014                    updateDigest(digest, new File(pkg.baseCodePath));
16015                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16016                        for (String path : pkg.splitCodePaths) {
16017                            updateDigest(digest, new File(path));
16018                        }
16019                    }
16020                    digestBytes = digest.digest();
16021                } catch (NoSuchAlgorithmException | IOException e) {
16022                    res.setError(INSTALL_FAILED_INVALID_APK,
16023                            "Could not compute hash: " + pkgName);
16024                    return;
16025                }
16026                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16027                    res.setError(INSTALL_FAILED_INVALID_APK,
16028                            "New package fails restrict-update check: " + pkgName);
16029                    return;
16030                }
16031                // retain upgrade restriction
16032                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16033            }
16034
16035            // Check for shared user id changes
16036            String invalidPackageName =
16037                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16038            if (invalidPackageName != null) {
16039                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16040                        "Package " + invalidPackageName + " tried to change user "
16041                                + oldPackage.mSharedUserId);
16042                return;
16043            }
16044
16045            // check if the new package supports all of the abis which the old package supports
16046            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16047            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16048            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16049                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16050                        "Update to package " + pkgName + " doesn't support multi arch");
16051                return;
16052            }
16053
16054            // In case of rollback, remember per-user/profile install state
16055            allUsers = sUserManager.getUserIds();
16056            installedUsers = ps.queryInstalledUsers(allUsers, true);
16057
16058            // don't allow an upgrade from full to ephemeral
16059            if (isInstantApp) {
16060                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16061                    for (int currentUser : allUsers) {
16062                        if (!ps.getInstantApp(currentUser)) {
16063                            // can't downgrade from full to instant
16064                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16065                                    + " for user: " + currentUser);
16066                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16067                            return;
16068                        }
16069                    }
16070                } else if (!ps.getInstantApp(user.getIdentifier())) {
16071                    // can't downgrade from full to instant
16072                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16073                            + " for user: " + user.getIdentifier());
16074                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16075                    return;
16076                }
16077            }
16078        }
16079
16080        // Update what is removed
16081        res.removedInfo = new PackageRemovedInfo(this);
16082        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16083        res.removedInfo.removedPackage = oldPackage.packageName;
16084        res.removedInfo.installerPackageName = ps.installerPackageName;
16085        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16086        res.removedInfo.isUpdate = true;
16087        res.removedInfo.origUsers = installedUsers;
16088        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16089        for (int i = 0; i < installedUsers.length; i++) {
16090            final int userId = installedUsers[i];
16091            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16092        }
16093
16094        final int childCount = (oldPackage.childPackages != null)
16095                ? oldPackage.childPackages.size() : 0;
16096        for (int i = 0; i < childCount; i++) {
16097            boolean childPackageUpdated = false;
16098            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16099            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16100            if (res.addedChildPackages != null) {
16101                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16102                if (childRes != null) {
16103                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16104                    childRes.removedInfo.removedPackage = childPkg.packageName;
16105                    if (childPs != null) {
16106                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16107                    }
16108                    childRes.removedInfo.isUpdate = true;
16109                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16110                    childPackageUpdated = true;
16111                }
16112            }
16113            if (!childPackageUpdated) {
16114                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16115                childRemovedRes.removedPackage = childPkg.packageName;
16116                if (childPs != null) {
16117                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16118                }
16119                childRemovedRes.isUpdate = false;
16120                childRemovedRes.dataRemoved = true;
16121                synchronized (mPackages) {
16122                    if (childPs != null) {
16123                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16124                    }
16125                }
16126                if (res.removedInfo.removedChildPackages == null) {
16127                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16128                }
16129                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16130            }
16131        }
16132
16133        boolean sysPkg = (isSystemApp(oldPackage));
16134        if (sysPkg) {
16135            // Set the system/privileged/oem/vendor/product flags as needed
16136            final boolean privileged =
16137                    (oldPackage.applicationInfo.privateFlags
16138                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16139            final boolean oem =
16140                    (oldPackage.applicationInfo.privateFlags
16141                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16142            final boolean vendor =
16143                    (oldPackage.applicationInfo.privateFlags
16144                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16145            final boolean product =
16146                    (oldPackage.applicationInfo.privateFlags
16147                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16148            final @ParseFlags int systemParseFlags = parseFlags;
16149            final @ScanFlags int systemScanFlags = scanFlags
16150                    | SCAN_AS_SYSTEM
16151                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16152                    | (oem ? SCAN_AS_OEM : 0)
16153                    | (vendor ? SCAN_AS_VENDOR : 0)
16154                    | (product ? SCAN_AS_PRODUCT : 0);
16155
16156            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16157                    user, allUsers, installerPackageName, res, installReason);
16158        } else {
16159            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16160                    user, allUsers, installerPackageName, res, installReason);
16161        }
16162    }
16163
16164    @Override
16165    public List<String> getPreviousCodePaths(String packageName) {
16166        final int callingUid = Binder.getCallingUid();
16167        final List<String> result = new ArrayList<>();
16168        if (getInstantAppPackageName(callingUid) != null) {
16169            return result;
16170        }
16171        final PackageSetting ps = mSettings.mPackages.get(packageName);
16172        if (ps != null
16173                && ps.oldCodePaths != null
16174                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16175            result.addAll(ps.oldCodePaths);
16176        }
16177        return result;
16178    }
16179
16180    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16181            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16182            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16183            String installerPackageName, PackageInstalledInfo res, int installReason) {
16184        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16185                + deletedPackage);
16186
16187        String pkgName = deletedPackage.packageName;
16188        boolean deletedPkg = true;
16189        boolean addedPkg = false;
16190        boolean updatedSettings = false;
16191        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16192        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16193                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16194
16195        final long origUpdateTime = (pkg.mExtras != null)
16196                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16197
16198        // First delete the existing package while retaining the data directory
16199        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16200                res.removedInfo, true, pkg)) {
16201            // If the existing package wasn't successfully deleted
16202            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16203            deletedPkg = false;
16204        } else {
16205            // Successfully deleted the old package; proceed with replace.
16206
16207            // If deleted package lived in a container, give users a chance to
16208            // relinquish resources before killing.
16209            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16210                if (DEBUG_INSTALL) {
16211                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16212                }
16213                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16214                final ArrayList<String> pkgList = new ArrayList<String>(1);
16215                pkgList.add(deletedPackage.applicationInfo.packageName);
16216                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16217            }
16218
16219            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16220                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16221
16222            try {
16223                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16224                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16225                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16226                        installReason);
16227
16228                // Update the in-memory copy of the previous code paths.
16229                PackageSetting ps = mSettings.mPackages.get(pkgName);
16230                if (!killApp) {
16231                    if (ps.oldCodePaths == null) {
16232                        ps.oldCodePaths = new ArraySet<>();
16233                    }
16234                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16235                    if (deletedPackage.splitCodePaths != null) {
16236                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16237                    }
16238                } else {
16239                    ps.oldCodePaths = null;
16240                }
16241                if (ps.childPackageNames != null) {
16242                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16243                        final String childPkgName = ps.childPackageNames.get(i);
16244                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16245                        childPs.oldCodePaths = ps.oldCodePaths;
16246                    }
16247                }
16248                // set instant app status, but, only if it's explicitly specified
16249                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16250                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16251                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16252                prepareAppDataAfterInstallLIF(newPackage);
16253                addedPkg = true;
16254                mDexManager.notifyPackageUpdated(newPackage.packageName,
16255                        newPackage.baseCodePath, newPackage.splitCodePaths);
16256            } catch (PackageManagerException e) {
16257                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16258            }
16259        }
16260
16261        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16262            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16263
16264            // Revert all internal state mutations and added folders for the failed install
16265            if (addedPkg) {
16266                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16267                        res.removedInfo, true, null);
16268            }
16269
16270            // Restore the old package
16271            if (deletedPkg) {
16272                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16273                File restoreFile = new File(deletedPackage.codePath);
16274                // Parse old package
16275                boolean oldExternal = isExternal(deletedPackage);
16276                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16277                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16278                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16279                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16280                try {
16281                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16282                            null);
16283                } catch (PackageManagerException e) {
16284                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16285                            + e.getMessage());
16286                    return;
16287                }
16288
16289                synchronized (mPackages) {
16290                    // Ensure the installer package name up to date
16291                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16292
16293                    // Update permissions for restored package
16294                    mPermissionManager.updatePermissions(
16295                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16296                            mPermissionCallback);
16297
16298                    mSettings.writeLPr();
16299                }
16300
16301                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16302            }
16303        } else {
16304            synchronized (mPackages) {
16305                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16306                if (ps != null) {
16307                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16308                    if (res.removedInfo.removedChildPackages != null) {
16309                        final int childCount = res.removedInfo.removedChildPackages.size();
16310                        // Iterate in reverse as we may modify the collection
16311                        for (int i = childCount - 1; i >= 0; i--) {
16312                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16313                            if (res.addedChildPackages.containsKey(childPackageName)) {
16314                                res.removedInfo.removedChildPackages.removeAt(i);
16315                            } else {
16316                                PackageRemovedInfo childInfo = res.removedInfo
16317                                        .removedChildPackages.valueAt(i);
16318                                childInfo.removedForAllUsers = mPackages.get(
16319                                        childInfo.removedPackage) == null;
16320                            }
16321                        }
16322                    }
16323                }
16324            }
16325        }
16326    }
16327
16328    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16329            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16330            final @ScanFlags int scanFlags, UserHandle user,
16331            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16332            int installReason) {
16333        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16334                + ", old=" + deletedPackage);
16335
16336        final boolean disabledSystem;
16337
16338        // Remove existing system package
16339        removePackageLI(deletedPackage, true);
16340
16341        synchronized (mPackages) {
16342            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16343        }
16344        if (!disabledSystem) {
16345            // We didn't need to disable the .apk as a current system package,
16346            // which means we are replacing another update that is already
16347            // installed.  We need to make sure to delete the older one's .apk.
16348            res.removedInfo.args = createInstallArgsForExisting(0,
16349                    deletedPackage.applicationInfo.getCodePath(),
16350                    deletedPackage.applicationInfo.getResourcePath(),
16351                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16352        } else {
16353            res.removedInfo.args = null;
16354        }
16355
16356        // Successfully disabled the old package. Now proceed with re-installation
16357        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16358                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16359
16360        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16361        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16362                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16363
16364        PackageParser.Package newPackage = null;
16365        try {
16366            // Add the package to the internal data structures
16367            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16368
16369            // Set the update and install times
16370            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16371            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16372                    System.currentTimeMillis());
16373
16374            // Update the package dynamic state if succeeded
16375            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16376                // Now that the install succeeded make sure we remove data
16377                // directories for any child package the update removed.
16378                final int deletedChildCount = (deletedPackage.childPackages != null)
16379                        ? deletedPackage.childPackages.size() : 0;
16380                final int newChildCount = (newPackage.childPackages != null)
16381                        ? newPackage.childPackages.size() : 0;
16382                for (int i = 0; i < deletedChildCount; i++) {
16383                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16384                    boolean childPackageDeleted = true;
16385                    for (int j = 0; j < newChildCount; j++) {
16386                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16387                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16388                            childPackageDeleted = false;
16389                            break;
16390                        }
16391                    }
16392                    if (childPackageDeleted) {
16393                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16394                                deletedChildPkg.packageName);
16395                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16396                            PackageRemovedInfo removedChildRes = res.removedInfo
16397                                    .removedChildPackages.get(deletedChildPkg.packageName);
16398                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16399                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16400                        }
16401                    }
16402                }
16403
16404                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16405                        installReason);
16406                prepareAppDataAfterInstallLIF(newPackage);
16407
16408                mDexManager.notifyPackageUpdated(newPackage.packageName,
16409                            newPackage.baseCodePath, newPackage.splitCodePaths);
16410            }
16411        } catch (PackageManagerException e) {
16412            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16413            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16414        }
16415
16416        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16417            // Re installation failed. Restore old information
16418            // Remove new pkg information
16419            if (newPackage != null) {
16420                removeInstalledPackageLI(newPackage, true);
16421            }
16422            // Add back the old system package
16423            try {
16424                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16425            } catch (PackageManagerException e) {
16426                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16427            }
16428
16429            synchronized (mPackages) {
16430                if (disabledSystem) {
16431                    enableSystemPackageLPw(deletedPackage);
16432                }
16433
16434                // Ensure the installer package name up to date
16435                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16436
16437                // Update permissions for restored package
16438                mPermissionManager.updatePermissions(
16439                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16440                        mPermissionCallback);
16441
16442                mSettings.writeLPr();
16443            }
16444
16445            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16446                    + " after failed upgrade");
16447        }
16448    }
16449
16450    /**
16451     * Checks whether the parent or any of the child packages have a change shared
16452     * user. For a package to be a valid update the shred users of the parent and
16453     * the children should match. We may later support changing child shared users.
16454     * @param oldPkg The updated package.
16455     * @param newPkg The update package.
16456     * @return The shared user that change between the versions.
16457     */
16458    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16459            PackageParser.Package newPkg) {
16460        // Check parent shared user
16461        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16462            return newPkg.packageName;
16463        }
16464        // Check child shared users
16465        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16466        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16467        for (int i = 0; i < newChildCount; i++) {
16468            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16469            // If this child was present, did it have the same shared user?
16470            for (int j = 0; j < oldChildCount; j++) {
16471                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16472                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16473                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16474                    return newChildPkg.packageName;
16475                }
16476            }
16477        }
16478        return null;
16479    }
16480
16481    private void removeNativeBinariesLI(PackageSetting ps) {
16482        // Remove the lib path for the parent package
16483        if (ps != null) {
16484            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16485            // Remove the lib path for the child packages
16486            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16487            for (int i = 0; i < childCount; i++) {
16488                PackageSetting childPs = null;
16489                synchronized (mPackages) {
16490                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16491                }
16492                if (childPs != null) {
16493                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16494                            .legacyNativeLibraryPathString);
16495                }
16496            }
16497        }
16498    }
16499
16500    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16501        // Enable the parent package
16502        mSettings.enableSystemPackageLPw(pkg.packageName);
16503        // Enable the child packages
16504        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16505        for (int i = 0; i < childCount; i++) {
16506            PackageParser.Package childPkg = pkg.childPackages.get(i);
16507            mSettings.enableSystemPackageLPw(childPkg.packageName);
16508        }
16509    }
16510
16511    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16512            PackageParser.Package newPkg) {
16513        // Disable the parent package (parent always replaced)
16514        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16515        // Disable the child packages
16516        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16517        for (int i = 0; i < childCount; i++) {
16518            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16519            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16520            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16521        }
16522        return disabled;
16523    }
16524
16525    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16526            String installerPackageName) {
16527        // Enable the parent package
16528        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16529        // Enable the child packages
16530        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16531        for (int i = 0; i < childCount; i++) {
16532            PackageParser.Package childPkg = pkg.childPackages.get(i);
16533            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16534        }
16535    }
16536
16537    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16538            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16539        // Update the parent package setting
16540        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16541                res, user, installReason);
16542        // Update the child packages setting
16543        final int childCount = (newPackage.childPackages != null)
16544                ? newPackage.childPackages.size() : 0;
16545        for (int i = 0; i < childCount; i++) {
16546            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16547            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16548            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16549                    childRes.origUsers, childRes, user, installReason);
16550        }
16551    }
16552
16553    private void updateSettingsInternalLI(PackageParser.Package pkg,
16554            String installerPackageName, int[] allUsers, int[] installedForUsers,
16555            PackageInstalledInfo res, UserHandle user, int installReason) {
16556        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16557
16558        String pkgName = pkg.packageName;
16559        synchronized (mPackages) {
16560            //write settings. the installStatus will be incomplete at this stage.
16561            //note that the new package setting would have already been
16562            //added to mPackages. It hasn't been persisted yet.
16563            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16564            // TODO: Remove this write? It's also written at the end of this method
16565            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16566            mSettings.writeLPr();
16567            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16568        }
16569
16570        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16571        synchronized (mPackages) {
16572// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16573            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16574                    mPermissionCallback);
16575            // For system-bundled packages, we assume that installing an upgraded version
16576            // of the package implies that the user actually wants to run that new code,
16577            // so we enable the package.
16578            PackageSetting ps = mSettings.mPackages.get(pkgName);
16579            final int userId = user.getIdentifier();
16580            if (ps != null) {
16581                if (isSystemApp(pkg)) {
16582                    if (DEBUG_INSTALL) {
16583                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16584                    }
16585                    // Enable system package for requested users
16586                    if (res.origUsers != null) {
16587                        for (int origUserId : res.origUsers) {
16588                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16589                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16590                                        origUserId, installerPackageName);
16591                            }
16592                        }
16593                    }
16594                    // Also convey the prior install/uninstall state
16595                    if (allUsers != null && installedForUsers != null) {
16596                        for (int currentUserId : allUsers) {
16597                            final boolean installed = ArrayUtils.contains(
16598                                    installedForUsers, currentUserId);
16599                            if (DEBUG_INSTALL) {
16600                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16601                            }
16602                            ps.setInstalled(installed, currentUserId);
16603                        }
16604                        // these install state changes will be persisted in the
16605                        // upcoming call to mSettings.writeLPr().
16606                    }
16607                }
16608                // It's implied that when a user requests installation, they want the app to be
16609                // installed and enabled.
16610                if (userId != UserHandle.USER_ALL) {
16611                    ps.setInstalled(true, userId);
16612                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16613                } else {
16614                    for (int currentUserId : sUserManager.getUserIds()) {
16615                        ps.setInstalled(true, currentUserId);
16616                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16617                                installerPackageName);
16618                    }
16619                }
16620
16621                // When replacing an existing package, preserve the original install reason for all
16622                // users that had the package installed before.
16623                final Set<Integer> previousUserIds = new ArraySet<>();
16624                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16625                    final int installReasonCount = res.removedInfo.installReasons.size();
16626                    for (int i = 0; i < installReasonCount; i++) {
16627                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16628                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16629                        ps.setInstallReason(previousInstallReason, previousUserId);
16630                        previousUserIds.add(previousUserId);
16631                    }
16632                }
16633
16634                // Set install reason for users that are having the package newly installed.
16635                if (userId == UserHandle.USER_ALL) {
16636                    for (int currentUserId : sUserManager.getUserIds()) {
16637                        if (!previousUserIds.contains(currentUserId)) {
16638                            ps.setInstallReason(installReason, currentUserId);
16639                        }
16640                    }
16641                } else if (!previousUserIds.contains(userId)) {
16642                    ps.setInstallReason(installReason, userId);
16643                }
16644                mSettings.writeKernelMappingLPr(ps);
16645            }
16646            res.name = pkgName;
16647            res.uid = pkg.applicationInfo.uid;
16648            res.pkg = pkg;
16649            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16650            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16651            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16652            //to update install status
16653            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16654            mSettings.writeLPr();
16655            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16656        }
16657
16658        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16659    }
16660
16661    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16662        try {
16663            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16664            installPackageLI(args, res);
16665        } finally {
16666            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16667        }
16668    }
16669
16670    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16671        final int installFlags = args.installFlags;
16672        final String installerPackageName = args.installerPackageName;
16673        final String volumeUuid = args.volumeUuid;
16674        final File tmpPackageFile = new File(args.getCodePath());
16675        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16676        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16677                || (args.volumeUuid != null));
16678        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16679        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16680        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16681        final boolean virtualPreload =
16682                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16683        boolean replace = false;
16684        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16685        if (args.move != null) {
16686            // moving a complete application; perform an initial scan on the new install location
16687            scanFlags |= SCAN_INITIAL;
16688        }
16689        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16690            scanFlags |= SCAN_DONT_KILL_APP;
16691        }
16692        if (instantApp) {
16693            scanFlags |= SCAN_AS_INSTANT_APP;
16694        }
16695        if (fullApp) {
16696            scanFlags |= SCAN_AS_FULL_APP;
16697        }
16698        if (virtualPreload) {
16699            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16700        }
16701
16702        // Result object to be returned
16703        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16704        res.installerPackageName = installerPackageName;
16705
16706        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16707
16708        // Sanity check
16709        if (instantApp && (forwardLocked || onExternal)) {
16710            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16711                    + " external=" + onExternal);
16712            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16713            return;
16714        }
16715
16716        // Retrieve PackageSettings and parse package
16717        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16718                | PackageParser.PARSE_ENFORCE_CODE
16719                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16720                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16721                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16722        PackageParser pp = new PackageParser();
16723        pp.setSeparateProcesses(mSeparateProcesses);
16724        pp.setDisplayMetrics(mMetrics);
16725        pp.setCallback(mPackageParserCallback);
16726
16727        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16728        final PackageParser.Package pkg;
16729        try {
16730            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16731            DexMetadataHelper.validatePackageDexMetadata(pkg);
16732        } catch (PackageParserException e) {
16733            res.setError("Failed parse during installPackageLI", e);
16734            return;
16735        } finally {
16736            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16737        }
16738
16739        // Instant apps have several additional install-time checks.
16740        if (instantApp) {
16741            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16742                Slog.w(TAG,
16743                        "Instant app package " + pkg.packageName + " does not target at least O");
16744                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16745                        "Instant app package must target at least O");
16746                return;
16747            }
16748            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16749                Slog.w(TAG, "Instant app package " + pkg.packageName
16750                        + " does not target targetSandboxVersion 2");
16751                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16752                        "Instant app package must use targetSandboxVersion 2");
16753                return;
16754            }
16755            if (pkg.mSharedUserId != null) {
16756                Slog.w(TAG, "Instant app package " + pkg.packageName
16757                        + " may not declare sharedUserId.");
16758                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16759                        "Instant app package may not declare a sharedUserId");
16760                return;
16761            }
16762        }
16763
16764        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16765            // Static shared libraries have synthetic package names
16766            renameStaticSharedLibraryPackage(pkg);
16767
16768            // No static shared libs on external storage
16769            if (onExternal) {
16770                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16771                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16772                        "Packages declaring static-shared libs cannot be updated");
16773                return;
16774            }
16775        }
16776
16777        // If we are installing a clustered package add results for the children
16778        if (pkg.childPackages != null) {
16779            synchronized (mPackages) {
16780                final int childCount = pkg.childPackages.size();
16781                for (int i = 0; i < childCount; i++) {
16782                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16783                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16784                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16785                    childRes.pkg = childPkg;
16786                    childRes.name = childPkg.packageName;
16787                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16788                    if (childPs != null) {
16789                        childRes.origUsers = childPs.queryInstalledUsers(
16790                                sUserManager.getUserIds(), true);
16791                    }
16792                    if ((mPackages.containsKey(childPkg.packageName))) {
16793                        childRes.removedInfo = new PackageRemovedInfo(this);
16794                        childRes.removedInfo.removedPackage = childPkg.packageName;
16795                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16796                    }
16797                    if (res.addedChildPackages == null) {
16798                        res.addedChildPackages = new ArrayMap<>();
16799                    }
16800                    res.addedChildPackages.put(childPkg.packageName, childRes);
16801                }
16802            }
16803        }
16804
16805        // If package doesn't declare API override, mark that we have an install
16806        // time CPU ABI override.
16807        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16808            pkg.cpuAbiOverride = args.abiOverride;
16809        }
16810
16811        String pkgName = res.name = pkg.packageName;
16812        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16813            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16814                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16815                return;
16816            }
16817        }
16818
16819        try {
16820            // either use what we've been given or parse directly from the APK
16821            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16822                pkg.setSigningDetails(args.signingDetails);
16823            } else {
16824                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16825            }
16826        } catch (PackageParserException e) {
16827            res.setError("Failed collect during installPackageLI", e);
16828            return;
16829        }
16830
16831        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16832                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16833            Slog.w(TAG, "Instant app package " + pkg.packageName
16834                    + " is not signed with at least APK Signature Scheme v2");
16835            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16836                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16837            return;
16838        }
16839
16840        // Get rid of all references to package scan path via parser.
16841        pp = null;
16842        String oldCodePath = null;
16843        boolean systemApp = false;
16844        synchronized (mPackages) {
16845            // Check if installing already existing package
16846            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16847                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16848                if (pkg.mOriginalPackages != null
16849                        && pkg.mOriginalPackages.contains(oldName)
16850                        && mPackages.containsKey(oldName)) {
16851                    // This package is derived from an original package,
16852                    // and this device has been updating from that original
16853                    // name.  We must continue using the original name, so
16854                    // rename the new package here.
16855                    pkg.setPackageName(oldName);
16856                    pkgName = pkg.packageName;
16857                    replace = true;
16858                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16859                            + oldName + " pkgName=" + pkgName);
16860                } else if (mPackages.containsKey(pkgName)) {
16861                    // This package, under its official name, already exists
16862                    // on the device; we should replace it.
16863                    replace = true;
16864                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16865                }
16866
16867                // Child packages are installed through the parent package
16868                if (pkg.parentPackage != null) {
16869                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16870                            "Package " + pkg.packageName + " is child of package "
16871                                    + pkg.parentPackage.parentPackage + ". Child packages "
16872                                    + "can be updated only through the parent package.");
16873                    return;
16874                }
16875
16876                if (replace) {
16877                    // Prevent apps opting out from runtime permissions
16878                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16879                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16880                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16881                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16882                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16883                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16884                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16885                                        + " doesn't support runtime permissions but the old"
16886                                        + " target SDK " + oldTargetSdk + " does.");
16887                        return;
16888                    }
16889                    // Prevent persistent apps from being updated
16890                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16891                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16892                                "Package " + oldPackage.packageName + " is a persistent app. "
16893                                        + "Persistent apps are not updateable.");
16894                        return;
16895                    }
16896                    // Prevent apps from downgrading their targetSandbox.
16897                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16898                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16899                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16900                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16901                                "Package " + pkg.packageName + " new target sandbox "
16902                                + newTargetSandbox + " is incompatible with the previous value of"
16903                                + oldTargetSandbox + ".");
16904                        return;
16905                    }
16906
16907                    // Prevent installing of child packages
16908                    if (oldPackage.parentPackage != null) {
16909                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16910                                "Package " + pkg.packageName + " is child of package "
16911                                        + oldPackage.parentPackage + ". Child packages "
16912                                        + "can be updated only through the parent package.");
16913                        return;
16914                    }
16915                }
16916            }
16917
16918            PackageSetting ps = mSettings.mPackages.get(pkgName);
16919            if (ps != null) {
16920                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16921
16922                // Static shared libs have same package with different versions where
16923                // we internally use a synthetic package name to allow multiple versions
16924                // of the same package, therefore we need to compare signatures against
16925                // the package setting for the latest library version.
16926                PackageSetting signatureCheckPs = ps;
16927                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16928                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16929                    if (libraryEntry != null) {
16930                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16931                    }
16932                }
16933
16934                // Quick sanity check that we're signed correctly if updating;
16935                // we'll check this again later when scanning, but we want to
16936                // bail early here before tripping over redefined permissions.
16937                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16938                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16939                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16940                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16941                                + pkg.packageName + " upgrade keys do not match the "
16942                                + "previously installed version");
16943                        return;
16944                    }
16945                } else {
16946                    try {
16947                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16948                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16949                        // We don't care about disabledPkgSetting on install for now.
16950                        final boolean compatMatch = verifySignatures(
16951                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
16952                                compareRecover);
16953                        // The new KeySets will be re-added later in the scanning process.
16954                        if (compatMatch) {
16955                            synchronized (mPackages) {
16956                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16957                            }
16958                        }
16959                    } catch (PackageManagerException e) {
16960                        res.setError(e.error, e.getMessage());
16961                        return;
16962                    }
16963                }
16964
16965                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16966                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16967                    systemApp = (ps.pkg.applicationInfo.flags &
16968                            ApplicationInfo.FLAG_SYSTEM) != 0;
16969                }
16970                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16971            }
16972
16973            int N = pkg.permissions.size();
16974            for (int i = N-1; i >= 0; i--) {
16975                final PackageParser.Permission perm = pkg.permissions.get(i);
16976                final BasePermission bp =
16977                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16978
16979                // Don't allow anyone but the system to define ephemeral permissions.
16980                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16981                        && !systemApp) {
16982                    Slog.w(TAG, "Non-System package " + pkg.packageName
16983                            + " attempting to delcare ephemeral permission "
16984                            + perm.info.name + "; Removing ephemeral.");
16985                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16986                }
16987
16988                // Check whether the newly-scanned package wants to define an already-defined perm
16989                if (bp != null) {
16990                    // If the defining package is signed with our cert, it's okay.  This
16991                    // also includes the "updating the same package" case, of course.
16992                    // "updating same package" could also involve key-rotation.
16993                    final boolean sigsOk;
16994                    final String sourcePackageName = bp.getSourcePackageName();
16995                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16996                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16997                    if (sourcePackageName.equals(pkg.packageName)
16998                            && (ksms.shouldCheckUpgradeKeySetLocked(
16999                                    sourcePackageSetting, scanFlags))) {
17000                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17001                    } else {
17002
17003                        // in the event of signing certificate rotation, we need to see if the
17004                        // package's certificate has rotated from the current one, or if it is an
17005                        // older certificate with which the current is ok with sharing permissions
17006                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17007                                        pkg.mSigningDetails,
17008                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17009                            sigsOk = true;
17010                        } else if (pkg.mSigningDetails.checkCapability(
17011                                        sourcePackageSetting.signatures.mSigningDetails,
17012                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17013
17014                            // the scanned package checks out, has signing certificate rotation
17015                            // history, and is newer; bring it over
17016                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17017                            sigsOk = true;
17018                        } else {
17019                            sigsOk = false;
17020                        }
17021                    }
17022                    if (!sigsOk) {
17023                        // If the owning package is the system itself, we log but allow
17024                        // install to proceed; we fail the install on all other permission
17025                        // redefinitions.
17026                        if (!sourcePackageName.equals("android")) {
17027                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17028                                    + pkg.packageName + " attempting to redeclare permission "
17029                                    + perm.info.name + " already owned by " + sourcePackageName);
17030                            res.origPermission = perm.info.name;
17031                            res.origPackage = sourcePackageName;
17032                            return;
17033                        } else {
17034                            Slog.w(TAG, "Package " + pkg.packageName
17035                                    + " attempting to redeclare system permission "
17036                                    + perm.info.name + "; ignoring new declaration");
17037                            pkg.permissions.remove(i);
17038                        }
17039                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17040                        // Prevent apps to change protection level to dangerous from any other
17041                        // type as this would allow a privilege escalation where an app adds a
17042                        // normal/signature permission in other app's group and later redefines
17043                        // it as dangerous leading to the group auto-grant.
17044                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17045                                == PermissionInfo.PROTECTION_DANGEROUS) {
17046                            if (bp != null && !bp.isRuntime()) {
17047                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17048                                        + "non-runtime permission " + perm.info.name
17049                                        + " to runtime; keeping old protection level");
17050                                perm.info.protectionLevel = bp.getProtectionLevel();
17051                            }
17052                        }
17053                    }
17054                }
17055            }
17056        }
17057
17058        if (systemApp) {
17059            if (onExternal) {
17060                // Abort update; system app can't be replaced with app on sdcard
17061                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17062                        "Cannot install updates to system apps on sdcard");
17063                return;
17064            } else if (instantApp) {
17065                // Abort update; system app can't be replaced with an instant app
17066                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17067                        "Cannot update a system app with an instant app");
17068                return;
17069            }
17070        }
17071
17072        if (args.move != null) {
17073            // We did an in-place move, so dex is ready to roll
17074            scanFlags |= SCAN_NO_DEX;
17075            scanFlags |= SCAN_MOVE;
17076
17077            synchronized (mPackages) {
17078                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17079                if (ps == null) {
17080                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17081                            "Missing settings for moved package " + pkgName);
17082                }
17083
17084                // We moved the entire application as-is, so bring over the
17085                // previously derived ABI information.
17086                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17087                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17088            }
17089
17090        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17091            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17092            scanFlags |= SCAN_NO_DEX;
17093
17094            try {
17095                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17096                    args.abiOverride : pkg.cpuAbiOverride);
17097                final boolean extractNativeLibs = !pkg.isLibrary();
17098                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17099            } catch (PackageManagerException pme) {
17100                Slog.e(TAG, "Error deriving application ABI", pme);
17101                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17102                return;
17103            }
17104
17105            // Shared libraries for the package need to be updated.
17106            synchronized (mPackages) {
17107                try {
17108                    updateSharedLibrariesLPr(pkg, null);
17109                } catch (PackageManagerException e) {
17110                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17111                }
17112            }
17113        }
17114
17115        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17116            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17117            return;
17118        }
17119
17120        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17121            String apkPath = null;
17122            synchronized (mPackages) {
17123                // Note that if the attacker managed to skip verify setup, for example by tampering
17124                // with the package settings, upon reboot we will do full apk verification when
17125                // verity is not detected.
17126                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17127                if (ps != null && ps.isPrivileged()) {
17128                    apkPath = pkg.baseCodePath;
17129                }
17130            }
17131
17132            if (apkPath != null) {
17133                final VerityUtils.SetupResult result =
17134                        VerityUtils.generateApkVeritySetupData(apkPath);
17135                if (result.isOk()) {
17136                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17137                    FileDescriptor fd = result.getUnownedFileDescriptor();
17138                    try {
17139                        mInstaller.installApkVerity(apkPath, fd);
17140                    } catch (InstallerException e) {
17141                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17142                                "Failed to set up verity: " + e);
17143                        return;
17144                    } finally {
17145                        IoUtils.closeQuietly(fd);
17146                    }
17147                } else if (result.isFailed()) {
17148                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17149                    return;
17150                } else {
17151                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17152                    // reboot.
17153                }
17154            }
17155        }
17156
17157        if (!instantApp) {
17158            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17159        } else {
17160            if (DEBUG_DOMAIN_VERIFICATION) {
17161                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17162            }
17163        }
17164
17165        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17166                "installPackageLI")) {
17167            if (replace) {
17168                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17169                    // Static libs have a synthetic package name containing the version
17170                    // and cannot be updated as an update would get a new package name,
17171                    // unless this is the exact same version code which is useful for
17172                    // development.
17173                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17174                    if (existingPkg != null &&
17175                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17176                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17177                                + "static-shared libs cannot be updated");
17178                        return;
17179                    }
17180                }
17181                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17182                        installerPackageName, res, args.installReason);
17183            } else {
17184                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17185                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17186            }
17187        }
17188
17189        // Prepare the application profiles for the new code paths.
17190        // This needs to be done before invoking dexopt so that any install-time profile
17191        // can be used for optimizations.
17192        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17193
17194        // Check whether we need to dexopt the app.
17195        //
17196        // NOTE: it is IMPORTANT to call dexopt:
17197        //   - after doRename which will sync the package data from PackageParser.Package and its
17198        //     corresponding ApplicationInfo.
17199        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17200        //     uid of the application (pkg.applicationInfo.uid).
17201        //     This update happens in place!
17202        //
17203        // We only need to dexopt if the package meets ALL of the following conditions:
17204        //   1) it is not forward locked.
17205        //   2) it is not on on an external ASEC container.
17206        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17207        //
17208        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17209        // complete, so we skip this step during installation. Instead, we'll take extra time
17210        // the first time the instant app starts. It's preferred to do it this way to provide
17211        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17212        // middle of running an instant app. The default behaviour can be overridden
17213        // via gservices.
17214        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17215                && !forwardLocked
17216                && !pkg.applicationInfo.isExternalAsec()
17217                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17218                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17219
17220        if (performDexopt) {
17221            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17222            // Do not run PackageDexOptimizer through the local performDexOpt
17223            // method because `pkg` may not be in `mPackages` yet.
17224            //
17225            // Also, don't fail application installs if the dexopt step fails.
17226            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17227                    REASON_INSTALL,
17228                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17229                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17230            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17231                    null /* instructionSets */,
17232                    getOrCreateCompilerPackageStats(pkg),
17233                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17234                    dexoptOptions);
17235            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17236        }
17237
17238        // Notify BackgroundDexOptService that the package has been changed.
17239        // If this is an update of a package which used to fail to compile,
17240        // BackgroundDexOptService will remove it from its blacklist.
17241        // TODO: Layering violation
17242        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17243
17244        synchronized (mPackages) {
17245            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17246            if (ps != null) {
17247                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17248                ps.setUpdateAvailable(false /*updateAvailable*/);
17249            }
17250
17251            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17252            for (int i = 0; i < childCount; i++) {
17253                PackageParser.Package childPkg = pkg.childPackages.get(i);
17254                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17255                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17256                if (childPs != null) {
17257                    childRes.newUsers = childPs.queryInstalledUsers(
17258                            sUserManager.getUserIds(), true);
17259                }
17260            }
17261
17262            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17263                updateSequenceNumberLP(ps, res.newUsers);
17264                updateInstantAppInstallerLocked(pkgName);
17265            }
17266        }
17267    }
17268
17269    private void startIntentFilterVerifications(int userId, boolean replacing,
17270            PackageParser.Package pkg) {
17271        if (mIntentFilterVerifierComponent == null) {
17272            Slog.w(TAG, "No IntentFilter verification will not be done as "
17273                    + "there is no IntentFilterVerifier available!");
17274            return;
17275        }
17276
17277        final int verifierUid = getPackageUid(
17278                mIntentFilterVerifierComponent.getPackageName(),
17279                MATCH_DEBUG_TRIAGED_MISSING,
17280                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17281
17282        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17283        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17284        mHandler.sendMessage(msg);
17285
17286        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17287        for (int i = 0; i < childCount; i++) {
17288            PackageParser.Package childPkg = pkg.childPackages.get(i);
17289            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17290            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17291            mHandler.sendMessage(msg);
17292        }
17293    }
17294
17295    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17296            PackageParser.Package pkg) {
17297        int size = pkg.activities.size();
17298        if (size == 0) {
17299            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17300                    "No activity, so no need to verify any IntentFilter!");
17301            return;
17302        }
17303
17304        final boolean hasDomainURLs = hasDomainURLs(pkg);
17305        if (!hasDomainURLs) {
17306            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17307                    "No domain URLs, so no need to verify any IntentFilter!");
17308            return;
17309        }
17310
17311        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17312                + " if any IntentFilter from the " + size
17313                + " Activities needs verification ...");
17314
17315        int count = 0;
17316        final String packageName = pkg.packageName;
17317
17318        synchronized (mPackages) {
17319            // If this is a new install and we see that we've already run verification for this
17320            // package, we have nothing to do: it means the state was restored from backup.
17321            if (!replacing) {
17322                IntentFilterVerificationInfo ivi =
17323                        mSettings.getIntentFilterVerificationLPr(packageName);
17324                if (ivi != null) {
17325                    if (DEBUG_DOMAIN_VERIFICATION) {
17326                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17327                                + ivi.getStatusString());
17328                    }
17329                    return;
17330                }
17331            }
17332
17333            // If any filters need to be verified, then all need to be.
17334            boolean needToVerify = false;
17335            for (PackageParser.Activity a : pkg.activities) {
17336                for (ActivityIntentInfo filter : a.intents) {
17337                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17338                        if (DEBUG_DOMAIN_VERIFICATION) {
17339                            Slog.d(TAG,
17340                                    "Intent filter needs verification, so processing all filters");
17341                        }
17342                        needToVerify = true;
17343                        break;
17344                    }
17345                }
17346            }
17347
17348            if (needToVerify) {
17349                final int verificationId = mIntentFilterVerificationToken++;
17350                for (PackageParser.Activity a : pkg.activities) {
17351                    for (ActivityIntentInfo filter : a.intents) {
17352                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17353                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17354                                    "Verification needed for IntentFilter:" + filter.toString());
17355                            mIntentFilterVerifier.addOneIntentFilterVerification(
17356                                    verifierUid, userId, verificationId, filter, packageName);
17357                            count++;
17358                        }
17359                    }
17360                }
17361            }
17362        }
17363
17364        if (count > 0) {
17365            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17366                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17367                    +  " for userId:" + userId);
17368            mIntentFilterVerifier.startVerifications(userId);
17369        } else {
17370            if (DEBUG_DOMAIN_VERIFICATION) {
17371                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17372            }
17373        }
17374    }
17375
17376    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17377        final ComponentName cn  = filter.activity.getComponentName();
17378        final String packageName = cn.getPackageName();
17379
17380        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17381                packageName);
17382        if (ivi == null) {
17383            return true;
17384        }
17385        int status = ivi.getStatus();
17386        switch (status) {
17387            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17388            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17389                return true;
17390
17391            default:
17392                // Nothing to do
17393                return false;
17394        }
17395    }
17396
17397    private static boolean isMultiArch(ApplicationInfo info) {
17398        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17399    }
17400
17401    private static boolean isExternal(PackageParser.Package pkg) {
17402        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17403    }
17404
17405    private static boolean isExternal(PackageSetting ps) {
17406        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17407    }
17408
17409    private static boolean isSystemApp(PackageParser.Package pkg) {
17410        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17411    }
17412
17413    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17414        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17415    }
17416
17417    private static boolean isOemApp(PackageParser.Package pkg) {
17418        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17419    }
17420
17421    private static boolean isVendorApp(PackageParser.Package pkg) {
17422        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17423    }
17424
17425    private static boolean isProductApp(PackageParser.Package pkg) {
17426        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17427    }
17428
17429    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17430        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17431    }
17432
17433    private static boolean isSystemApp(PackageSetting ps) {
17434        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17435    }
17436
17437    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17438        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17439    }
17440
17441    private int packageFlagsToInstallFlags(PackageSetting ps) {
17442        int installFlags = 0;
17443        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17444            // This existing package was an external ASEC install when we have
17445            // the external flag without a UUID
17446            installFlags |= PackageManager.INSTALL_EXTERNAL;
17447        }
17448        if (ps.isForwardLocked()) {
17449            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17450        }
17451        return installFlags;
17452    }
17453
17454    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17455        if (isExternal(pkg)) {
17456            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17457                return mSettings.getExternalVersion();
17458            } else {
17459                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17460            }
17461        } else {
17462            return mSettings.getInternalVersion();
17463        }
17464    }
17465
17466    private void deleteTempPackageFiles() {
17467        final FilenameFilter filter = new FilenameFilter() {
17468            public boolean accept(File dir, String name) {
17469                return name.startsWith("vmdl") && name.endsWith(".tmp");
17470            }
17471        };
17472        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17473            file.delete();
17474        }
17475    }
17476
17477    @Override
17478    public void deletePackageAsUser(String packageName, int versionCode,
17479            IPackageDeleteObserver observer, int userId, int flags) {
17480        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17481                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17482    }
17483
17484    @Override
17485    public void deletePackageVersioned(VersionedPackage versionedPackage,
17486            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17487        final int callingUid = Binder.getCallingUid();
17488        mContext.enforceCallingOrSelfPermission(
17489                android.Manifest.permission.DELETE_PACKAGES, null);
17490        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17491        Preconditions.checkNotNull(versionedPackage);
17492        Preconditions.checkNotNull(observer);
17493        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17494                PackageManager.VERSION_CODE_HIGHEST,
17495                Long.MAX_VALUE, "versionCode must be >= -1");
17496
17497        final String packageName = versionedPackage.getPackageName();
17498        final long versionCode = versionedPackage.getLongVersionCode();
17499        final String internalPackageName;
17500        synchronized (mPackages) {
17501            // Normalize package name to handle renamed packages and static libs
17502            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17503        }
17504
17505        final int uid = Binder.getCallingUid();
17506        if (!isOrphaned(internalPackageName)
17507                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17508            try {
17509                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17510                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17511                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17512                observer.onUserActionRequired(intent);
17513            } catch (RemoteException re) {
17514            }
17515            return;
17516        }
17517        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17518        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17519        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17520            mContext.enforceCallingOrSelfPermission(
17521                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17522                    "deletePackage for user " + userId);
17523        }
17524
17525        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17526            try {
17527                observer.onPackageDeleted(packageName,
17528                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17529            } catch (RemoteException re) {
17530            }
17531            return;
17532        }
17533
17534        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17535            try {
17536                observer.onPackageDeleted(packageName,
17537                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17538            } catch (RemoteException re) {
17539            }
17540            return;
17541        }
17542
17543        if (DEBUG_REMOVE) {
17544            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17545                    + " deleteAllUsers: " + deleteAllUsers + " version="
17546                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17547                    ? "VERSION_CODE_HIGHEST" : versionCode));
17548        }
17549        // Queue up an async operation since the package deletion may take a little while.
17550        mHandler.post(new Runnable() {
17551            public void run() {
17552                mHandler.removeCallbacks(this);
17553                int returnCode;
17554                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17555                boolean doDeletePackage = true;
17556                if (ps != null) {
17557                    final boolean targetIsInstantApp =
17558                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17559                    doDeletePackage = !targetIsInstantApp
17560                            || canViewInstantApps;
17561                }
17562                if (doDeletePackage) {
17563                    if (!deleteAllUsers) {
17564                        returnCode = deletePackageX(internalPackageName, versionCode,
17565                                userId, deleteFlags);
17566                    } else {
17567                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17568                                internalPackageName, users);
17569                        // If nobody is blocking uninstall, proceed with delete for all users
17570                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17571                            returnCode = deletePackageX(internalPackageName, versionCode,
17572                                    userId, deleteFlags);
17573                        } else {
17574                            // Otherwise uninstall individually for users with blockUninstalls=false
17575                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17576                            for (int userId : users) {
17577                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17578                                    returnCode = deletePackageX(internalPackageName, versionCode,
17579                                            userId, userFlags);
17580                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17581                                        Slog.w(TAG, "Package delete failed for user " + userId
17582                                                + ", returnCode " + returnCode);
17583                                    }
17584                                }
17585                            }
17586                            // The app has only been marked uninstalled for certain users.
17587                            // We still need to report that delete was blocked
17588                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17589                        }
17590                    }
17591                } else {
17592                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17593                }
17594                try {
17595                    observer.onPackageDeleted(packageName, returnCode, null);
17596                } catch (RemoteException e) {
17597                    Log.i(TAG, "Observer no longer exists.");
17598                } //end catch
17599            } //end run
17600        });
17601    }
17602
17603    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17604        if (pkg.staticSharedLibName != null) {
17605            return pkg.manifestPackageName;
17606        }
17607        return pkg.packageName;
17608    }
17609
17610    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17611        // Handle renamed packages
17612        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17613        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17614
17615        // Is this a static library?
17616        LongSparseArray<SharedLibraryEntry> versionedLib =
17617                mStaticLibsByDeclaringPackage.get(packageName);
17618        if (versionedLib == null || versionedLib.size() <= 0) {
17619            return packageName;
17620        }
17621
17622        // Figure out which lib versions the caller can see
17623        LongSparseLongArray versionsCallerCanSee = null;
17624        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17625        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17626                && callingAppId != Process.ROOT_UID) {
17627            versionsCallerCanSee = new LongSparseLongArray();
17628            String libName = versionedLib.valueAt(0).info.getName();
17629            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17630            if (uidPackages != null) {
17631                for (String uidPackage : uidPackages) {
17632                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17633                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17634                    if (libIdx >= 0) {
17635                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17636                        versionsCallerCanSee.append(libVersion, libVersion);
17637                    }
17638                }
17639            }
17640        }
17641
17642        // Caller can see nothing - done
17643        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17644            return packageName;
17645        }
17646
17647        // Find the version the caller can see and the app version code
17648        SharedLibraryEntry highestVersion = null;
17649        final int versionCount = versionedLib.size();
17650        for (int i = 0; i < versionCount; i++) {
17651            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17652            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17653                    libEntry.info.getLongVersion()) < 0) {
17654                continue;
17655            }
17656            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17657            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17658                if (libVersionCode == versionCode) {
17659                    return libEntry.apk;
17660                }
17661            } else if (highestVersion == null) {
17662                highestVersion = libEntry;
17663            } else if (libVersionCode  > highestVersion.info
17664                    .getDeclaringPackage().getLongVersionCode()) {
17665                highestVersion = libEntry;
17666            }
17667        }
17668
17669        if (highestVersion != null) {
17670            return highestVersion.apk;
17671        }
17672
17673        return packageName;
17674    }
17675
17676    boolean isCallerVerifier(int callingUid) {
17677        final int callingUserId = UserHandle.getUserId(callingUid);
17678        return mRequiredVerifierPackage != null &&
17679                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17680    }
17681
17682    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17683        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17684              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17685            return true;
17686        }
17687        final int callingUserId = UserHandle.getUserId(callingUid);
17688        // If the caller installed the pkgName, then allow it to silently uninstall.
17689        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17690            return true;
17691        }
17692
17693        // Allow package verifier to silently uninstall.
17694        if (mRequiredVerifierPackage != null &&
17695                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17696            return true;
17697        }
17698
17699        // Allow package uninstaller to silently uninstall.
17700        if (mRequiredUninstallerPackage != null &&
17701                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17702            return true;
17703        }
17704
17705        // Allow storage manager to silently uninstall.
17706        if (mStorageManagerPackage != null &&
17707                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17708            return true;
17709        }
17710
17711        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17712        // uninstall for device owner provisioning.
17713        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17714                == PERMISSION_GRANTED) {
17715            return true;
17716        }
17717
17718        return false;
17719    }
17720
17721    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17722        int[] result = EMPTY_INT_ARRAY;
17723        for (int userId : userIds) {
17724            if (getBlockUninstallForUser(packageName, userId)) {
17725                result = ArrayUtils.appendInt(result, userId);
17726            }
17727        }
17728        return result;
17729    }
17730
17731    @Override
17732    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17733        final int callingUid = Binder.getCallingUid();
17734        if (getInstantAppPackageName(callingUid) != null
17735                && !isCallerSameApp(packageName, callingUid)) {
17736            return false;
17737        }
17738        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17739    }
17740
17741    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17742        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17743                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17744        try {
17745            if (dpm != null) {
17746                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17747                        /* callingUserOnly =*/ false);
17748                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17749                        : deviceOwnerComponentName.getPackageName();
17750                // Does the package contains the device owner?
17751                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17752                // this check is probably not needed, since DO should be registered as a device
17753                // admin on some user too. (Original bug for this: b/17657954)
17754                if (packageName.equals(deviceOwnerPackageName)) {
17755                    return true;
17756                }
17757                // Does it contain a device admin for any user?
17758                int[] users;
17759                if (userId == UserHandle.USER_ALL) {
17760                    users = sUserManager.getUserIds();
17761                } else {
17762                    users = new int[]{userId};
17763                }
17764                for (int i = 0; i < users.length; ++i) {
17765                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17766                        return true;
17767                    }
17768                }
17769            }
17770        } catch (RemoteException e) {
17771        }
17772        return false;
17773    }
17774
17775    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17776        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17777    }
17778
17779    /**
17780     *  This method is an internal method that could be get invoked either
17781     *  to delete an installed package or to clean up a failed installation.
17782     *  After deleting an installed package, a broadcast is sent to notify any
17783     *  listeners that the package has been removed. For cleaning up a failed
17784     *  installation, the broadcast is not necessary since the package's
17785     *  installation wouldn't have sent the initial broadcast either
17786     *  The key steps in deleting a package are
17787     *  deleting the package information in internal structures like mPackages,
17788     *  deleting the packages base directories through installd
17789     *  updating mSettings to reflect current status
17790     *  persisting settings for later use
17791     *  sending a broadcast if necessary
17792     */
17793    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17794        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17795        final boolean res;
17796
17797        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17798                ? UserHandle.USER_ALL : userId;
17799
17800        if (isPackageDeviceAdmin(packageName, removeUser)) {
17801            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17802            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17803        }
17804
17805        PackageSetting uninstalledPs = null;
17806        PackageParser.Package pkg = null;
17807
17808        // for the uninstall-updates case and restricted profiles, remember the per-
17809        // user handle installed state
17810        int[] allUsers;
17811        synchronized (mPackages) {
17812            uninstalledPs = mSettings.mPackages.get(packageName);
17813            if (uninstalledPs == null) {
17814                Slog.w(TAG, "Not removing non-existent package " + packageName);
17815                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17816            }
17817
17818            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17819                    && uninstalledPs.versionCode != versionCode) {
17820                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17821                        + uninstalledPs.versionCode + " != " + versionCode);
17822                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17823            }
17824
17825            // Static shared libs can be declared by any package, so let us not
17826            // allow removing a package if it provides a lib others depend on.
17827            pkg = mPackages.get(packageName);
17828
17829            allUsers = sUserManager.getUserIds();
17830
17831            if (pkg != null && pkg.staticSharedLibName != null) {
17832                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17833                        pkg.staticSharedLibVersion);
17834                if (libEntry != null) {
17835                    for (int currUserId : allUsers) {
17836                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17837                            continue;
17838                        }
17839                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17840                                libEntry.info, 0, currUserId);
17841                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17842                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17843                                    + " hosting lib " + libEntry.info.getName() + " version "
17844                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17845                                    + " for user " + currUserId);
17846                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17847                        }
17848                    }
17849                }
17850            }
17851
17852            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17853        }
17854
17855        final int freezeUser;
17856        if (isUpdatedSystemApp(uninstalledPs)
17857                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17858            // We're downgrading a system app, which will apply to all users, so
17859            // freeze them all during the downgrade
17860            freezeUser = UserHandle.USER_ALL;
17861        } else {
17862            freezeUser = removeUser;
17863        }
17864
17865        synchronized (mInstallLock) {
17866            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17867            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17868                    deleteFlags, "deletePackageX")) {
17869                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17870                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17871            }
17872            synchronized (mPackages) {
17873                if (res) {
17874                    if (pkg != null) {
17875                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17876                    }
17877                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17878                    updateInstantAppInstallerLocked(packageName);
17879                }
17880            }
17881        }
17882
17883        if (res) {
17884            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17885            info.sendPackageRemovedBroadcasts(killApp);
17886            info.sendSystemPackageUpdatedBroadcasts();
17887            info.sendSystemPackageAppearedBroadcasts();
17888        }
17889        // Force a gc here.
17890        Runtime.getRuntime().gc();
17891        // Delete the resources here after sending the broadcast to let
17892        // other processes clean up before deleting resources.
17893        if (info.args != null) {
17894            synchronized (mInstallLock) {
17895                info.args.doPostDeleteLI(true);
17896            }
17897        }
17898
17899        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17900    }
17901
17902    static class PackageRemovedInfo {
17903        final PackageSender packageSender;
17904        String removedPackage;
17905        String installerPackageName;
17906        int uid = -1;
17907        int removedAppId = -1;
17908        int[] origUsers;
17909        int[] removedUsers = null;
17910        int[] broadcastUsers = null;
17911        int[] instantUserIds = null;
17912        SparseArray<Integer> installReasons;
17913        boolean isRemovedPackageSystemUpdate = false;
17914        boolean isUpdate;
17915        boolean dataRemoved;
17916        boolean removedForAllUsers;
17917        boolean isStaticSharedLib;
17918        // Clean up resources deleted packages.
17919        InstallArgs args = null;
17920        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17921        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17922
17923        PackageRemovedInfo(PackageSender packageSender) {
17924            this.packageSender = packageSender;
17925        }
17926
17927        void sendPackageRemovedBroadcasts(boolean killApp) {
17928            sendPackageRemovedBroadcastInternal(killApp);
17929            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17930            for (int i = 0; i < childCount; i++) {
17931                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17932                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17933            }
17934        }
17935
17936        void sendSystemPackageUpdatedBroadcasts() {
17937            if (isRemovedPackageSystemUpdate) {
17938                sendSystemPackageUpdatedBroadcastsInternal();
17939                final int childCount = (removedChildPackages != null)
17940                        ? removedChildPackages.size() : 0;
17941                for (int i = 0; i < childCount; i++) {
17942                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17943                    if (childInfo.isRemovedPackageSystemUpdate) {
17944                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17945                    }
17946                }
17947            }
17948        }
17949
17950        void sendSystemPackageAppearedBroadcasts() {
17951            final int packageCount = (appearedChildPackages != null)
17952                    ? appearedChildPackages.size() : 0;
17953            for (int i = 0; i < packageCount; i++) {
17954                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17955                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17956                    true /*sendBootCompleted*/, false /*startReceiver*/,
17957                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
17958            }
17959        }
17960
17961        private void sendSystemPackageUpdatedBroadcastsInternal() {
17962            Bundle extras = new Bundle(2);
17963            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17964            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17965            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17966                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17967            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17968                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
17969            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17970                null, null, 0, removedPackage, null, null, null);
17971            if (installerPackageName != null) {
17972                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17973                        removedPackage, extras, 0 /*flags*/,
17974                        installerPackageName, null, null, null);
17975                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17976                        removedPackage, extras, 0 /*flags*/,
17977                        installerPackageName, null, null, null);
17978            }
17979        }
17980
17981        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17982            // Don't send static shared library removal broadcasts as these
17983            // libs are visible only the the apps that depend on them an one
17984            // cannot remove the library if it has a dependency.
17985            if (isStaticSharedLib) {
17986                return;
17987            }
17988            Bundle extras = new Bundle(2);
17989            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17990            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17991            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17992            if (isUpdate || isRemovedPackageSystemUpdate) {
17993                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17994            }
17995            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17996            if (removedPackage != null) {
17997                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17998                    removedPackage, extras, 0, null /*targetPackage*/, null,
17999                    broadcastUsers, instantUserIds);
18000                if (installerPackageName != null) {
18001                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18002                            removedPackage, extras, 0 /*flags*/,
18003                            installerPackageName, null, broadcastUsers, instantUserIds);
18004                }
18005                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18006                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18007                        removedPackage, extras,
18008                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18009                        null, null, broadcastUsers, instantUserIds);
18010                    packageSender.notifyPackageRemoved(removedPackage);
18011                }
18012            }
18013            if (removedAppId >= 0) {
18014                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18015                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18016                    null, null, broadcastUsers, instantUserIds);
18017            }
18018        }
18019
18020        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18021            removedUsers = userIds;
18022            if (removedUsers == null) {
18023                broadcastUsers = null;
18024                return;
18025            }
18026
18027            broadcastUsers = EMPTY_INT_ARRAY;
18028            instantUserIds = EMPTY_INT_ARRAY;
18029            for (int i = userIds.length - 1; i >= 0; --i) {
18030                final int userId = userIds[i];
18031                if (deletedPackageSetting.getInstantApp(userId)) {
18032                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18033                } else {
18034                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18035                }
18036            }
18037        }
18038    }
18039
18040    /*
18041     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18042     * flag is not set, the data directory is removed as well.
18043     * make sure this flag is set for partially installed apps. If not its meaningless to
18044     * delete a partially installed application.
18045     */
18046    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18047            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18048        String packageName = ps.name;
18049        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18050        // Retrieve object to delete permissions for shared user later on
18051        final PackageParser.Package deletedPkg;
18052        final PackageSetting deletedPs;
18053        // reader
18054        synchronized (mPackages) {
18055            deletedPkg = mPackages.get(packageName);
18056            deletedPs = mSettings.mPackages.get(packageName);
18057            if (outInfo != null) {
18058                outInfo.removedPackage = packageName;
18059                outInfo.installerPackageName = ps.installerPackageName;
18060                outInfo.isStaticSharedLib = deletedPkg != null
18061                        && deletedPkg.staticSharedLibName != null;
18062                outInfo.populateUsers(deletedPs == null ? null
18063                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18064            }
18065        }
18066
18067        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18068
18069        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18070            final PackageParser.Package resolvedPkg;
18071            if (deletedPkg != null) {
18072                resolvedPkg = deletedPkg;
18073            } else {
18074                // We don't have a parsed package when it lives on an ejected
18075                // adopted storage device, so fake something together
18076                resolvedPkg = new PackageParser.Package(ps.name);
18077                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18078            }
18079            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18080                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18081            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18082            if (outInfo != null) {
18083                outInfo.dataRemoved = true;
18084            }
18085            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18086        }
18087
18088        int removedAppId = -1;
18089
18090        // writer
18091        synchronized (mPackages) {
18092            boolean installedStateChanged = false;
18093            if (deletedPs != null) {
18094                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18095                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18096                    clearDefaultBrowserIfNeeded(packageName);
18097                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18098                    removedAppId = mSettings.removePackageLPw(packageName);
18099                    if (outInfo != null) {
18100                        outInfo.removedAppId = removedAppId;
18101                    }
18102                    mPermissionManager.updatePermissions(
18103                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18104                    if (deletedPs.sharedUser != null) {
18105                        // Remove permissions associated with package. Since runtime
18106                        // permissions are per user we have to kill the removed package
18107                        // or packages running under the shared user of the removed
18108                        // package if revoking the permissions requested only by the removed
18109                        // package is successful and this causes a change in gids.
18110                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18111                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18112                                    userId);
18113                            if (userIdToKill == UserHandle.USER_ALL
18114                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18115                                // If gids changed for this user, kill all affected packages.
18116                                mHandler.post(new Runnable() {
18117                                    @Override
18118                                    public void run() {
18119                                        // This has to happen with no lock held.
18120                                        killApplication(deletedPs.name, deletedPs.appId,
18121                                                KILL_APP_REASON_GIDS_CHANGED);
18122                                    }
18123                                });
18124                                break;
18125                            }
18126                        }
18127                    }
18128                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18129                }
18130                // make sure to preserve per-user disabled state if this removal was just
18131                // a downgrade of a system app to the factory package
18132                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18133                    if (DEBUG_REMOVE) {
18134                        Slog.d(TAG, "Propagating install state across downgrade");
18135                    }
18136                    for (int userId : allUserHandles) {
18137                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18138                        if (DEBUG_REMOVE) {
18139                            Slog.d(TAG, "    user " + userId + " => " + installed);
18140                        }
18141                        if (installed != ps.getInstalled(userId)) {
18142                            installedStateChanged = true;
18143                        }
18144                        ps.setInstalled(installed, userId);
18145                    }
18146                }
18147            }
18148            // can downgrade to reader
18149            if (writeSettings) {
18150                // Save settings now
18151                mSettings.writeLPr();
18152            }
18153            if (installedStateChanged) {
18154                mSettings.writeKernelMappingLPr(ps);
18155            }
18156        }
18157        if (removedAppId != -1) {
18158            // A user ID was deleted here. Go through all users and remove it
18159            // from KeyStore.
18160            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18161        }
18162    }
18163
18164    static boolean locationIsPrivileged(String path) {
18165        try {
18166            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18167            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18168            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18169            return path.startsWith(privilegedAppDir.getCanonicalPath())
18170                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18171                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18172        } catch (IOException e) {
18173            Slog.e(TAG, "Unable to access code path " + path);
18174        }
18175        return false;
18176    }
18177
18178    static boolean locationIsOem(String path) {
18179        try {
18180            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18181        } catch (IOException e) {
18182            Slog.e(TAG, "Unable to access code path " + path);
18183        }
18184        return false;
18185    }
18186
18187    static boolean locationIsVendor(String path) {
18188        try {
18189            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
18190        } catch (IOException e) {
18191            Slog.e(TAG, "Unable to access code path " + path);
18192        }
18193        return false;
18194    }
18195
18196    static boolean locationIsProduct(String path) {
18197        try {
18198            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18199        } catch (IOException e) {
18200            Slog.e(TAG, "Unable to access code path " + path);
18201        }
18202        return false;
18203    }
18204
18205    /*
18206     * Tries to delete system package.
18207     */
18208    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18209            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18210            boolean writeSettings) {
18211        if (deletedPs.parentPackageName != null) {
18212            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18213            return false;
18214        }
18215
18216        final boolean applyUserRestrictions
18217                = (allUserHandles != null) && (outInfo.origUsers != null);
18218        final PackageSetting disabledPs;
18219        // Confirm if the system package has been updated
18220        // An updated system app can be deleted. This will also have to restore
18221        // the system pkg from system partition
18222        // reader
18223        synchronized (mPackages) {
18224            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18225        }
18226
18227        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18228                + " disabledPs=" + disabledPs);
18229
18230        if (disabledPs == null) {
18231            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18232            return false;
18233        } else if (DEBUG_REMOVE) {
18234            Slog.d(TAG, "Deleting system pkg from data partition");
18235        }
18236
18237        if (DEBUG_REMOVE) {
18238            if (applyUserRestrictions) {
18239                Slog.d(TAG, "Remembering install states:");
18240                for (int userId : allUserHandles) {
18241                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18242                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18243                }
18244            }
18245        }
18246
18247        // Delete the updated package
18248        outInfo.isRemovedPackageSystemUpdate = true;
18249        if (outInfo.removedChildPackages != null) {
18250            final int childCount = (deletedPs.childPackageNames != null)
18251                    ? deletedPs.childPackageNames.size() : 0;
18252            for (int i = 0; i < childCount; i++) {
18253                String childPackageName = deletedPs.childPackageNames.get(i);
18254                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18255                        .contains(childPackageName)) {
18256                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18257                            childPackageName);
18258                    if (childInfo != null) {
18259                        childInfo.isRemovedPackageSystemUpdate = true;
18260                    }
18261                }
18262            }
18263        }
18264
18265        if (disabledPs.versionCode < deletedPs.versionCode) {
18266            // Delete data for downgrades
18267            flags &= ~PackageManager.DELETE_KEEP_DATA;
18268        } else {
18269            // Preserve data by setting flag
18270            flags |= PackageManager.DELETE_KEEP_DATA;
18271        }
18272
18273        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18274                outInfo, writeSettings, disabledPs.pkg);
18275        if (!ret) {
18276            return false;
18277        }
18278
18279        // writer
18280        synchronized (mPackages) {
18281            // NOTE: The system package always needs to be enabled; even if it's for
18282            // a compressed stub. If we don't, installing the system package fails
18283            // during scan [scanning checks the disabled packages]. We will reverse
18284            // this later, after we've "installed" the stub.
18285            // Reinstate the old system package
18286            enableSystemPackageLPw(disabledPs.pkg);
18287            // Remove any native libraries from the upgraded package.
18288            removeNativeBinariesLI(deletedPs);
18289        }
18290
18291        // Install the system package
18292        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18293        try {
18294            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18295                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18296        } catch (PackageManagerException e) {
18297            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18298                    + e.getMessage());
18299            return false;
18300        } finally {
18301            if (disabledPs.pkg.isStub) {
18302                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18303            }
18304        }
18305        return true;
18306    }
18307
18308    /**
18309     * Installs a package that's already on the system partition.
18310     */
18311    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18312            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18313            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18314                    throws PackageManagerException {
18315        @ParseFlags int parseFlags =
18316                mDefParseFlags
18317                | PackageParser.PARSE_MUST_BE_APK
18318                | PackageParser.PARSE_IS_SYSTEM_DIR;
18319        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18320        if (isPrivileged || locationIsPrivileged(codePathString)) {
18321            scanFlags |= SCAN_AS_PRIVILEGED;
18322        }
18323        if (locationIsOem(codePathString)) {
18324            scanFlags |= SCAN_AS_OEM;
18325        }
18326        if (locationIsVendor(codePathString)) {
18327            scanFlags |= SCAN_AS_VENDOR;
18328        }
18329        if (locationIsProduct(codePathString)) {
18330            scanFlags |= SCAN_AS_PRODUCT;
18331        }
18332
18333        final File codePath = new File(codePathString);
18334        final PackageParser.Package pkg =
18335                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18336
18337        try {
18338            // update shared libraries for the newly re-installed system package
18339            updateSharedLibrariesLPr(pkg, null);
18340        } catch (PackageManagerException e) {
18341            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18342        }
18343
18344        prepareAppDataAfterInstallLIF(pkg);
18345
18346        // writer
18347        synchronized (mPackages) {
18348            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18349
18350            // Propagate the permissions state as we do not want to drop on the floor
18351            // runtime permissions. The update permissions method below will take
18352            // care of removing obsolete permissions and grant install permissions.
18353            if (origPermissionState != null) {
18354                ps.getPermissionsState().copyFrom(origPermissionState);
18355            }
18356            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18357                    mPermissionCallback);
18358
18359            final boolean applyUserRestrictions
18360                    = (allUserHandles != null) && (origUserHandles != null);
18361            if (applyUserRestrictions) {
18362                boolean installedStateChanged = false;
18363                if (DEBUG_REMOVE) {
18364                    Slog.d(TAG, "Propagating install state across reinstall");
18365                }
18366                for (int userId : allUserHandles) {
18367                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18368                    if (DEBUG_REMOVE) {
18369                        Slog.d(TAG, "    user " + userId + " => " + installed);
18370                    }
18371                    if (installed != ps.getInstalled(userId)) {
18372                        installedStateChanged = true;
18373                    }
18374                    ps.setInstalled(installed, userId);
18375
18376                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18377                }
18378                // Regardless of writeSettings we need to ensure that this restriction
18379                // state propagation is persisted
18380                mSettings.writeAllUsersPackageRestrictionsLPr();
18381                if (installedStateChanged) {
18382                    mSettings.writeKernelMappingLPr(ps);
18383                }
18384            }
18385            // can downgrade to reader here
18386            if (writeSettings) {
18387                mSettings.writeLPr();
18388            }
18389        }
18390        return pkg;
18391    }
18392
18393    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18394            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18395            PackageRemovedInfo outInfo, boolean writeSettings,
18396            PackageParser.Package replacingPackage) {
18397        synchronized (mPackages) {
18398            if (outInfo != null) {
18399                outInfo.uid = ps.appId;
18400            }
18401
18402            if (outInfo != null && outInfo.removedChildPackages != null) {
18403                final int childCount = (ps.childPackageNames != null)
18404                        ? ps.childPackageNames.size() : 0;
18405                for (int i = 0; i < childCount; i++) {
18406                    String childPackageName = ps.childPackageNames.get(i);
18407                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18408                    if (childPs == null) {
18409                        return false;
18410                    }
18411                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18412                            childPackageName);
18413                    if (childInfo != null) {
18414                        childInfo.uid = childPs.appId;
18415                    }
18416                }
18417            }
18418        }
18419
18420        // Delete package data from internal structures and also remove data if flag is set
18421        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18422
18423        // Delete the child packages data
18424        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18425        for (int i = 0; i < childCount; i++) {
18426            PackageSetting childPs;
18427            synchronized (mPackages) {
18428                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18429            }
18430            if (childPs != null) {
18431                PackageRemovedInfo childOutInfo = (outInfo != null
18432                        && outInfo.removedChildPackages != null)
18433                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18434                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18435                        && (replacingPackage != null
18436                        && !replacingPackage.hasChildPackage(childPs.name))
18437                        ? flags & ~DELETE_KEEP_DATA : flags;
18438                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18439                        deleteFlags, writeSettings);
18440            }
18441        }
18442
18443        // Delete application code and resources only for parent packages
18444        if (ps.parentPackageName == null) {
18445            if (deleteCodeAndResources && (outInfo != null)) {
18446                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18447                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18448                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18449            }
18450        }
18451
18452        return true;
18453    }
18454
18455    @Override
18456    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18457            int userId) {
18458        mContext.enforceCallingOrSelfPermission(
18459                android.Manifest.permission.DELETE_PACKAGES, null);
18460        synchronized (mPackages) {
18461            // Cannot block uninstall of static shared libs as they are
18462            // considered a part of the using app (emulating static linking).
18463            // Also static libs are installed always on internal storage.
18464            PackageParser.Package pkg = mPackages.get(packageName);
18465            if (pkg != null && pkg.staticSharedLibName != null) {
18466                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18467                        + " providing static shared library: " + pkg.staticSharedLibName);
18468                return false;
18469            }
18470            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18471            mSettings.writePackageRestrictionsLPr(userId);
18472        }
18473        return true;
18474    }
18475
18476    @Override
18477    public boolean getBlockUninstallForUser(String packageName, int userId) {
18478        synchronized (mPackages) {
18479            final PackageSetting ps = mSettings.mPackages.get(packageName);
18480            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18481                return false;
18482            }
18483            return mSettings.getBlockUninstallLPr(userId, packageName);
18484        }
18485    }
18486
18487    @Override
18488    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18489        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18490        synchronized (mPackages) {
18491            PackageSetting ps = mSettings.mPackages.get(packageName);
18492            if (ps == null) {
18493                Log.w(TAG, "Package doesn't exist: " + packageName);
18494                return false;
18495            }
18496            if (systemUserApp) {
18497                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18498            } else {
18499                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18500            }
18501            mSettings.writeLPr();
18502        }
18503        return true;
18504    }
18505
18506    /*
18507     * This method handles package deletion in general
18508     */
18509    private boolean deletePackageLIF(String packageName, UserHandle user,
18510            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18511            PackageRemovedInfo outInfo, boolean writeSettings,
18512            PackageParser.Package replacingPackage) {
18513        if (packageName == null) {
18514            Slog.w(TAG, "Attempt to delete null packageName.");
18515            return false;
18516        }
18517
18518        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18519
18520        PackageSetting ps;
18521        synchronized (mPackages) {
18522            ps = mSettings.mPackages.get(packageName);
18523            if (ps == null) {
18524                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18525                return false;
18526            }
18527
18528            if (ps.parentPackageName != null && (!isSystemApp(ps)
18529                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18530                if (DEBUG_REMOVE) {
18531                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18532                            + ((user == null) ? UserHandle.USER_ALL : user));
18533                }
18534                final int removedUserId = (user != null) ? user.getIdentifier()
18535                        : UserHandle.USER_ALL;
18536                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18537                    return false;
18538                }
18539                markPackageUninstalledForUserLPw(ps, user);
18540                scheduleWritePackageRestrictionsLocked(user);
18541                return true;
18542            }
18543        }
18544
18545        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18546                && user.getIdentifier() != UserHandle.USER_ALL)) {
18547            // The caller is asking that the package only be deleted for a single
18548            // user.  To do this, we just mark its uninstalled state and delete
18549            // its data. If this is a system app, we only allow this to happen if
18550            // they have set the special DELETE_SYSTEM_APP which requests different
18551            // semantics than normal for uninstalling system apps.
18552            markPackageUninstalledForUserLPw(ps, user);
18553
18554            if (!isSystemApp(ps)) {
18555                // Do not uninstall the APK if an app should be cached
18556                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18557                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18558                    // Other user still have this package installed, so all
18559                    // we need to do is clear this user's data and save that
18560                    // it is uninstalled.
18561                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18562                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18563                        return false;
18564                    }
18565                    scheduleWritePackageRestrictionsLocked(user);
18566                    return true;
18567                } else {
18568                    // We need to set it back to 'installed' so the uninstall
18569                    // broadcasts will be sent correctly.
18570                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18571                    ps.setInstalled(true, user.getIdentifier());
18572                    mSettings.writeKernelMappingLPr(ps);
18573                }
18574            } else {
18575                // This is a system app, so we assume that the
18576                // other users still have this package installed, so all
18577                // we need to do is clear this user's data and save that
18578                // it is uninstalled.
18579                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18580                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18581                    return false;
18582                }
18583                scheduleWritePackageRestrictionsLocked(user);
18584                return true;
18585            }
18586        }
18587
18588        // If we are deleting a composite package for all users, keep track
18589        // of result for each child.
18590        if (ps.childPackageNames != null && outInfo != null) {
18591            synchronized (mPackages) {
18592                final int childCount = ps.childPackageNames.size();
18593                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18594                for (int i = 0; i < childCount; i++) {
18595                    String childPackageName = ps.childPackageNames.get(i);
18596                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18597                    childInfo.removedPackage = childPackageName;
18598                    childInfo.installerPackageName = ps.installerPackageName;
18599                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18600                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18601                    if (childPs != null) {
18602                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18603                    }
18604                }
18605            }
18606        }
18607
18608        boolean ret = false;
18609        if (isSystemApp(ps)) {
18610            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18611            // When an updated system application is deleted we delete the existing resources
18612            // as well and fall back to existing code in system partition
18613            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18614        } else {
18615            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18616            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18617                    outInfo, writeSettings, replacingPackage);
18618        }
18619
18620        // Take a note whether we deleted the package for all users
18621        if (outInfo != null) {
18622            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18623            if (outInfo.removedChildPackages != null) {
18624                synchronized (mPackages) {
18625                    final int childCount = outInfo.removedChildPackages.size();
18626                    for (int i = 0; i < childCount; i++) {
18627                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18628                        if (childInfo != null) {
18629                            childInfo.removedForAllUsers = mPackages.get(
18630                                    childInfo.removedPackage) == null;
18631                        }
18632                    }
18633                }
18634            }
18635            // If we uninstalled an update to a system app there may be some
18636            // child packages that appeared as they are declared in the system
18637            // app but were not declared in the update.
18638            if (isSystemApp(ps)) {
18639                synchronized (mPackages) {
18640                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18641                    final int childCount = (updatedPs.childPackageNames != null)
18642                            ? updatedPs.childPackageNames.size() : 0;
18643                    for (int i = 0; i < childCount; i++) {
18644                        String childPackageName = updatedPs.childPackageNames.get(i);
18645                        if (outInfo.removedChildPackages == null
18646                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18647                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18648                            if (childPs == null) {
18649                                continue;
18650                            }
18651                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18652                            installRes.name = childPackageName;
18653                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18654                            installRes.pkg = mPackages.get(childPackageName);
18655                            installRes.uid = childPs.pkg.applicationInfo.uid;
18656                            if (outInfo.appearedChildPackages == null) {
18657                                outInfo.appearedChildPackages = new ArrayMap<>();
18658                            }
18659                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18660                        }
18661                    }
18662                }
18663            }
18664        }
18665
18666        return ret;
18667    }
18668
18669    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18670        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18671                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18672        for (int nextUserId : userIds) {
18673            if (DEBUG_REMOVE) {
18674                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18675            }
18676            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18677                    false /*installed*/,
18678                    true /*stopped*/,
18679                    true /*notLaunched*/,
18680                    false /*hidden*/,
18681                    false /*suspended*/,
18682                    false /*instantApp*/,
18683                    false /*virtualPreload*/,
18684                    null /*lastDisableAppCaller*/,
18685                    null /*enabledComponents*/,
18686                    null /*disabledComponents*/,
18687                    ps.readUserState(nextUserId).domainVerificationStatus,
18688                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18689                    null /*harmfulAppWarning*/);
18690        }
18691        mSettings.writeKernelMappingLPr(ps);
18692    }
18693
18694    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18695            PackageRemovedInfo outInfo) {
18696        final PackageParser.Package pkg;
18697        synchronized (mPackages) {
18698            pkg = mPackages.get(ps.name);
18699        }
18700
18701        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18702                : new int[] {userId};
18703        for (int nextUserId : userIds) {
18704            if (DEBUG_REMOVE) {
18705                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18706                        + nextUserId);
18707            }
18708
18709            destroyAppDataLIF(pkg, userId,
18710                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18711            destroyAppProfilesLIF(pkg, userId);
18712            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18713            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18714            schedulePackageCleaning(ps.name, nextUserId, false);
18715            synchronized (mPackages) {
18716                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18717                    scheduleWritePackageRestrictionsLocked(nextUserId);
18718                }
18719                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18720            }
18721        }
18722
18723        if (outInfo != null) {
18724            outInfo.removedPackage = ps.name;
18725            outInfo.installerPackageName = ps.installerPackageName;
18726            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18727            outInfo.removedAppId = ps.appId;
18728            outInfo.removedUsers = userIds;
18729            outInfo.broadcastUsers = userIds;
18730        }
18731
18732        return true;
18733    }
18734
18735    private final class ClearStorageConnection implements ServiceConnection {
18736        IMediaContainerService mContainerService;
18737
18738        @Override
18739        public void onServiceConnected(ComponentName name, IBinder service) {
18740            synchronized (this) {
18741                mContainerService = IMediaContainerService.Stub
18742                        .asInterface(Binder.allowBlocking(service));
18743                notifyAll();
18744            }
18745        }
18746
18747        @Override
18748        public void onServiceDisconnected(ComponentName name) {
18749        }
18750    }
18751
18752    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18753        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18754
18755        final boolean mounted;
18756        if (Environment.isExternalStorageEmulated()) {
18757            mounted = true;
18758        } else {
18759            final String status = Environment.getExternalStorageState();
18760
18761            mounted = status.equals(Environment.MEDIA_MOUNTED)
18762                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18763        }
18764
18765        if (!mounted) {
18766            return;
18767        }
18768
18769        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18770        int[] users;
18771        if (userId == UserHandle.USER_ALL) {
18772            users = sUserManager.getUserIds();
18773        } else {
18774            users = new int[] { userId };
18775        }
18776        final ClearStorageConnection conn = new ClearStorageConnection();
18777        if (mContext.bindServiceAsUser(
18778                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18779            try {
18780                for (int curUser : users) {
18781                    long timeout = SystemClock.uptimeMillis() + 5000;
18782                    synchronized (conn) {
18783                        long now;
18784                        while (conn.mContainerService == null &&
18785                                (now = SystemClock.uptimeMillis()) < timeout) {
18786                            try {
18787                                conn.wait(timeout - now);
18788                            } catch (InterruptedException e) {
18789                            }
18790                        }
18791                    }
18792                    if (conn.mContainerService == null) {
18793                        return;
18794                    }
18795
18796                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18797                    clearDirectory(conn.mContainerService,
18798                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18799                    if (allData) {
18800                        clearDirectory(conn.mContainerService,
18801                                userEnv.buildExternalStorageAppDataDirs(packageName));
18802                        clearDirectory(conn.mContainerService,
18803                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18804                    }
18805                }
18806            } finally {
18807                mContext.unbindService(conn);
18808            }
18809        }
18810    }
18811
18812    @Override
18813    public void clearApplicationProfileData(String packageName) {
18814        enforceSystemOrRoot("Only the system can clear all profile data");
18815
18816        final PackageParser.Package pkg;
18817        synchronized (mPackages) {
18818            pkg = mPackages.get(packageName);
18819        }
18820
18821        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18822            synchronized (mInstallLock) {
18823                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18824            }
18825        }
18826    }
18827
18828    @Override
18829    public void clearApplicationUserData(final String packageName,
18830            final IPackageDataObserver observer, final int userId) {
18831        mContext.enforceCallingOrSelfPermission(
18832                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18833
18834        final int callingUid = Binder.getCallingUid();
18835        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18836                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18837
18838        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18839        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18840        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18841            throw new SecurityException("Cannot clear data for a protected package: "
18842                    + packageName);
18843        }
18844        // Queue up an async operation since the package deletion may take a little while.
18845        mHandler.post(new Runnable() {
18846            public void run() {
18847                mHandler.removeCallbacks(this);
18848                final boolean succeeded;
18849                if (!filterApp) {
18850                    try (PackageFreezer freezer = freezePackage(packageName,
18851                            "clearApplicationUserData")) {
18852                        synchronized (mInstallLock) {
18853                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18854                        }
18855                        clearExternalStorageDataSync(packageName, userId, true);
18856                        synchronized (mPackages) {
18857                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18858                                    packageName, userId);
18859                        }
18860                    }
18861                    if (succeeded) {
18862                        // invoke DeviceStorageMonitor's update method to clear any notifications
18863                        DeviceStorageMonitorInternal dsm = LocalServices
18864                                .getService(DeviceStorageMonitorInternal.class);
18865                        if (dsm != null) {
18866                            dsm.checkMemory();
18867                        }
18868                    }
18869                } else {
18870                    succeeded = false;
18871                }
18872                if (observer != null) {
18873                    try {
18874                        observer.onRemoveCompleted(packageName, succeeded);
18875                    } catch (RemoteException e) {
18876                        Log.i(TAG, "Observer no longer exists.");
18877                    }
18878                } //end if observer
18879            } //end run
18880        });
18881    }
18882
18883    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18884        if (packageName == null) {
18885            Slog.w(TAG, "Attempt to delete null packageName.");
18886            return false;
18887        }
18888
18889        // Try finding details about the requested package
18890        PackageParser.Package pkg;
18891        synchronized (mPackages) {
18892            pkg = mPackages.get(packageName);
18893            if (pkg == null) {
18894                final PackageSetting ps = mSettings.mPackages.get(packageName);
18895                if (ps != null) {
18896                    pkg = ps.pkg;
18897                }
18898            }
18899
18900            if (pkg == null) {
18901                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18902                return false;
18903            }
18904
18905            PackageSetting ps = (PackageSetting) pkg.mExtras;
18906            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18907        }
18908
18909        clearAppDataLIF(pkg, userId,
18910                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18911
18912        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18913        removeKeystoreDataIfNeeded(userId, appId);
18914
18915        UserManagerInternal umInternal = getUserManagerInternal();
18916        final int flags;
18917        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18918            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18919        } else if (umInternal.isUserRunning(userId)) {
18920            flags = StorageManager.FLAG_STORAGE_DE;
18921        } else {
18922            flags = 0;
18923        }
18924        prepareAppDataContentsLIF(pkg, userId, flags);
18925
18926        return true;
18927    }
18928
18929    /**
18930     * Reverts user permission state changes (permissions and flags) in
18931     * all packages for a given user.
18932     *
18933     * @param userId The device user for which to do a reset.
18934     */
18935    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18936        final int packageCount = mPackages.size();
18937        for (int i = 0; i < packageCount; i++) {
18938            PackageParser.Package pkg = mPackages.valueAt(i);
18939            PackageSetting ps = (PackageSetting) pkg.mExtras;
18940            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18941        }
18942    }
18943
18944    private void resetNetworkPolicies(int userId) {
18945        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18946    }
18947
18948    /**
18949     * Reverts user permission state changes (permissions and flags).
18950     *
18951     * @param ps The package for which to reset.
18952     * @param userId The device user for which to do a reset.
18953     */
18954    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18955            final PackageSetting ps, final int userId) {
18956        if (ps.pkg == null) {
18957            return;
18958        }
18959
18960        // These are flags that can change base on user actions.
18961        final int userSettableMask = FLAG_PERMISSION_USER_SET
18962                | FLAG_PERMISSION_USER_FIXED
18963                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18964                | FLAG_PERMISSION_REVIEW_REQUIRED;
18965
18966        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18967                | FLAG_PERMISSION_POLICY_FIXED;
18968
18969        boolean writeInstallPermissions = false;
18970        boolean writeRuntimePermissions = false;
18971
18972        final int permissionCount = ps.pkg.requestedPermissions.size();
18973        for (int i = 0; i < permissionCount; i++) {
18974            final String permName = ps.pkg.requestedPermissions.get(i);
18975            final BasePermission bp =
18976                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18977            if (bp == null) {
18978                continue;
18979            }
18980
18981            // If shared user we just reset the state to which only this app contributed.
18982            if (ps.sharedUser != null) {
18983                boolean used = false;
18984                final int packageCount = ps.sharedUser.packages.size();
18985                for (int j = 0; j < packageCount; j++) {
18986                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18987                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18988                            && pkg.pkg.requestedPermissions.contains(permName)) {
18989                        used = true;
18990                        break;
18991                    }
18992                }
18993                if (used) {
18994                    continue;
18995                }
18996            }
18997
18998            final PermissionsState permissionsState = ps.getPermissionsState();
18999
19000            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19001
19002            // Always clear the user settable flags.
19003            final boolean hasInstallState =
19004                    permissionsState.getInstallPermissionState(permName) != null;
19005            // If permission review is enabled and this is a legacy app, mark the
19006            // permission as requiring a review as this is the initial state.
19007            int flags = 0;
19008            if (mSettings.mPermissions.mPermissionReviewRequired
19009                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19010                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19011            }
19012            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19013                if (hasInstallState) {
19014                    writeInstallPermissions = true;
19015                } else {
19016                    writeRuntimePermissions = true;
19017                }
19018            }
19019
19020            // Below is only runtime permission handling.
19021            if (!bp.isRuntime()) {
19022                continue;
19023            }
19024
19025            // Never clobber system or policy.
19026            if ((oldFlags & policyOrSystemFlags) != 0) {
19027                continue;
19028            }
19029
19030            // If this permission was granted by default, make sure it is.
19031            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19032                if (permissionsState.grantRuntimePermission(bp, userId)
19033                        != PERMISSION_OPERATION_FAILURE) {
19034                    writeRuntimePermissions = true;
19035                }
19036            // If permission review is enabled the permissions for a legacy apps
19037            // are represented as constantly granted runtime ones, so don't revoke.
19038            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19039                // Otherwise, reset the permission.
19040                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19041                switch (revokeResult) {
19042                    case PERMISSION_OPERATION_SUCCESS:
19043                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19044                        writeRuntimePermissions = true;
19045                        final int appId = ps.appId;
19046                        mHandler.post(new Runnable() {
19047                            @Override
19048                            public void run() {
19049                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19050                            }
19051                        });
19052                    } break;
19053                }
19054            }
19055        }
19056
19057        // Synchronously write as we are taking permissions away.
19058        if (writeRuntimePermissions) {
19059            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19060        }
19061
19062        // Synchronously write as we are taking permissions away.
19063        if (writeInstallPermissions) {
19064            mSettings.writeLPr();
19065        }
19066    }
19067
19068    /**
19069     * Remove entries from the keystore daemon. Will only remove it if the
19070     * {@code appId} is valid.
19071     */
19072    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19073        if (appId < 0) {
19074            return;
19075        }
19076
19077        final KeyStore keyStore = KeyStore.getInstance();
19078        if (keyStore != null) {
19079            if (userId == UserHandle.USER_ALL) {
19080                for (final int individual : sUserManager.getUserIds()) {
19081                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19082                }
19083            } else {
19084                keyStore.clearUid(UserHandle.getUid(userId, appId));
19085            }
19086        } else {
19087            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19088        }
19089    }
19090
19091    @Override
19092    public void deleteApplicationCacheFiles(final String packageName,
19093            final IPackageDataObserver observer) {
19094        final int userId = UserHandle.getCallingUserId();
19095        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19096    }
19097
19098    @Override
19099    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19100            final IPackageDataObserver observer) {
19101        final int callingUid = Binder.getCallingUid();
19102        mContext.enforceCallingOrSelfPermission(
19103                android.Manifest.permission.DELETE_CACHE_FILES, null);
19104        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19105                /* requireFullPermission= */ true, /* checkShell= */ false,
19106                "delete application cache files");
19107        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19108                android.Manifest.permission.ACCESS_INSTANT_APPS);
19109
19110        final PackageParser.Package pkg;
19111        synchronized (mPackages) {
19112            pkg = mPackages.get(packageName);
19113        }
19114
19115        // Queue up an async operation since the package deletion may take a little while.
19116        mHandler.post(new Runnable() {
19117            public void run() {
19118                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19119                boolean doClearData = true;
19120                if (ps != null) {
19121                    final boolean targetIsInstantApp =
19122                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19123                    doClearData = !targetIsInstantApp
19124                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19125                }
19126                if (doClearData) {
19127                    synchronized (mInstallLock) {
19128                        final int flags = StorageManager.FLAG_STORAGE_DE
19129                                | StorageManager.FLAG_STORAGE_CE;
19130                        // We're only clearing cache files, so we don't care if the
19131                        // app is unfrozen and still able to run
19132                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19133                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19134                    }
19135                    clearExternalStorageDataSync(packageName, userId, false);
19136                }
19137                if (observer != null) {
19138                    try {
19139                        observer.onRemoveCompleted(packageName, true);
19140                    } catch (RemoteException e) {
19141                        Log.i(TAG, "Observer no longer exists.");
19142                    }
19143                }
19144            }
19145        });
19146    }
19147
19148    @Override
19149    public void getPackageSizeInfo(final String packageName, int userHandle,
19150            final IPackageStatsObserver observer) {
19151        throw new UnsupportedOperationException(
19152                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19153    }
19154
19155    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19156        final PackageSetting ps;
19157        synchronized (mPackages) {
19158            ps = mSettings.mPackages.get(packageName);
19159            if (ps == null) {
19160                Slog.w(TAG, "Failed to find settings for " + packageName);
19161                return false;
19162            }
19163        }
19164
19165        final String[] packageNames = { packageName };
19166        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19167        final String[] codePaths = { ps.codePathString };
19168
19169        try {
19170            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19171                    ps.appId, ceDataInodes, codePaths, stats);
19172
19173            // For now, ignore code size of packages on system partition
19174            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19175                stats.codeSize = 0;
19176            }
19177
19178            // External clients expect these to be tracked separately
19179            stats.dataSize -= stats.cacheSize;
19180
19181        } catch (InstallerException e) {
19182            Slog.w(TAG, String.valueOf(e));
19183            return false;
19184        }
19185
19186        return true;
19187    }
19188
19189    private int getUidTargetSdkVersionLockedLPr(int uid) {
19190        Object obj = mSettings.getUserIdLPr(uid);
19191        if (obj instanceof SharedUserSetting) {
19192            final SharedUserSetting sus = (SharedUserSetting) obj;
19193            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19194            final Iterator<PackageSetting> it = sus.packages.iterator();
19195            while (it.hasNext()) {
19196                final PackageSetting ps = it.next();
19197                if (ps.pkg != null) {
19198                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19199                    if (v < vers) vers = v;
19200                }
19201            }
19202            return vers;
19203        } else if (obj instanceof PackageSetting) {
19204            final PackageSetting ps = (PackageSetting) obj;
19205            if (ps.pkg != null) {
19206                return ps.pkg.applicationInfo.targetSdkVersion;
19207            }
19208        }
19209        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19210    }
19211
19212    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19213        final PackageParser.Package p = mPackages.get(packageName);
19214        if (p != null) {
19215            return p.applicationInfo.targetSdkVersion;
19216        }
19217        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19218    }
19219
19220    @Override
19221    public void addPreferredActivity(IntentFilter filter, int match,
19222            ComponentName[] set, ComponentName activity, int userId) {
19223        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19224                "Adding preferred");
19225    }
19226
19227    private void addPreferredActivityInternal(IntentFilter filter, int match,
19228            ComponentName[] set, ComponentName activity, boolean always, int userId,
19229            String opname) {
19230        // writer
19231        int callingUid = Binder.getCallingUid();
19232        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19233                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19234        if (filter.countActions() == 0) {
19235            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19236            return;
19237        }
19238        synchronized (mPackages) {
19239            if (mContext.checkCallingOrSelfPermission(
19240                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19241                    != PackageManager.PERMISSION_GRANTED) {
19242                if (getUidTargetSdkVersionLockedLPr(callingUid)
19243                        < Build.VERSION_CODES.FROYO) {
19244                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19245                            + callingUid);
19246                    return;
19247                }
19248                mContext.enforceCallingOrSelfPermission(
19249                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19250            }
19251
19252            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19253            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19254                    + userId + ":");
19255            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19256            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19257            scheduleWritePackageRestrictionsLocked(userId);
19258            postPreferredActivityChangedBroadcast(userId);
19259        }
19260    }
19261
19262    private void postPreferredActivityChangedBroadcast(int userId) {
19263        mHandler.post(() -> {
19264            final IActivityManager am = ActivityManager.getService();
19265            if (am == null) {
19266                return;
19267            }
19268
19269            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19270            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19271            try {
19272                am.broadcastIntent(null, intent, null, null,
19273                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19274                        null, false, false, userId);
19275            } catch (RemoteException e) {
19276            }
19277        });
19278    }
19279
19280    @Override
19281    public void replacePreferredActivity(IntentFilter filter, int match,
19282            ComponentName[] set, ComponentName activity, int userId) {
19283        if (filter.countActions() != 1) {
19284            throw new IllegalArgumentException(
19285                    "replacePreferredActivity expects filter to have only 1 action.");
19286        }
19287        if (filter.countDataAuthorities() != 0
19288                || filter.countDataPaths() != 0
19289                || filter.countDataSchemes() > 1
19290                || filter.countDataTypes() != 0) {
19291            throw new IllegalArgumentException(
19292                    "replacePreferredActivity expects filter to have no data authorities, " +
19293                    "paths, or types; and at most one scheme.");
19294        }
19295
19296        final int callingUid = Binder.getCallingUid();
19297        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19298                true /* requireFullPermission */, false /* checkShell */,
19299                "replace preferred activity");
19300        synchronized (mPackages) {
19301            if (mContext.checkCallingOrSelfPermission(
19302                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19303                    != PackageManager.PERMISSION_GRANTED) {
19304                if (getUidTargetSdkVersionLockedLPr(callingUid)
19305                        < Build.VERSION_CODES.FROYO) {
19306                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19307                            + Binder.getCallingUid());
19308                    return;
19309                }
19310                mContext.enforceCallingOrSelfPermission(
19311                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19312            }
19313
19314            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19315            if (pir != null) {
19316                // Get all of the existing entries that exactly match this filter.
19317                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19318                if (existing != null && existing.size() == 1) {
19319                    PreferredActivity cur = existing.get(0);
19320                    if (DEBUG_PREFERRED) {
19321                        Slog.i(TAG, "Checking replace of preferred:");
19322                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19323                        if (!cur.mPref.mAlways) {
19324                            Slog.i(TAG, "  -- CUR; not mAlways!");
19325                        } else {
19326                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19327                            Slog.i(TAG, "  -- CUR: mSet="
19328                                    + Arrays.toString(cur.mPref.mSetComponents));
19329                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19330                            Slog.i(TAG, "  -- NEW: mMatch="
19331                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19332                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19333                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19334                        }
19335                    }
19336                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19337                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19338                            && cur.mPref.sameSet(set)) {
19339                        // Setting the preferred activity to what it happens to be already
19340                        if (DEBUG_PREFERRED) {
19341                            Slog.i(TAG, "Replacing with same preferred activity "
19342                                    + cur.mPref.mShortComponent + " for user "
19343                                    + userId + ":");
19344                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19345                        }
19346                        return;
19347                    }
19348                }
19349
19350                if (existing != null) {
19351                    if (DEBUG_PREFERRED) {
19352                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19353                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19354                    }
19355                    for (int i = 0; i < existing.size(); i++) {
19356                        PreferredActivity pa = existing.get(i);
19357                        if (DEBUG_PREFERRED) {
19358                            Slog.i(TAG, "Removing existing preferred activity "
19359                                    + pa.mPref.mComponent + ":");
19360                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19361                        }
19362                        pir.removeFilter(pa);
19363                    }
19364                }
19365            }
19366            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19367                    "Replacing preferred");
19368        }
19369    }
19370
19371    @Override
19372    public void clearPackagePreferredActivities(String packageName) {
19373        final int callingUid = Binder.getCallingUid();
19374        if (getInstantAppPackageName(callingUid) != null) {
19375            return;
19376        }
19377        // writer
19378        synchronized (mPackages) {
19379            PackageParser.Package pkg = mPackages.get(packageName);
19380            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19381                if (mContext.checkCallingOrSelfPermission(
19382                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19383                        != PackageManager.PERMISSION_GRANTED) {
19384                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19385                            < Build.VERSION_CODES.FROYO) {
19386                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19387                                + callingUid);
19388                        return;
19389                    }
19390                    mContext.enforceCallingOrSelfPermission(
19391                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19392                }
19393            }
19394            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19395            if (ps != null
19396                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19397                return;
19398            }
19399            int user = UserHandle.getCallingUserId();
19400            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19401                scheduleWritePackageRestrictionsLocked(user);
19402            }
19403        }
19404    }
19405
19406    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19407    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19408        ArrayList<PreferredActivity> removed = null;
19409        boolean changed = false;
19410        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19411            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19412            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19413            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19414                continue;
19415            }
19416            Iterator<PreferredActivity> it = pir.filterIterator();
19417            while (it.hasNext()) {
19418                PreferredActivity pa = it.next();
19419                // Mark entry for removal only if it matches the package name
19420                // and the entry is of type "always".
19421                if (packageName == null ||
19422                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19423                                && pa.mPref.mAlways)) {
19424                    if (removed == null) {
19425                        removed = new ArrayList<PreferredActivity>();
19426                    }
19427                    removed.add(pa);
19428                }
19429            }
19430            if (removed != null) {
19431                for (int j=0; j<removed.size(); j++) {
19432                    PreferredActivity pa = removed.get(j);
19433                    pir.removeFilter(pa);
19434                }
19435                changed = true;
19436            }
19437        }
19438        if (changed) {
19439            postPreferredActivityChangedBroadcast(userId);
19440        }
19441        return changed;
19442    }
19443
19444    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19445    private void clearIntentFilterVerificationsLPw(int userId) {
19446        final int packageCount = mPackages.size();
19447        for (int i = 0; i < packageCount; i++) {
19448            PackageParser.Package pkg = mPackages.valueAt(i);
19449            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19450        }
19451    }
19452
19453    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19454    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19455        if (userId == UserHandle.USER_ALL) {
19456            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19457                    sUserManager.getUserIds())) {
19458                for (int oneUserId : sUserManager.getUserIds()) {
19459                    scheduleWritePackageRestrictionsLocked(oneUserId);
19460                }
19461            }
19462        } else {
19463            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19464                scheduleWritePackageRestrictionsLocked(userId);
19465            }
19466        }
19467    }
19468
19469    /** Clears state for all users, and touches intent filter verification policy */
19470    void clearDefaultBrowserIfNeeded(String packageName) {
19471        for (int oneUserId : sUserManager.getUserIds()) {
19472            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19473        }
19474    }
19475
19476    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19477        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19478        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19479            if (packageName.equals(defaultBrowserPackageName)) {
19480                setDefaultBrowserPackageName(null, userId);
19481            }
19482        }
19483    }
19484
19485    @Override
19486    public void resetApplicationPreferences(int userId) {
19487        mContext.enforceCallingOrSelfPermission(
19488                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19489        final long identity = Binder.clearCallingIdentity();
19490        // writer
19491        try {
19492            synchronized (mPackages) {
19493                clearPackagePreferredActivitiesLPw(null, userId);
19494                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19495                // TODO: We have to reset the default SMS and Phone. This requires
19496                // significant refactoring to keep all default apps in the package
19497                // manager (cleaner but more work) or have the services provide
19498                // callbacks to the package manager to request a default app reset.
19499                applyFactoryDefaultBrowserLPw(userId);
19500                clearIntentFilterVerificationsLPw(userId);
19501                primeDomainVerificationsLPw(userId);
19502                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19503                scheduleWritePackageRestrictionsLocked(userId);
19504            }
19505            resetNetworkPolicies(userId);
19506        } finally {
19507            Binder.restoreCallingIdentity(identity);
19508        }
19509    }
19510
19511    @Override
19512    public int getPreferredActivities(List<IntentFilter> outFilters,
19513            List<ComponentName> outActivities, String packageName) {
19514        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19515            return 0;
19516        }
19517        int num = 0;
19518        final int userId = UserHandle.getCallingUserId();
19519        // reader
19520        synchronized (mPackages) {
19521            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19522            if (pir != null) {
19523                final Iterator<PreferredActivity> it = pir.filterIterator();
19524                while (it.hasNext()) {
19525                    final PreferredActivity pa = it.next();
19526                    if (packageName == null
19527                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19528                                    && pa.mPref.mAlways)) {
19529                        if (outFilters != null) {
19530                            outFilters.add(new IntentFilter(pa));
19531                        }
19532                        if (outActivities != null) {
19533                            outActivities.add(pa.mPref.mComponent);
19534                        }
19535                    }
19536                }
19537            }
19538        }
19539
19540        return num;
19541    }
19542
19543    @Override
19544    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19545            int userId) {
19546        int callingUid = Binder.getCallingUid();
19547        if (callingUid != Process.SYSTEM_UID) {
19548            throw new SecurityException(
19549                    "addPersistentPreferredActivity can only be run by the system");
19550        }
19551        if (filter.countActions() == 0) {
19552            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19553            return;
19554        }
19555        synchronized (mPackages) {
19556            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19557                    ":");
19558            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19559            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19560                    new PersistentPreferredActivity(filter, activity));
19561            scheduleWritePackageRestrictionsLocked(userId);
19562            postPreferredActivityChangedBroadcast(userId);
19563        }
19564    }
19565
19566    @Override
19567    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19568        int callingUid = Binder.getCallingUid();
19569        if (callingUid != Process.SYSTEM_UID) {
19570            throw new SecurityException(
19571                    "clearPackagePersistentPreferredActivities can only be run by the system");
19572        }
19573        ArrayList<PersistentPreferredActivity> removed = null;
19574        boolean changed = false;
19575        synchronized (mPackages) {
19576            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19577                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19578                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19579                        .valueAt(i);
19580                if (userId != thisUserId) {
19581                    continue;
19582                }
19583                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19584                while (it.hasNext()) {
19585                    PersistentPreferredActivity ppa = it.next();
19586                    // Mark entry for removal only if it matches the package name.
19587                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19588                        if (removed == null) {
19589                            removed = new ArrayList<PersistentPreferredActivity>();
19590                        }
19591                        removed.add(ppa);
19592                    }
19593                }
19594                if (removed != null) {
19595                    for (int j=0; j<removed.size(); j++) {
19596                        PersistentPreferredActivity ppa = removed.get(j);
19597                        ppir.removeFilter(ppa);
19598                    }
19599                    changed = true;
19600                }
19601            }
19602
19603            if (changed) {
19604                scheduleWritePackageRestrictionsLocked(userId);
19605                postPreferredActivityChangedBroadcast(userId);
19606            }
19607        }
19608    }
19609
19610    /**
19611     * Common machinery for picking apart a restored XML blob and passing
19612     * it to a caller-supplied functor to be applied to the running system.
19613     */
19614    private void restoreFromXml(XmlPullParser parser, int userId,
19615            String expectedStartTag, BlobXmlRestorer functor)
19616            throws IOException, XmlPullParserException {
19617        int type;
19618        while ((type = parser.next()) != XmlPullParser.START_TAG
19619                && type != XmlPullParser.END_DOCUMENT) {
19620        }
19621        if (type != XmlPullParser.START_TAG) {
19622            // oops didn't find a start tag?!
19623            if (DEBUG_BACKUP) {
19624                Slog.e(TAG, "Didn't find start tag during restore");
19625            }
19626            return;
19627        }
19628Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19629        // this is supposed to be TAG_PREFERRED_BACKUP
19630        if (!expectedStartTag.equals(parser.getName())) {
19631            if (DEBUG_BACKUP) {
19632                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19633            }
19634            return;
19635        }
19636
19637        // skip interfering stuff, then we're aligned with the backing implementation
19638        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19639Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19640        functor.apply(parser, userId);
19641    }
19642
19643    private interface BlobXmlRestorer {
19644        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19645    }
19646
19647    /**
19648     * Non-Binder method, support for the backup/restore mechanism: write the
19649     * full set of preferred activities in its canonical XML format.  Returns the
19650     * XML output as a byte array, or null if there is none.
19651     */
19652    @Override
19653    public byte[] getPreferredActivityBackup(int userId) {
19654        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19655            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19656        }
19657
19658        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19659        try {
19660            final XmlSerializer serializer = new FastXmlSerializer();
19661            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19662            serializer.startDocument(null, true);
19663            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19664
19665            synchronized (mPackages) {
19666                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19667            }
19668
19669            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19670            serializer.endDocument();
19671            serializer.flush();
19672        } catch (Exception e) {
19673            if (DEBUG_BACKUP) {
19674                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19675            }
19676            return null;
19677        }
19678
19679        return dataStream.toByteArray();
19680    }
19681
19682    @Override
19683    public void restorePreferredActivities(byte[] backup, int userId) {
19684        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19685            throw new SecurityException("Only the system may call restorePreferredActivities()");
19686        }
19687
19688        try {
19689            final XmlPullParser parser = Xml.newPullParser();
19690            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19691            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19692                    new BlobXmlRestorer() {
19693                        @Override
19694                        public void apply(XmlPullParser parser, int userId)
19695                                throws XmlPullParserException, IOException {
19696                            synchronized (mPackages) {
19697                                mSettings.readPreferredActivitiesLPw(parser, userId);
19698                            }
19699                        }
19700                    } );
19701        } catch (Exception e) {
19702            if (DEBUG_BACKUP) {
19703                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19704            }
19705        }
19706    }
19707
19708    /**
19709     * Non-Binder method, support for the backup/restore mechanism: write the
19710     * default browser (etc) settings in its canonical XML format.  Returns the default
19711     * browser XML representation as a byte array, or null if there is none.
19712     */
19713    @Override
19714    public byte[] getDefaultAppsBackup(int userId) {
19715        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19716            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19717        }
19718
19719        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19720        try {
19721            final XmlSerializer serializer = new FastXmlSerializer();
19722            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19723            serializer.startDocument(null, true);
19724            serializer.startTag(null, TAG_DEFAULT_APPS);
19725
19726            synchronized (mPackages) {
19727                mSettings.writeDefaultAppsLPr(serializer, userId);
19728            }
19729
19730            serializer.endTag(null, TAG_DEFAULT_APPS);
19731            serializer.endDocument();
19732            serializer.flush();
19733        } catch (Exception e) {
19734            if (DEBUG_BACKUP) {
19735                Slog.e(TAG, "Unable to write default apps for backup", e);
19736            }
19737            return null;
19738        }
19739
19740        return dataStream.toByteArray();
19741    }
19742
19743    @Override
19744    public void restoreDefaultApps(byte[] backup, int userId) {
19745        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19746            throw new SecurityException("Only the system may call restoreDefaultApps()");
19747        }
19748
19749        try {
19750            final XmlPullParser parser = Xml.newPullParser();
19751            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19752            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19753                    new BlobXmlRestorer() {
19754                        @Override
19755                        public void apply(XmlPullParser parser, int userId)
19756                                throws XmlPullParserException, IOException {
19757                            synchronized (mPackages) {
19758                                mSettings.readDefaultAppsLPw(parser, userId);
19759                            }
19760                        }
19761                    } );
19762        } catch (Exception e) {
19763            if (DEBUG_BACKUP) {
19764                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19765            }
19766        }
19767    }
19768
19769    @Override
19770    public byte[] getIntentFilterVerificationBackup(int userId) {
19771        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19772            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19773        }
19774
19775        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19776        try {
19777            final XmlSerializer serializer = new FastXmlSerializer();
19778            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19779            serializer.startDocument(null, true);
19780            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19781
19782            synchronized (mPackages) {
19783                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19784            }
19785
19786            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19787            serializer.endDocument();
19788            serializer.flush();
19789        } catch (Exception e) {
19790            if (DEBUG_BACKUP) {
19791                Slog.e(TAG, "Unable to write default apps for backup", e);
19792            }
19793            return null;
19794        }
19795
19796        return dataStream.toByteArray();
19797    }
19798
19799    @Override
19800    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19801        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19802            throw new SecurityException("Only the system may call restorePreferredActivities()");
19803        }
19804
19805        try {
19806            final XmlPullParser parser = Xml.newPullParser();
19807            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19808            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19809                    new BlobXmlRestorer() {
19810                        @Override
19811                        public void apply(XmlPullParser parser, int userId)
19812                                throws XmlPullParserException, IOException {
19813                            synchronized (mPackages) {
19814                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19815                                mSettings.writeLPr();
19816                            }
19817                        }
19818                    } );
19819        } catch (Exception e) {
19820            if (DEBUG_BACKUP) {
19821                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19822            }
19823        }
19824    }
19825
19826    @Override
19827    public byte[] getPermissionGrantBackup(int userId) {
19828        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19829            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19830        }
19831
19832        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19833        try {
19834            final XmlSerializer serializer = new FastXmlSerializer();
19835            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19836            serializer.startDocument(null, true);
19837            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19838
19839            synchronized (mPackages) {
19840                serializeRuntimePermissionGrantsLPr(serializer, userId);
19841            }
19842
19843            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19844            serializer.endDocument();
19845            serializer.flush();
19846        } catch (Exception e) {
19847            if (DEBUG_BACKUP) {
19848                Slog.e(TAG, "Unable to write default apps for backup", e);
19849            }
19850            return null;
19851        }
19852
19853        return dataStream.toByteArray();
19854    }
19855
19856    @Override
19857    public void restorePermissionGrants(byte[] backup, int userId) {
19858        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19859            throw new SecurityException("Only the system may call restorePermissionGrants()");
19860        }
19861
19862        try {
19863            final XmlPullParser parser = Xml.newPullParser();
19864            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19865            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19866                    new BlobXmlRestorer() {
19867                        @Override
19868                        public void apply(XmlPullParser parser, int userId)
19869                                throws XmlPullParserException, IOException {
19870                            synchronized (mPackages) {
19871                                processRestoredPermissionGrantsLPr(parser, userId);
19872                            }
19873                        }
19874                    } );
19875        } catch (Exception e) {
19876            if (DEBUG_BACKUP) {
19877                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19878            }
19879        }
19880    }
19881
19882    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19883            throws IOException {
19884        serializer.startTag(null, TAG_ALL_GRANTS);
19885
19886        final int N = mSettings.mPackages.size();
19887        for (int i = 0; i < N; i++) {
19888            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19889            boolean pkgGrantsKnown = false;
19890
19891            PermissionsState packagePerms = ps.getPermissionsState();
19892
19893            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19894                final int grantFlags = state.getFlags();
19895                // only look at grants that are not system/policy fixed
19896                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19897                    final boolean isGranted = state.isGranted();
19898                    // And only back up the user-twiddled state bits
19899                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19900                        final String packageName = mSettings.mPackages.keyAt(i);
19901                        if (!pkgGrantsKnown) {
19902                            serializer.startTag(null, TAG_GRANT);
19903                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19904                            pkgGrantsKnown = true;
19905                        }
19906
19907                        final boolean userSet =
19908                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19909                        final boolean userFixed =
19910                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19911                        final boolean revoke =
19912                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19913
19914                        serializer.startTag(null, TAG_PERMISSION);
19915                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19916                        if (isGranted) {
19917                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19918                        }
19919                        if (userSet) {
19920                            serializer.attribute(null, ATTR_USER_SET, "true");
19921                        }
19922                        if (userFixed) {
19923                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19924                        }
19925                        if (revoke) {
19926                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19927                        }
19928                        serializer.endTag(null, TAG_PERMISSION);
19929                    }
19930                }
19931            }
19932
19933            if (pkgGrantsKnown) {
19934                serializer.endTag(null, TAG_GRANT);
19935            }
19936        }
19937
19938        serializer.endTag(null, TAG_ALL_GRANTS);
19939    }
19940
19941    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19942            throws XmlPullParserException, IOException {
19943        String pkgName = null;
19944        int outerDepth = parser.getDepth();
19945        int type;
19946        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19947                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19948            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19949                continue;
19950            }
19951
19952            final String tagName = parser.getName();
19953            if (tagName.equals(TAG_GRANT)) {
19954                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19955                if (DEBUG_BACKUP) {
19956                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19957                }
19958            } else if (tagName.equals(TAG_PERMISSION)) {
19959
19960                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19961                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19962
19963                int newFlagSet = 0;
19964                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19965                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19966                }
19967                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19968                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19969                }
19970                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19971                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19972                }
19973                if (DEBUG_BACKUP) {
19974                    Slog.v(TAG, "  + Restoring grant:"
19975                            + " pkg=" + pkgName
19976                            + " perm=" + permName
19977                            + " granted=" + isGranted
19978                            + " bits=0x" + Integer.toHexString(newFlagSet));
19979                }
19980                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19981                if (ps != null) {
19982                    // Already installed so we apply the grant immediately
19983                    if (DEBUG_BACKUP) {
19984                        Slog.v(TAG, "        + already installed; applying");
19985                    }
19986                    PermissionsState perms = ps.getPermissionsState();
19987                    BasePermission bp =
19988                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19989                    if (bp != null) {
19990                        if (isGranted) {
19991                            perms.grantRuntimePermission(bp, userId);
19992                        }
19993                        if (newFlagSet != 0) {
19994                            perms.updatePermissionFlags(
19995                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19996                        }
19997                    }
19998                } else {
19999                    // Need to wait for post-restore install to apply the grant
20000                    if (DEBUG_BACKUP) {
20001                        Slog.v(TAG, "        - not yet installed; saving for later");
20002                    }
20003                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20004                            isGranted, newFlagSet, userId);
20005                }
20006            } else {
20007                PackageManagerService.reportSettingsProblem(Log.WARN,
20008                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20009                XmlUtils.skipCurrentTag(parser);
20010            }
20011        }
20012
20013        scheduleWriteSettingsLocked();
20014        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20015    }
20016
20017    @Override
20018    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20019            int sourceUserId, int targetUserId, int flags) {
20020        mContext.enforceCallingOrSelfPermission(
20021                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20022        int callingUid = Binder.getCallingUid();
20023        enforceOwnerRights(ownerPackage, callingUid);
20024        PackageManagerServiceUtils.enforceShellRestriction(
20025                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20026        if (intentFilter.countActions() == 0) {
20027            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20028            return;
20029        }
20030        synchronized (mPackages) {
20031            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20032                    ownerPackage, targetUserId, flags);
20033            CrossProfileIntentResolver resolver =
20034                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20035            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20036            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20037            if (existing != null) {
20038                int size = existing.size();
20039                for (int i = 0; i < size; i++) {
20040                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20041                        return;
20042                    }
20043                }
20044            }
20045            resolver.addFilter(newFilter);
20046            scheduleWritePackageRestrictionsLocked(sourceUserId);
20047        }
20048    }
20049
20050    @Override
20051    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20052        mContext.enforceCallingOrSelfPermission(
20053                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20054        final int callingUid = Binder.getCallingUid();
20055        enforceOwnerRights(ownerPackage, callingUid);
20056        PackageManagerServiceUtils.enforceShellRestriction(
20057                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20058        synchronized (mPackages) {
20059            CrossProfileIntentResolver resolver =
20060                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20061            ArraySet<CrossProfileIntentFilter> set =
20062                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20063            for (CrossProfileIntentFilter filter : set) {
20064                if (filter.getOwnerPackage().equals(ownerPackage)) {
20065                    resolver.removeFilter(filter);
20066                }
20067            }
20068            scheduleWritePackageRestrictionsLocked(sourceUserId);
20069        }
20070    }
20071
20072    // Enforcing that callingUid is owning pkg on userId
20073    private void enforceOwnerRights(String pkg, int callingUid) {
20074        // The system owns everything.
20075        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20076            return;
20077        }
20078        final int callingUserId = UserHandle.getUserId(callingUid);
20079        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20080        if (pi == null) {
20081            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20082                    + callingUserId);
20083        }
20084        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20085            throw new SecurityException("Calling uid " + callingUid
20086                    + " does not own package " + pkg);
20087        }
20088    }
20089
20090    @Override
20091    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20092        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20093            return null;
20094        }
20095        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20096    }
20097
20098    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20099        UserManagerService ums = UserManagerService.getInstance();
20100        if (ums != null) {
20101            final UserInfo parent = ums.getProfileParent(userId);
20102            final int launcherUid = (parent != null) ? parent.id : userId;
20103            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20104            if (launcherComponent != null) {
20105                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20106                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20107                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20108                        .setPackage(launcherComponent.getPackageName());
20109                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20110            }
20111        }
20112    }
20113
20114    /**
20115     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20116     * then reports the most likely home activity or null if there are more than one.
20117     */
20118    private ComponentName getDefaultHomeActivity(int userId) {
20119        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20120        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20121        if (cn != null) {
20122            return cn;
20123        }
20124
20125        // Find the launcher with the highest priority and return that component if there are no
20126        // other home activity with the same priority.
20127        int lastPriority = Integer.MIN_VALUE;
20128        ComponentName lastComponent = null;
20129        final int size = allHomeCandidates.size();
20130        for (int i = 0; i < size; i++) {
20131            final ResolveInfo ri = allHomeCandidates.get(i);
20132            if (ri.priority > lastPriority) {
20133                lastComponent = ri.activityInfo.getComponentName();
20134                lastPriority = ri.priority;
20135            } else if (ri.priority == lastPriority) {
20136                // Two components found with same priority.
20137                lastComponent = null;
20138            }
20139        }
20140        return lastComponent;
20141    }
20142
20143    private Intent getHomeIntent() {
20144        Intent intent = new Intent(Intent.ACTION_MAIN);
20145        intent.addCategory(Intent.CATEGORY_HOME);
20146        intent.addCategory(Intent.CATEGORY_DEFAULT);
20147        return intent;
20148    }
20149
20150    private IntentFilter getHomeFilter() {
20151        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20152        filter.addCategory(Intent.CATEGORY_HOME);
20153        filter.addCategory(Intent.CATEGORY_DEFAULT);
20154        return filter;
20155    }
20156
20157    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20158            int userId) {
20159        Intent intent  = getHomeIntent();
20160        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20161                PackageManager.GET_META_DATA, userId);
20162        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20163                true, false, false, userId);
20164
20165        allHomeCandidates.clear();
20166        if (list != null) {
20167            for (ResolveInfo ri : list) {
20168                allHomeCandidates.add(ri);
20169            }
20170        }
20171        return (preferred == null || preferred.activityInfo == null)
20172                ? null
20173                : new ComponentName(preferred.activityInfo.packageName,
20174                        preferred.activityInfo.name);
20175    }
20176
20177    @Override
20178    public void setHomeActivity(ComponentName comp, int userId) {
20179        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20180            return;
20181        }
20182        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20183        getHomeActivitiesAsUser(homeActivities, userId);
20184
20185        boolean found = false;
20186
20187        final int size = homeActivities.size();
20188        final ComponentName[] set = new ComponentName[size];
20189        for (int i = 0; i < size; i++) {
20190            final ResolveInfo candidate = homeActivities.get(i);
20191            final ActivityInfo info = candidate.activityInfo;
20192            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20193            set[i] = activityName;
20194            if (!found && activityName.equals(comp)) {
20195                found = true;
20196            }
20197        }
20198        if (!found) {
20199            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20200                    + userId);
20201        }
20202        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20203                set, comp, userId);
20204    }
20205
20206    private @Nullable String getSetupWizardPackageName() {
20207        final Intent intent = new Intent(Intent.ACTION_MAIN);
20208        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20209
20210        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20211                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20212                        | MATCH_DISABLED_COMPONENTS,
20213                UserHandle.myUserId());
20214        if (matches.size() == 1) {
20215            return matches.get(0).getComponentInfo().packageName;
20216        } else {
20217            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20218                    + ": matches=" + matches);
20219            return null;
20220        }
20221    }
20222
20223    private @Nullable String getStorageManagerPackageName() {
20224        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20225
20226        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20227                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20228                        | MATCH_DISABLED_COMPONENTS,
20229                UserHandle.myUserId());
20230        if (matches.size() == 1) {
20231            return matches.get(0).getComponentInfo().packageName;
20232        } else {
20233            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20234                    + matches.size() + ": matches=" + matches);
20235            return null;
20236        }
20237    }
20238
20239    @Override
20240    public void setApplicationEnabledSetting(String appPackageName,
20241            int newState, int flags, int userId, String callingPackage) {
20242        if (!sUserManager.exists(userId)) return;
20243        if (callingPackage == null) {
20244            callingPackage = Integer.toString(Binder.getCallingUid());
20245        }
20246        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20247    }
20248
20249    @Override
20250    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20251        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20252        synchronized (mPackages) {
20253            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20254            if (pkgSetting != null) {
20255                pkgSetting.setUpdateAvailable(updateAvailable);
20256            }
20257        }
20258    }
20259
20260    @Override
20261    public void setComponentEnabledSetting(ComponentName componentName,
20262            int newState, int flags, int userId) {
20263        if (!sUserManager.exists(userId)) return;
20264        setEnabledSetting(componentName.getPackageName(),
20265                componentName.getClassName(), newState, flags, userId, null);
20266    }
20267
20268    private void setEnabledSetting(final String packageName, String className, int newState,
20269            final int flags, int userId, String callingPackage) {
20270        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20271              || newState == COMPONENT_ENABLED_STATE_ENABLED
20272              || newState == COMPONENT_ENABLED_STATE_DISABLED
20273              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20274              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20275            throw new IllegalArgumentException("Invalid new component state: "
20276                    + newState);
20277        }
20278        PackageSetting pkgSetting;
20279        final int callingUid = Binder.getCallingUid();
20280        final int permission;
20281        if (callingUid == Process.SYSTEM_UID) {
20282            permission = PackageManager.PERMISSION_GRANTED;
20283        } else {
20284            permission = mContext.checkCallingOrSelfPermission(
20285                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20286        }
20287        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20288                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20289        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20290        boolean sendNow = false;
20291        boolean isApp = (className == null);
20292        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20293        String componentName = isApp ? packageName : className;
20294        int packageUid = -1;
20295        ArrayList<String> components;
20296
20297        // reader
20298        synchronized (mPackages) {
20299            pkgSetting = mSettings.mPackages.get(packageName);
20300            if (pkgSetting == null) {
20301                if (!isCallerInstantApp) {
20302                    if (className == null) {
20303                        throw new IllegalArgumentException("Unknown package: " + packageName);
20304                    }
20305                    throw new IllegalArgumentException(
20306                            "Unknown component: " + packageName + "/" + className);
20307                } else {
20308                    // throw SecurityException to prevent leaking package information
20309                    throw new SecurityException(
20310                            "Attempt to change component state; "
20311                            + "pid=" + Binder.getCallingPid()
20312                            + ", uid=" + callingUid
20313                            + (className == null
20314                                    ? ", package=" + packageName
20315                                    : ", component=" + packageName + "/" + className));
20316                }
20317            }
20318        }
20319
20320        // Limit who can change which apps
20321        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20322            // Don't allow apps that don't have permission to modify other apps
20323            if (!allowedByPermission
20324                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20325                throw new SecurityException(
20326                        "Attempt to change component state; "
20327                        + "pid=" + Binder.getCallingPid()
20328                        + ", uid=" + callingUid
20329                        + (className == null
20330                                ? ", package=" + packageName
20331                                : ", component=" + packageName + "/" + className));
20332            }
20333            // Don't allow changing protected packages.
20334            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20335                throw new SecurityException("Cannot disable a protected package: " + packageName);
20336            }
20337        }
20338
20339        synchronized (mPackages) {
20340            if (callingUid == Process.SHELL_UID
20341                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20342                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20343                // unless it is a test package.
20344                int oldState = pkgSetting.getEnabled(userId);
20345                if (className == null
20346                        &&
20347                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20348                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20349                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20350                        &&
20351                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20352                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20353                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20354                    // ok
20355                } else {
20356                    throw new SecurityException(
20357                            "Shell cannot change component state for " + packageName + "/"
20358                                    + className + " to " + newState);
20359                }
20360            }
20361        }
20362        if (className == null) {
20363            // We're dealing with an application/package level state change
20364            synchronized (mPackages) {
20365                if (pkgSetting.getEnabled(userId) == newState) {
20366                    // Nothing to do
20367                    return;
20368                }
20369            }
20370            // If we're enabling a system stub, there's a little more work to do.
20371            // Prior to enabling the package, we need to decompress the APK(s) to the
20372            // data partition and then replace the version on the system partition.
20373            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20374            final boolean isSystemStub = deletedPkg.isStub
20375                    && deletedPkg.isSystem();
20376            if (isSystemStub
20377                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20378                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20379                final File codePath = decompressPackage(deletedPkg);
20380                if (codePath == null) {
20381                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20382                    return;
20383                }
20384                // TODO remove direct parsing of the package object during internal cleanup
20385                // of scan package
20386                // We need to call parse directly here for no other reason than we need
20387                // the new package in order to disable the old one [we use the information
20388                // for some internal optimization to optionally create a new package setting
20389                // object on replace]. However, we can't get the package from the scan
20390                // because the scan modifies live structures and we need to remove the
20391                // old [system] package from the system before a scan can be attempted.
20392                // Once scan is indempotent we can remove this parse and use the package
20393                // object we scanned, prior to adding it to package settings.
20394                final PackageParser pp = new PackageParser();
20395                pp.setSeparateProcesses(mSeparateProcesses);
20396                pp.setDisplayMetrics(mMetrics);
20397                pp.setCallback(mPackageParserCallback);
20398                final PackageParser.Package tmpPkg;
20399                try {
20400                    final @ParseFlags int parseFlags = mDefParseFlags
20401                            | PackageParser.PARSE_MUST_BE_APK
20402                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20403                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20404                } catch (PackageParserException e) {
20405                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20406                    return;
20407                }
20408                synchronized (mInstallLock) {
20409                    // Disable the stub and remove any package entries
20410                    removePackageLI(deletedPkg, true);
20411                    synchronized (mPackages) {
20412                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20413                    }
20414                    final PackageParser.Package pkg;
20415                    try (PackageFreezer freezer =
20416                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20417                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20418                                | PackageParser.PARSE_ENFORCE_CODE;
20419                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20420                                0 /*currentTime*/, null /*user*/);
20421                        prepareAppDataAfterInstallLIF(pkg);
20422                        synchronized (mPackages) {
20423                            try {
20424                                updateSharedLibrariesLPr(pkg, null);
20425                            } catch (PackageManagerException e) {
20426                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20427                            }
20428                            mPermissionManager.updatePermissions(
20429                                    pkg.packageName, pkg, true, mPackages.values(),
20430                                    mPermissionCallback);
20431                            mSettings.writeLPr();
20432                        }
20433                    } catch (PackageManagerException e) {
20434                        // Whoops! Something went wrong; try to roll back to the stub
20435                        Slog.w(TAG, "Failed to install compressed system package:"
20436                                + pkgSetting.name, e);
20437                        // Remove the failed install
20438                        removeCodePathLI(codePath);
20439
20440                        // Install the system package
20441                        try (PackageFreezer freezer =
20442                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20443                            synchronized (mPackages) {
20444                                // NOTE: The system package always needs to be enabled; even
20445                                // if it's for a compressed stub. If we don't, installing the
20446                                // system package fails during scan [scanning checks the disabled
20447                                // packages]. We will reverse this later, after we've "installed"
20448                                // the stub.
20449                                // This leaves us in a fragile state; the stub should never be
20450                                // enabled, so, cross your fingers and hope nothing goes wrong
20451                                // until we can disable the package later.
20452                                enableSystemPackageLPw(deletedPkg);
20453                            }
20454                            installPackageFromSystemLIF(deletedPkg.codePath,
20455                                    false /*isPrivileged*/, null /*allUserHandles*/,
20456                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20457                                    true /*writeSettings*/);
20458                        } catch (PackageManagerException pme) {
20459                            Slog.w(TAG, "Failed to restore system package:"
20460                                    + deletedPkg.packageName, pme);
20461                        } finally {
20462                            synchronized (mPackages) {
20463                                mSettings.disableSystemPackageLPw(
20464                                        deletedPkg.packageName, true /*replaced*/);
20465                                mSettings.writeLPr();
20466                            }
20467                        }
20468                        return;
20469                    }
20470                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20471                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20472                    mDexManager.notifyPackageUpdated(pkg.packageName,
20473                            pkg.baseCodePath, pkg.splitCodePaths);
20474                }
20475            }
20476            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20477                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20478                // Don't care about who enables an app.
20479                callingPackage = null;
20480            }
20481            synchronized (mPackages) {
20482                pkgSetting.setEnabled(newState, userId, callingPackage);
20483            }
20484        } else {
20485            synchronized (mPackages) {
20486                // We're dealing with a component level state change
20487                // First, verify that this is a valid class name.
20488                PackageParser.Package pkg = pkgSetting.pkg;
20489                if (pkg == null || !pkg.hasComponentClassName(className)) {
20490                    if (pkg != null &&
20491                            pkg.applicationInfo.targetSdkVersion >=
20492                                    Build.VERSION_CODES.JELLY_BEAN) {
20493                        throw new IllegalArgumentException("Component class " + className
20494                                + " does not exist in " + packageName);
20495                    } else {
20496                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20497                                + className + " does not exist in " + packageName);
20498                    }
20499                }
20500                switch (newState) {
20501                    case COMPONENT_ENABLED_STATE_ENABLED:
20502                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20503                            return;
20504                        }
20505                        break;
20506                    case COMPONENT_ENABLED_STATE_DISABLED:
20507                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20508                            return;
20509                        }
20510                        break;
20511                    case COMPONENT_ENABLED_STATE_DEFAULT:
20512                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20513                            return;
20514                        }
20515                        break;
20516                    default:
20517                        Slog.e(TAG, "Invalid new component state: " + newState);
20518                        return;
20519                }
20520            }
20521        }
20522        synchronized (mPackages) {
20523            scheduleWritePackageRestrictionsLocked(userId);
20524            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20525            final long callingId = Binder.clearCallingIdentity();
20526            try {
20527                updateInstantAppInstallerLocked(packageName);
20528            } finally {
20529                Binder.restoreCallingIdentity(callingId);
20530            }
20531            components = mPendingBroadcasts.get(userId, packageName);
20532            final boolean newPackage = components == null;
20533            if (newPackage) {
20534                components = new ArrayList<String>();
20535            }
20536            if (!components.contains(componentName)) {
20537                components.add(componentName);
20538            }
20539            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20540                sendNow = true;
20541                // Purge entry from pending broadcast list if another one exists already
20542                // since we are sending one right away.
20543                mPendingBroadcasts.remove(userId, packageName);
20544            } else {
20545                if (newPackage) {
20546                    mPendingBroadcasts.put(userId, packageName, components);
20547                }
20548                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20549                    // Schedule a message
20550                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20551                }
20552            }
20553        }
20554
20555        long callingId = Binder.clearCallingIdentity();
20556        try {
20557            if (sendNow) {
20558                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20559                sendPackageChangedBroadcast(packageName,
20560                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20561            }
20562        } finally {
20563            Binder.restoreCallingIdentity(callingId);
20564        }
20565    }
20566
20567    @Override
20568    public void flushPackageRestrictionsAsUser(int userId) {
20569        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20570            return;
20571        }
20572        if (!sUserManager.exists(userId)) {
20573            return;
20574        }
20575        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20576                false /* checkShell */, "flushPackageRestrictions");
20577        synchronized (mPackages) {
20578            mSettings.writePackageRestrictionsLPr(userId);
20579            mDirtyUsers.remove(userId);
20580            if (mDirtyUsers.isEmpty()) {
20581                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20582            }
20583        }
20584    }
20585
20586    private void sendPackageChangedBroadcast(String packageName,
20587            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20588        if (DEBUG_INSTALL)
20589            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20590                    + componentNames);
20591        Bundle extras = new Bundle(4);
20592        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20593        String nameList[] = new String[componentNames.size()];
20594        componentNames.toArray(nameList);
20595        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20596        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20597        extras.putInt(Intent.EXTRA_UID, packageUid);
20598        // If this is not reporting a change of the overall package, then only send it
20599        // to registered receivers.  We don't want to launch a swath of apps for every
20600        // little component state change.
20601        final int flags = !componentNames.contains(packageName)
20602                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20603        final int userId = UserHandle.getUserId(packageUid);
20604        final boolean isInstantApp = isInstantApp(packageName, userId);
20605        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20606        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20607        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20608                userIds, instantUserIds);
20609    }
20610
20611    @Override
20612    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20613        if (!sUserManager.exists(userId)) return;
20614        final int callingUid = Binder.getCallingUid();
20615        if (getInstantAppPackageName(callingUid) != null) {
20616            return;
20617        }
20618        final int permission = mContext.checkCallingOrSelfPermission(
20619                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20620        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20621        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20622                true /* requireFullPermission */, true /* checkShell */, "stop package");
20623        // writer
20624        synchronized (mPackages) {
20625            final PackageSetting ps = mSettings.mPackages.get(packageName);
20626            if (!filterAppAccessLPr(ps, callingUid, userId)
20627                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20628                            allowedByPermission, callingUid, userId)) {
20629                scheduleWritePackageRestrictionsLocked(userId);
20630            }
20631        }
20632    }
20633
20634    @Override
20635    public String getInstallerPackageName(String packageName) {
20636        final int callingUid = Binder.getCallingUid();
20637        if (getInstantAppPackageName(callingUid) != null) {
20638            return null;
20639        }
20640        // reader
20641        synchronized (mPackages) {
20642            final PackageSetting ps = mSettings.mPackages.get(packageName);
20643            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20644                return null;
20645            }
20646            return mSettings.getInstallerPackageNameLPr(packageName);
20647        }
20648    }
20649
20650    public boolean isOrphaned(String packageName) {
20651        // reader
20652        synchronized (mPackages) {
20653            return mSettings.isOrphaned(packageName);
20654        }
20655    }
20656
20657    @Override
20658    public int getApplicationEnabledSetting(String packageName, int userId) {
20659        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20660        int callingUid = Binder.getCallingUid();
20661        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20662                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20663        // reader
20664        synchronized (mPackages) {
20665            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20666                return COMPONENT_ENABLED_STATE_DISABLED;
20667            }
20668            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20669        }
20670    }
20671
20672    @Override
20673    public int getComponentEnabledSetting(ComponentName component, int userId) {
20674        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20675        int callingUid = Binder.getCallingUid();
20676        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20677                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20678        synchronized (mPackages) {
20679            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20680                    component, TYPE_UNKNOWN, userId)) {
20681                return COMPONENT_ENABLED_STATE_DISABLED;
20682            }
20683            return mSettings.getComponentEnabledSettingLPr(component, userId);
20684        }
20685    }
20686
20687    @Override
20688    public void enterSafeMode() {
20689        enforceSystemOrRoot("Only the system can request entering safe mode");
20690
20691        if (!mSystemReady) {
20692            mSafeMode = true;
20693        }
20694    }
20695
20696    @Override
20697    public void systemReady() {
20698        enforceSystemOrRoot("Only the system can claim the system is ready");
20699
20700        mSystemReady = true;
20701        final ContentResolver resolver = mContext.getContentResolver();
20702        ContentObserver co = new ContentObserver(mHandler) {
20703            @Override
20704            public void onChange(boolean selfChange) {
20705                mEphemeralAppsDisabled =
20706                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20707                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20708            }
20709        };
20710        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20711                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20712                false, co, UserHandle.USER_SYSTEM);
20713        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20714                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20715        co.onChange(true);
20716
20717        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20718        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20719        // it is done.
20720        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20721            @Override
20722            public void onChange(boolean selfChange) {
20723                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20724                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20725                        oobEnabled == 1 ? "true" : "false");
20726            }
20727        };
20728        mContext.getContentResolver().registerContentObserver(
20729                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20730                UserHandle.USER_SYSTEM);
20731        // At boot, restore the value from the setting, which persists across reboot.
20732        privAppOobObserver.onChange(true);
20733
20734        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20735        // disabled after already being started.
20736        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20737                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20738
20739        // Read the compatibilty setting when the system is ready.
20740        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20741                mContext.getContentResolver(),
20742                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20743        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20744        if (DEBUG_SETTINGS) {
20745            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20746        }
20747
20748        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20749
20750        synchronized (mPackages) {
20751            // Verify that all of the preferred activity components actually
20752            // exist.  It is possible for applications to be updated and at
20753            // that point remove a previously declared activity component that
20754            // had been set as a preferred activity.  We try to clean this up
20755            // the next time we encounter that preferred activity, but it is
20756            // possible for the user flow to never be able to return to that
20757            // situation so here we do a sanity check to make sure we haven't
20758            // left any junk around.
20759            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20760            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20761                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20762                removed.clear();
20763                for (PreferredActivity pa : pir.filterSet()) {
20764                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20765                        removed.add(pa);
20766                    }
20767                }
20768                if (removed.size() > 0) {
20769                    for (int r=0; r<removed.size(); r++) {
20770                        PreferredActivity pa = removed.get(r);
20771                        Slog.w(TAG, "Removing dangling preferred activity: "
20772                                + pa.mPref.mComponent);
20773                        pir.removeFilter(pa);
20774                    }
20775                    mSettings.writePackageRestrictionsLPr(
20776                            mSettings.mPreferredActivities.keyAt(i));
20777                }
20778            }
20779
20780            for (int userId : UserManagerService.getInstance().getUserIds()) {
20781                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20782                    grantPermissionsUserIds = ArrayUtils.appendInt(
20783                            grantPermissionsUserIds, userId);
20784                }
20785            }
20786        }
20787        sUserManager.systemReady();
20788        // If we upgraded grant all default permissions before kicking off.
20789        for (int userId : grantPermissionsUserIds) {
20790            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20791        }
20792
20793        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20794            // If we did not grant default permissions, we preload from this the
20795            // default permission exceptions lazily to ensure we don't hit the
20796            // disk on a new user creation.
20797            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20798        }
20799
20800        // Now that we've scanned all packages, and granted any default
20801        // permissions, ensure permissions are updated. Beware of dragons if you
20802        // try optimizing this.
20803        synchronized (mPackages) {
20804            mPermissionManager.updateAllPermissions(
20805                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20806                    mPermissionCallback);
20807        }
20808
20809        // Kick off any messages waiting for system ready
20810        if (mPostSystemReadyMessages != null) {
20811            for (Message msg : mPostSystemReadyMessages) {
20812                msg.sendToTarget();
20813            }
20814            mPostSystemReadyMessages = null;
20815        }
20816
20817        // Watch for external volumes that come and go over time
20818        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20819        storage.registerListener(mStorageListener);
20820
20821        mInstallerService.systemReady();
20822        mPackageDexOptimizer.systemReady();
20823
20824        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20825                StorageManagerInternal.class);
20826        StorageManagerInternal.addExternalStoragePolicy(
20827                new StorageManagerInternal.ExternalStorageMountPolicy() {
20828            @Override
20829            public int getMountMode(int uid, String packageName) {
20830                if (Process.isIsolated(uid)) {
20831                    return Zygote.MOUNT_EXTERNAL_NONE;
20832                }
20833                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20834                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20835                }
20836                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20837                    return Zygote.MOUNT_EXTERNAL_READ;
20838                }
20839                return Zygote.MOUNT_EXTERNAL_WRITE;
20840            }
20841
20842            @Override
20843            public boolean hasExternalStorage(int uid, String packageName) {
20844                return true;
20845            }
20846        });
20847
20848        // Now that we're mostly running, clean up stale users and apps
20849        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20850        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20851
20852        mPermissionManager.systemReady();
20853    }
20854
20855    public void waitForAppDataPrepared() {
20856        if (mPrepareAppDataFuture == null) {
20857            return;
20858        }
20859        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20860        mPrepareAppDataFuture = null;
20861    }
20862
20863    @Override
20864    public boolean isSafeMode() {
20865        // allow instant applications
20866        return mSafeMode;
20867    }
20868
20869    @Override
20870    public boolean hasSystemUidErrors() {
20871        // allow instant applications
20872        return mHasSystemUidErrors;
20873    }
20874
20875    static String arrayToString(int[] array) {
20876        StringBuffer buf = new StringBuffer(128);
20877        buf.append('[');
20878        if (array != null) {
20879            for (int i=0; i<array.length; i++) {
20880                if (i > 0) buf.append(", ");
20881                buf.append(array[i]);
20882            }
20883        }
20884        buf.append(']');
20885        return buf.toString();
20886    }
20887
20888    @Override
20889    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20890            FileDescriptor err, String[] args, ShellCallback callback,
20891            ResultReceiver resultReceiver) {
20892        (new PackageManagerShellCommand(this)).exec(
20893                this, in, out, err, args, callback, resultReceiver);
20894    }
20895
20896    @Override
20897    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20898        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20899
20900        DumpState dumpState = new DumpState();
20901        boolean fullPreferred = false;
20902        boolean checkin = false;
20903
20904        String packageName = null;
20905        ArraySet<String> permissionNames = null;
20906
20907        int opti = 0;
20908        while (opti < args.length) {
20909            String opt = args[opti];
20910            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20911                break;
20912            }
20913            opti++;
20914
20915            if ("-a".equals(opt)) {
20916                // Right now we only know how to print all.
20917            } else if ("-h".equals(opt)) {
20918                pw.println("Package manager dump options:");
20919                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20920                pw.println("    --checkin: dump for a checkin");
20921                pw.println("    -f: print details of intent filters");
20922                pw.println("    -h: print this help");
20923                pw.println("  cmd may be one of:");
20924                pw.println("    l[ibraries]: list known shared libraries");
20925                pw.println("    f[eatures]: list device features");
20926                pw.println("    k[eysets]: print known keysets");
20927                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20928                pw.println("    perm[issions]: dump permissions");
20929                pw.println("    permission [name ...]: dump declaration and use of given permission");
20930                pw.println("    pref[erred]: print preferred package settings");
20931                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20932                pw.println("    prov[iders]: dump content providers");
20933                pw.println("    p[ackages]: dump installed packages");
20934                pw.println("    s[hared-users]: dump shared user IDs");
20935                pw.println("    m[essages]: print collected runtime messages");
20936                pw.println("    v[erifiers]: print package verifier info");
20937                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20938                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20939                pw.println("    version: print database version info");
20940                pw.println("    write: write current settings now");
20941                pw.println("    installs: details about install sessions");
20942                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20943                pw.println("    dexopt: dump dexopt state");
20944                pw.println("    compiler-stats: dump compiler statistics");
20945                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20946                pw.println("    service-permissions: dump permissions required by services");
20947                pw.println("    <package.name>: info about given package");
20948                return;
20949            } else if ("--checkin".equals(opt)) {
20950                checkin = true;
20951            } else if ("-f".equals(opt)) {
20952                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20953            } else if ("--proto".equals(opt)) {
20954                dumpProto(fd);
20955                return;
20956            } else {
20957                pw.println("Unknown argument: " + opt + "; use -h for help");
20958            }
20959        }
20960
20961        // Is the caller requesting to dump a particular piece of data?
20962        if (opti < args.length) {
20963            String cmd = args[opti];
20964            opti++;
20965            // Is this a package name?
20966            if ("android".equals(cmd) || cmd.contains(".")) {
20967                packageName = cmd;
20968                // When dumping a single package, we always dump all of its
20969                // filter information since the amount of data will be reasonable.
20970                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20971            } else if ("check-permission".equals(cmd)) {
20972                if (opti >= args.length) {
20973                    pw.println("Error: check-permission missing permission argument");
20974                    return;
20975                }
20976                String perm = args[opti];
20977                opti++;
20978                if (opti >= args.length) {
20979                    pw.println("Error: check-permission missing package argument");
20980                    return;
20981                }
20982
20983                String pkg = args[opti];
20984                opti++;
20985                int user = UserHandle.getUserId(Binder.getCallingUid());
20986                if (opti < args.length) {
20987                    try {
20988                        user = Integer.parseInt(args[opti]);
20989                    } catch (NumberFormatException e) {
20990                        pw.println("Error: check-permission user argument is not a number: "
20991                                + args[opti]);
20992                        return;
20993                    }
20994                }
20995
20996                // Normalize package name to handle renamed packages and static libs
20997                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20998
20999                pw.println(checkPermission(perm, pkg, user));
21000                return;
21001            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21002                dumpState.setDump(DumpState.DUMP_LIBS);
21003            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21004                dumpState.setDump(DumpState.DUMP_FEATURES);
21005            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21006                if (opti >= args.length) {
21007                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21008                            | DumpState.DUMP_SERVICE_RESOLVERS
21009                            | DumpState.DUMP_RECEIVER_RESOLVERS
21010                            | DumpState.DUMP_CONTENT_RESOLVERS);
21011                } else {
21012                    while (opti < args.length) {
21013                        String name = args[opti];
21014                        if ("a".equals(name) || "activity".equals(name)) {
21015                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21016                        } else if ("s".equals(name) || "service".equals(name)) {
21017                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21018                        } else if ("r".equals(name) || "receiver".equals(name)) {
21019                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21020                        } else if ("c".equals(name) || "content".equals(name)) {
21021                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21022                        } else {
21023                            pw.println("Error: unknown resolver table type: " + name);
21024                            return;
21025                        }
21026                        opti++;
21027                    }
21028                }
21029            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21030                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21031            } else if ("permission".equals(cmd)) {
21032                if (opti >= args.length) {
21033                    pw.println("Error: permission requires permission name");
21034                    return;
21035                }
21036                permissionNames = new ArraySet<>();
21037                while (opti < args.length) {
21038                    permissionNames.add(args[opti]);
21039                    opti++;
21040                }
21041                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21042                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21043            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21044                dumpState.setDump(DumpState.DUMP_PREFERRED);
21045            } else if ("preferred-xml".equals(cmd)) {
21046                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21047                if (opti < args.length && "--full".equals(args[opti])) {
21048                    fullPreferred = true;
21049                    opti++;
21050                }
21051            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21052                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21053            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21054                dumpState.setDump(DumpState.DUMP_PACKAGES);
21055            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21056                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21057            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21058                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21059            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21060                dumpState.setDump(DumpState.DUMP_MESSAGES);
21061            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21062                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21063            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21064                    || "intent-filter-verifiers".equals(cmd)) {
21065                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21066            } else if ("version".equals(cmd)) {
21067                dumpState.setDump(DumpState.DUMP_VERSION);
21068            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21069                dumpState.setDump(DumpState.DUMP_KEYSETS);
21070            } else if ("installs".equals(cmd)) {
21071                dumpState.setDump(DumpState.DUMP_INSTALLS);
21072            } else if ("frozen".equals(cmd)) {
21073                dumpState.setDump(DumpState.DUMP_FROZEN);
21074            } else if ("volumes".equals(cmd)) {
21075                dumpState.setDump(DumpState.DUMP_VOLUMES);
21076            } else if ("dexopt".equals(cmd)) {
21077                dumpState.setDump(DumpState.DUMP_DEXOPT);
21078            } else if ("compiler-stats".equals(cmd)) {
21079                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21080            } else if ("changes".equals(cmd)) {
21081                dumpState.setDump(DumpState.DUMP_CHANGES);
21082            } else if ("service-permissions".equals(cmd)) {
21083                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21084            } else if ("write".equals(cmd)) {
21085                synchronized (mPackages) {
21086                    mSettings.writeLPr();
21087                    pw.println("Settings written.");
21088                    return;
21089                }
21090            }
21091        }
21092
21093        if (checkin) {
21094            pw.println("vers,1");
21095        }
21096
21097        // reader
21098        synchronized (mPackages) {
21099            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21100                if (!checkin) {
21101                    if (dumpState.onTitlePrinted())
21102                        pw.println();
21103                    pw.println("Database versions:");
21104                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21105                }
21106            }
21107
21108            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21109                if (!checkin) {
21110                    if (dumpState.onTitlePrinted())
21111                        pw.println();
21112                    pw.println("Verifiers:");
21113                    pw.print("  Required: ");
21114                    pw.print(mRequiredVerifierPackage);
21115                    pw.print(" (uid=");
21116                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21117                            UserHandle.USER_SYSTEM));
21118                    pw.println(")");
21119                } else if (mRequiredVerifierPackage != null) {
21120                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21121                    pw.print(",");
21122                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21123                            UserHandle.USER_SYSTEM));
21124                }
21125            }
21126
21127            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21128                    packageName == null) {
21129                if (mIntentFilterVerifierComponent != null) {
21130                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21131                    if (!checkin) {
21132                        if (dumpState.onTitlePrinted())
21133                            pw.println();
21134                        pw.println("Intent Filter Verifier:");
21135                        pw.print("  Using: ");
21136                        pw.print(verifierPackageName);
21137                        pw.print(" (uid=");
21138                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21139                                UserHandle.USER_SYSTEM));
21140                        pw.println(")");
21141                    } else if (verifierPackageName != null) {
21142                        pw.print("ifv,"); pw.print(verifierPackageName);
21143                        pw.print(",");
21144                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21145                                UserHandle.USER_SYSTEM));
21146                    }
21147                } else {
21148                    pw.println();
21149                    pw.println("No Intent Filter Verifier available!");
21150                }
21151            }
21152
21153            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21154                boolean printedHeader = false;
21155                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21156                while (it.hasNext()) {
21157                    String libName = it.next();
21158                    LongSparseArray<SharedLibraryEntry> versionedLib
21159                            = mSharedLibraries.get(libName);
21160                    if (versionedLib == null) {
21161                        continue;
21162                    }
21163                    final int versionCount = versionedLib.size();
21164                    for (int i = 0; i < versionCount; i++) {
21165                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21166                        if (!checkin) {
21167                            if (!printedHeader) {
21168                                if (dumpState.onTitlePrinted())
21169                                    pw.println();
21170                                pw.println("Libraries:");
21171                                printedHeader = true;
21172                            }
21173                            pw.print("  ");
21174                        } else {
21175                            pw.print("lib,");
21176                        }
21177                        pw.print(libEntry.info.getName());
21178                        if (libEntry.info.isStatic()) {
21179                            pw.print(" version=" + libEntry.info.getLongVersion());
21180                        }
21181                        if (!checkin) {
21182                            pw.print(" -> ");
21183                        }
21184                        if (libEntry.path != null) {
21185                            pw.print(" (jar) ");
21186                            pw.print(libEntry.path);
21187                        } else {
21188                            pw.print(" (apk) ");
21189                            pw.print(libEntry.apk);
21190                        }
21191                        pw.println();
21192                    }
21193                }
21194            }
21195
21196            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21197                if (dumpState.onTitlePrinted())
21198                    pw.println();
21199                if (!checkin) {
21200                    pw.println("Features:");
21201                }
21202
21203                synchronized (mAvailableFeatures) {
21204                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21205                        if (checkin) {
21206                            pw.print("feat,");
21207                            pw.print(feat.name);
21208                            pw.print(",");
21209                            pw.println(feat.version);
21210                        } else {
21211                            pw.print("  ");
21212                            pw.print(feat.name);
21213                            if (feat.version > 0) {
21214                                pw.print(" version=");
21215                                pw.print(feat.version);
21216                            }
21217                            pw.println();
21218                        }
21219                    }
21220                }
21221            }
21222
21223            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21224                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21225                        : "Activity Resolver Table:", "  ", packageName,
21226                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21227                    dumpState.setTitlePrinted(true);
21228                }
21229            }
21230            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21231                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21232                        : "Receiver Resolver Table:", "  ", packageName,
21233                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21234                    dumpState.setTitlePrinted(true);
21235                }
21236            }
21237            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21238                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21239                        : "Service Resolver Table:", "  ", packageName,
21240                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21241                    dumpState.setTitlePrinted(true);
21242                }
21243            }
21244            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21245                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21246                        : "Provider Resolver Table:", "  ", packageName,
21247                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21248                    dumpState.setTitlePrinted(true);
21249                }
21250            }
21251
21252            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21253                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21254                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21255                    int user = mSettings.mPreferredActivities.keyAt(i);
21256                    if (pir.dump(pw,
21257                            dumpState.getTitlePrinted()
21258                                ? "\nPreferred Activities User " + user + ":"
21259                                : "Preferred Activities User " + user + ":", "  ",
21260                            packageName, true, false)) {
21261                        dumpState.setTitlePrinted(true);
21262                    }
21263                }
21264            }
21265
21266            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21267                pw.flush();
21268                FileOutputStream fout = new FileOutputStream(fd);
21269                BufferedOutputStream str = new BufferedOutputStream(fout);
21270                XmlSerializer serializer = new FastXmlSerializer();
21271                try {
21272                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21273                    serializer.startDocument(null, true);
21274                    serializer.setFeature(
21275                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21276                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21277                    serializer.endDocument();
21278                    serializer.flush();
21279                } catch (IllegalArgumentException e) {
21280                    pw.println("Failed writing: " + e);
21281                } catch (IllegalStateException e) {
21282                    pw.println("Failed writing: " + e);
21283                } catch (IOException e) {
21284                    pw.println("Failed writing: " + e);
21285                }
21286            }
21287
21288            if (!checkin
21289                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21290                    && packageName == null) {
21291                pw.println();
21292                int count = mSettings.mPackages.size();
21293                if (count == 0) {
21294                    pw.println("No applications!");
21295                    pw.println();
21296                } else {
21297                    final String prefix = "  ";
21298                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21299                    if (allPackageSettings.size() == 0) {
21300                        pw.println("No domain preferred apps!");
21301                        pw.println();
21302                    } else {
21303                        pw.println("App verification status:");
21304                        pw.println();
21305                        count = 0;
21306                        for (PackageSetting ps : allPackageSettings) {
21307                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21308                            if (ivi == null || ivi.getPackageName() == null) continue;
21309                            pw.println(prefix + "Package: " + ivi.getPackageName());
21310                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21311                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21312                            pw.println();
21313                            count++;
21314                        }
21315                        if (count == 0) {
21316                            pw.println(prefix + "No app verification established.");
21317                            pw.println();
21318                        }
21319                        for (int userId : sUserManager.getUserIds()) {
21320                            pw.println("App linkages for user " + userId + ":");
21321                            pw.println();
21322                            count = 0;
21323                            for (PackageSetting ps : allPackageSettings) {
21324                                final long status = ps.getDomainVerificationStatusForUser(userId);
21325                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21326                                        && !DEBUG_DOMAIN_VERIFICATION) {
21327                                    continue;
21328                                }
21329                                pw.println(prefix + "Package: " + ps.name);
21330                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21331                                String statusStr = IntentFilterVerificationInfo.
21332                                        getStatusStringFromValue(status);
21333                                pw.println(prefix + "Status:  " + statusStr);
21334                                pw.println();
21335                                count++;
21336                            }
21337                            if (count == 0) {
21338                                pw.println(prefix + "No configured app linkages.");
21339                                pw.println();
21340                            }
21341                        }
21342                    }
21343                }
21344            }
21345
21346            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21347                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21348            }
21349
21350            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21351                boolean printedSomething = false;
21352                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21353                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21354                        continue;
21355                    }
21356                    if (!printedSomething) {
21357                        if (dumpState.onTitlePrinted())
21358                            pw.println();
21359                        pw.println("Registered ContentProviders:");
21360                        printedSomething = true;
21361                    }
21362                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21363                    pw.print("    "); pw.println(p.toString());
21364                }
21365                printedSomething = false;
21366                for (Map.Entry<String, PackageParser.Provider> entry :
21367                        mProvidersByAuthority.entrySet()) {
21368                    PackageParser.Provider p = entry.getValue();
21369                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21370                        continue;
21371                    }
21372                    if (!printedSomething) {
21373                        if (dumpState.onTitlePrinted())
21374                            pw.println();
21375                        pw.println("ContentProvider Authorities:");
21376                        printedSomething = true;
21377                    }
21378                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21379                    pw.print("    "); pw.println(p.toString());
21380                    if (p.info != null && p.info.applicationInfo != null) {
21381                        final String appInfo = p.info.applicationInfo.toString();
21382                        pw.print("      applicationInfo="); pw.println(appInfo);
21383                    }
21384                }
21385            }
21386
21387            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21388                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21389            }
21390
21391            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21392                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21393            }
21394
21395            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21396                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21397            }
21398
21399            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21400                if (dumpState.onTitlePrinted()) pw.println();
21401                pw.println("Package Changes:");
21402                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21403                final int K = mChangedPackages.size();
21404                for (int i = 0; i < K; i++) {
21405                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21406                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21407                    final int N = changes.size();
21408                    if (N == 0) {
21409                        pw.print("    "); pw.println("No packages changed");
21410                    } else {
21411                        for (int j = 0; j < N; j++) {
21412                            final String pkgName = changes.valueAt(j);
21413                            final int sequenceNumber = changes.keyAt(j);
21414                            pw.print("    ");
21415                            pw.print("seq=");
21416                            pw.print(sequenceNumber);
21417                            pw.print(", package=");
21418                            pw.println(pkgName);
21419                        }
21420                    }
21421                }
21422            }
21423
21424            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21425                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21426            }
21427
21428            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21429                // XXX should handle packageName != null by dumping only install data that
21430                // the given package is involved with.
21431                if (dumpState.onTitlePrinted()) pw.println();
21432
21433                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21434                ipw.println();
21435                ipw.println("Frozen packages:");
21436                ipw.increaseIndent();
21437                if (mFrozenPackages.size() == 0) {
21438                    ipw.println("(none)");
21439                } else {
21440                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21441                        ipw.println(mFrozenPackages.valueAt(i));
21442                    }
21443                }
21444                ipw.decreaseIndent();
21445            }
21446
21447            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21448                if (dumpState.onTitlePrinted()) pw.println();
21449
21450                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21451                ipw.println();
21452                ipw.println("Loaded volumes:");
21453                ipw.increaseIndent();
21454                if (mLoadedVolumes.size() == 0) {
21455                    ipw.println("(none)");
21456                } else {
21457                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21458                        ipw.println(mLoadedVolumes.valueAt(i));
21459                    }
21460                }
21461                ipw.decreaseIndent();
21462            }
21463
21464            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21465                    && packageName == null) {
21466                if (dumpState.onTitlePrinted()) pw.println();
21467                pw.println("Service permissions:");
21468
21469                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21470                while (filterIterator.hasNext()) {
21471                    final ServiceIntentInfo info = filterIterator.next();
21472                    final ServiceInfo serviceInfo = info.service.info;
21473                    final String permission = serviceInfo.permission;
21474                    if (permission != null) {
21475                        pw.print("    ");
21476                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21477                        pw.print(": ");
21478                        pw.println(permission);
21479                    }
21480                }
21481            }
21482
21483            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21484                if (dumpState.onTitlePrinted()) pw.println();
21485                dumpDexoptStateLPr(pw, packageName);
21486            }
21487
21488            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21489                if (dumpState.onTitlePrinted()) pw.println();
21490                dumpCompilerStatsLPr(pw, packageName);
21491            }
21492
21493            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21494                if (dumpState.onTitlePrinted()) pw.println();
21495                mSettings.dumpReadMessagesLPr(pw, dumpState);
21496
21497                pw.println();
21498                pw.println("Package warning messages:");
21499                dumpCriticalInfo(pw, null);
21500            }
21501
21502            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21503                dumpCriticalInfo(pw, "msg,");
21504            }
21505        }
21506
21507        // PackageInstaller should be called outside of mPackages lock
21508        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21509            // XXX should handle packageName != null by dumping only install data that
21510            // the given package is involved with.
21511            if (dumpState.onTitlePrinted()) pw.println();
21512            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21513        }
21514    }
21515
21516    private void dumpProto(FileDescriptor fd) {
21517        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21518
21519        synchronized (mPackages) {
21520            final long requiredVerifierPackageToken =
21521                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21522            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21523            proto.write(
21524                    PackageServiceDumpProto.PackageShortProto.UID,
21525                    getPackageUid(
21526                            mRequiredVerifierPackage,
21527                            MATCH_DEBUG_TRIAGED_MISSING,
21528                            UserHandle.USER_SYSTEM));
21529            proto.end(requiredVerifierPackageToken);
21530
21531            if (mIntentFilterVerifierComponent != null) {
21532                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21533                final long verifierPackageToken =
21534                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21535                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21536                proto.write(
21537                        PackageServiceDumpProto.PackageShortProto.UID,
21538                        getPackageUid(
21539                                verifierPackageName,
21540                                MATCH_DEBUG_TRIAGED_MISSING,
21541                                UserHandle.USER_SYSTEM));
21542                proto.end(verifierPackageToken);
21543            }
21544
21545            dumpSharedLibrariesProto(proto);
21546            dumpFeaturesProto(proto);
21547            mSettings.dumpPackagesProto(proto);
21548            mSettings.dumpSharedUsersProto(proto);
21549            dumpCriticalInfo(proto);
21550        }
21551        proto.flush();
21552    }
21553
21554    private void dumpFeaturesProto(ProtoOutputStream proto) {
21555        synchronized (mAvailableFeatures) {
21556            final int count = mAvailableFeatures.size();
21557            for (int i = 0; i < count; i++) {
21558                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21559            }
21560        }
21561    }
21562
21563    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21564        final int count = mSharedLibraries.size();
21565        for (int i = 0; i < count; i++) {
21566            final String libName = mSharedLibraries.keyAt(i);
21567            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21568            if (versionedLib == null) {
21569                continue;
21570            }
21571            final int versionCount = versionedLib.size();
21572            for (int j = 0; j < versionCount; j++) {
21573                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21574                final long sharedLibraryToken =
21575                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21576                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21577                final boolean isJar = (libEntry.path != null);
21578                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21579                if (isJar) {
21580                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21581                } else {
21582                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21583                }
21584                proto.end(sharedLibraryToken);
21585            }
21586        }
21587    }
21588
21589    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21590        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21591        ipw.println();
21592        ipw.println("Dexopt state:");
21593        ipw.increaseIndent();
21594        Collection<PackageParser.Package> packages = null;
21595        if (packageName != null) {
21596            PackageParser.Package targetPackage = mPackages.get(packageName);
21597            if (targetPackage != null) {
21598                packages = Collections.singletonList(targetPackage);
21599            } else {
21600                ipw.println("Unable to find package: " + packageName);
21601                return;
21602            }
21603        } else {
21604            packages = mPackages.values();
21605        }
21606
21607        for (PackageParser.Package pkg : packages) {
21608            ipw.println("[" + pkg.packageName + "]");
21609            ipw.increaseIndent();
21610            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21611                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21612            ipw.decreaseIndent();
21613        }
21614    }
21615
21616    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21617        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21618        ipw.println();
21619        ipw.println("Compiler stats:");
21620        ipw.increaseIndent();
21621        Collection<PackageParser.Package> packages = null;
21622        if (packageName != null) {
21623            PackageParser.Package targetPackage = mPackages.get(packageName);
21624            if (targetPackage != null) {
21625                packages = Collections.singletonList(targetPackage);
21626            } else {
21627                ipw.println("Unable to find package: " + packageName);
21628                return;
21629            }
21630        } else {
21631            packages = mPackages.values();
21632        }
21633
21634        for (PackageParser.Package pkg : packages) {
21635            ipw.println("[" + pkg.packageName + "]");
21636            ipw.increaseIndent();
21637
21638            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21639            if (stats == null) {
21640                ipw.println("(No recorded stats)");
21641            } else {
21642                stats.dump(ipw);
21643            }
21644            ipw.decreaseIndent();
21645        }
21646    }
21647
21648    private String dumpDomainString(String packageName) {
21649        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21650                .getList();
21651        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21652
21653        ArraySet<String> result = new ArraySet<>();
21654        if (iviList.size() > 0) {
21655            for (IntentFilterVerificationInfo ivi : iviList) {
21656                for (String host : ivi.getDomains()) {
21657                    result.add(host);
21658                }
21659            }
21660        }
21661        if (filters != null && filters.size() > 0) {
21662            for (IntentFilter filter : filters) {
21663                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21664                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21665                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21666                    result.addAll(filter.getHostsList());
21667                }
21668            }
21669        }
21670
21671        StringBuilder sb = new StringBuilder(result.size() * 16);
21672        for (String domain : result) {
21673            if (sb.length() > 0) sb.append(" ");
21674            sb.append(domain);
21675        }
21676        return sb.toString();
21677    }
21678
21679    // ------- apps on sdcard specific code -------
21680    static final boolean DEBUG_SD_INSTALL = false;
21681
21682    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21683
21684    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21685
21686    private boolean mMediaMounted = false;
21687
21688    static String getEncryptKey() {
21689        try {
21690            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21691                    SD_ENCRYPTION_KEYSTORE_NAME);
21692            if (sdEncKey == null) {
21693                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21694                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21695                if (sdEncKey == null) {
21696                    Slog.e(TAG, "Failed to create encryption keys");
21697                    return null;
21698                }
21699            }
21700            return sdEncKey;
21701        } catch (NoSuchAlgorithmException nsae) {
21702            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21703            return null;
21704        } catch (IOException ioe) {
21705            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21706            return null;
21707        }
21708    }
21709
21710    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21711            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21712        final int size = infos.size();
21713        final String[] packageNames = new String[size];
21714        final int[] packageUids = new int[size];
21715        for (int i = 0; i < size; i++) {
21716            final ApplicationInfo info = infos.get(i);
21717            packageNames[i] = info.packageName;
21718            packageUids[i] = info.uid;
21719        }
21720        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21721                finishedReceiver);
21722    }
21723
21724    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21725            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21726        sendResourcesChangedBroadcast(mediaStatus, replacing,
21727                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21728    }
21729
21730    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21731            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21732        int size = pkgList.length;
21733        if (size > 0) {
21734            // Send broadcasts here
21735            Bundle extras = new Bundle();
21736            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21737            if (uidArr != null) {
21738                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21739            }
21740            if (replacing) {
21741                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21742            }
21743            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21744                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21745            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21746        }
21747    }
21748
21749    private void loadPrivatePackages(final VolumeInfo vol) {
21750        mHandler.post(new Runnable() {
21751            @Override
21752            public void run() {
21753                loadPrivatePackagesInner(vol);
21754            }
21755        });
21756    }
21757
21758    private void loadPrivatePackagesInner(VolumeInfo vol) {
21759        final String volumeUuid = vol.fsUuid;
21760        if (TextUtils.isEmpty(volumeUuid)) {
21761            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21762            return;
21763        }
21764
21765        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21766        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21767        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21768
21769        final VersionInfo ver;
21770        final List<PackageSetting> packages;
21771        synchronized (mPackages) {
21772            ver = mSettings.findOrCreateVersion(volumeUuid);
21773            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21774        }
21775
21776        for (PackageSetting ps : packages) {
21777            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21778            synchronized (mInstallLock) {
21779                final PackageParser.Package pkg;
21780                try {
21781                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21782                    loaded.add(pkg.applicationInfo);
21783
21784                } catch (PackageManagerException e) {
21785                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21786                }
21787
21788                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21789                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21790                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21791                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21792                }
21793            }
21794        }
21795
21796        // Reconcile app data for all started/unlocked users
21797        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21798        final UserManager um = mContext.getSystemService(UserManager.class);
21799        UserManagerInternal umInternal = getUserManagerInternal();
21800        for (UserInfo user : um.getUsers()) {
21801            final int flags;
21802            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21803                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21804            } else if (umInternal.isUserRunning(user.id)) {
21805                flags = StorageManager.FLAG_STORAGE_DE;
21806            } else {
21807                continue;
21808            }
21809
21810            try {
21811                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21812                synchronized (mInstallLock) {
21813                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21814                }
21815            } catch (IllegalStateException e) {
21816                // Device was probably ejected, and we'll process that event momentarily
21817                Slog.w(TAG, "Failed to prepare storage: " + e);
21818            }
21819        }
21820
21821        synchronized (mPackages) {
21822            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21823            if (sdkUpdated) {
21824                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21825                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21826            }
21827            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21828                    mPermissionCallback);
21829
21830            // Yay, everything is now upgraded
21831            ver.forceCurrent();
21832
21833            mSettings.writeLPr();
21834        }
21835
21836        for (PackageFreezer freezer : freezers) {
21837            freezer.close();
21838        }
21839
21840        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21841        sendResourcesChangedBroadcast(true, false, loaded, null);
21842        mLoadedVolumes.add(vol.getId());
21843    }
21844
21845    private void unloadPrivatePackages(final VolumeInfo vol) {
21846        mHandler.post(new Runnable() {
21847            @Override
21848            public void run() {
21849                unloadPrivatePackagesInner(vol);
21850            }
21851        });
21852    }
21853
21854    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21855        final String volumeUuid = vol.fsUuid;
21856        if (TextUtils.isEmpty(volumeUuid)) {
21857            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21858            return;
21859        }
21860
21861        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21862        synchronized (mInstallLock) {
21863        synchronized (mPackages) {
21864            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21865            for (PackageSetting ps : packages) {
21866                if (ps.pkg == null) continue;
21867
21868                final ApplicationInfo info = ps.pkg.applicationInfo;
21869                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21870                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21871
21872                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21873                        "unloadPrivatePackagesInner")) {
21874                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21875                            false, null)) {
21876                        unloaded.add(info);
21877                    } else {
21878                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21879                    }
21880                }
21881
21882                // Try very hard to release any references to this package
21883                // so we don't risk the system server being killed due to
21884                // open FDs
21885                AttributeCache.instance().removePackage(ps.name);
21886            }
21887
21888            mSettings.writeLPr();
21889        }
21890        }
21891
21892        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21893        sendResourcesChangedBroadcast(false, false, unloaded, null);
21894        mLoadedVolumes.remove(vol.getId());
21895
21896        // Try very hard to release any references to this path so we don't risk
21897        // the system server being killed due to open FDs
21898        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21899
21900        for (int i = 0; i < 3; i++) {
21901            System.gc();
21902            System.runFinalization();
21903        }
21904    }
21905
21906    private void assertPackageKnown(String volumeUuid, String packageName)
21907            throws PackageManagerException {
21908        synchronized (mPackages) {
21909            // Normalize package name to handle renamed packages
21910            packageName = normalizePackageNameLPr(packageName);
21911
21912            final PackageSetting ps = mSettings.mPackages.get(packageName);
21913            if (ps == null) {
21914                throw new PackageManagerException("Package " + packageName + " is unknown");
21915            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21916                throw new PackageManagerException(
21917                        "Package " + packageName + " found on unknown volume " + volumeUuid
21918                                + "; expected volume " + ps.volumeUuid);
21919            }
21920        }
21921    }
21922
21923    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21924            throws PackageManagerException {
21925        synchronized (mPackages) {
21926            // Normalize package name to handle renamed packages
21927            packageName = normalizePackageNameLPr(packageName);
21928
21929            final PackageSetting ps = mSettings.mPackages.get(packageName);
21930            if (ps == null) {
21931                throw new PackageManagerException("Package " + packageName + " is unknown");
21932            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21933                throw new PackageManagerException(
21934                        "Package " + packageName + " found on unknown volume " + volumeUuid
21935                                + "; expected volume " + ps.volumeUuid);
21936            } else if (!ps.getInstalled(userId)) {
21937                throw new PackageManagerException(
21938                        "Package " + packageName + " not installed for user " + userId);
21939            }
21940        }
21941    }
21942
21943    private List<String> collectAbsoluteCodePaths() {
21944        synchronized (mPackages) {
21945            List<String> codePaths = new ArrayList<>();
21946            final int packageCount = mSettings.mPackages.size();
21947            for (int i = 0; i < packageCount; i++) {
21948                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21949                codePaths.add(ps.codePath.getAbsolutePath());
21950            }
21951            return codePaths;
21952        }
21953    }
21954
21955    /**
21956     * Examine all apps present on given mounted volume, and destroy apps that
21957     * aren't expected, either due to uninstallation or reinstallation on
21958     * another volume.
21959     */
21960    private void reconcileApps(String volumeUuid) {
21961        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21962        List<File> filesToDelete = null;
21963
21964        final File[] files = FileUtils.listFilesOrEmpty(
21965                Environment.getDataAppDirectory(volumeUuid));
21966        for (File file : files) {
21967            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21968                    && !PackageInstallerService.isStageName(file.getName());
21969            if (!isPackage) {
21970                // Ignore entries which are not packages
21971                continue;
21972            }
21973
21974            String absolutePath = file.getAbsolutePath();
21975
21976            boolean pathValid = false;
21977            final int absoluteCodePathCount = absoluteCodePaths.size();
21978            for (int i = 0; i < absoluteCodePathCount; i++) {
21979                String absoluteCodePath = absoluteCodePaths.get(i);
21980                if (absolutePath.startsWith(absoluteCodePath)) {
21981                    pathValid = true;
21982                    break;
21983                }
21984            }
21985
21986            if (!pathValid) {
21987                if (filesToDelete == null) {
21988                    filesToDelete = new ArrayList<>();
21989                }
21990                filesToDelete.add(file);
21991            }
21992        }
21993
21994        if (filesToDelete != null) {
21995            final int fileToDeleteCount = filesToDelete.size();
21996            for (int i = 0; i < fileToDeleteCount; i++) {
21997                File fileToDelete = filesToDelete.get(i);
21998                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21999                synchronized (mInstallLock) {
22000                    removeCodePathLI(fileToDelete);
22001                }
22002            }
22003        }
22004    }
22005
22006    /**
22007     * Reconcile all app data for the given user.
22008     * <p>
22009     * Verifies that directories exist and that ownership and labeling is
22010     * correct for all installed apps on all mounted volumes.
22011     */
22012    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22013        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22014        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22015            final String volumeUuid = vol.getFsUuid();
22016            synchronized (mInstallLock) {
22017                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22018            }
22019        }
22020    }
22021
22022    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22023            boolean migrateAppData) {
22024        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22025    }
22026
22027    /**
22028     * Reconcile all app data on given mounted volume.
22029     * <p>
22030     * Destroys app data that isn't expected, either due to uninstallation or
22031     * reinstallation on another volume.
22032     * <p>
22033     * Verifies that directories exist and that ownership and labeling is
22034     * correct for all installed apps.
22035     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22036     */
22037    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22038            boolean migrateAppData, boolean onlyCoreApps) {
22039        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22040                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22041        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22042
22043        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22044        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22045
22046        // First look for stale data that doesn't belong, and check if things
22047        // have changed since we did our last restorecon
22048        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22049            if (StorageManager.isFileEncryptedNativeOrEmulated()
22050                    && !StorageManager.isUserKeyUnlocked(userId)) {
22051                throw new RuntimeException(
22052                        "Yikes, someone asked us to reconcile CE storage while " + userId
22053                                + " was still locked; this would have caused massive data loss!");
22054            }
22055
22056            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22057            for (File file : files) {
22058                final String packageName = file.getName();
22059                try {
22060                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22061                } catch (PackageManagerException e) {
22062                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22063                    try {
22064                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22065                                StorageManager.FLAG_STORAGE_CE, 0);
22066                    } catch (InstallerException e2) {
22067                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22068                    }
22069                }
22070            }
22071        }
22072        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22073            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22074            for (File file : files) {
22075                final String packageName = file.getName();
22076                try {
22077                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22078                } catch (PackageManagerException e) {
22079                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22080                    try {
22081                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22082                                StorageManager.FLAG_STORAGE_DE, 0);
22083                    } catch (InstallerException e2) {
22084                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22085                    }
22086                }
22087            }
22088        }
22089
22090        // Ensure that data directories are ready to roll for all packages
22091        // installed for this volume and user
22092        final List<PackageSetting> packages;
22093        synchronized (mPackages) {
22094            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22095        }
22096        int preparedCount = 0;
22097        for (PackageSetting ps : packages) {
22098            final String packageName = ps.name;
22099            if (ps.pkg == null) {
22100                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22101                // TODO: might be due to legacy ASEC apps; we should circle back
22102                // and reconcile again once they're scanned
22103                continue;
22104            }
22105            // Skip non-core apps if requested
22106            if (onlyCoreApps && !ps.pkg.coreApp) {
22107                result.add(packageName);
22108                continue;
22109            }
22110
22111            if (ps.getInstalled(userId)) {
22112                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22113                preparedCount++;
22114            }
22115        }
22116
22117        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22118        return result;
22119    }
22120
22121    /**
22122     * Prepare app data for the given app just after it was installed or
22123     * upgraded. This method carefully only touches users that it's installed
22124     * for, and it forces a restorecon to handle any seinfo changes.
22125     * <p>
22126     * Verifies that directories exist and that ownership and labeling is
22127     * correct for all installed apps. If there is an ownership mismatch, it
22128     * will try recovering system apps by wiping data; third-party app data is
22129     * left intact.
22130     * <p>
22131     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22132     */
22133    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22134        final PackageSetting ps;
22135        synchronized (mPackages) {
22136            ps = mSettings.mPackages.get(pkg.packageName);
22137            mSettings.writeKernelMappingLPr(ps);
22138        }
22139
22140        final UserManager um = mContext.getSystemService(UserManager.class);
22141        UserManagerInternal umInternal = getUserManagerInternal();
22142        for (UserInfo user : um.getUsers()) {
22143            final int flags;
22144            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22145                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22146            } else if (umInternal.isUserRunning(user.id)) {
22147                flags = StorageManager.FLAG_STORAGE_DE;
22148            } else {
22149                continue;
22150            }
22151
22152            if (ps.getInstalled(user.id)) {
22153                // TODO: when user data is locked, mark that we're still dirty
22154                prepareAppDataLIF(pkg, user.id, flags);
22155            }
22156        }
22157    }
22158
22159    /**
22160     * Prepare app data for the given app.
22161     * <p>
22162     * Verifies that directories exist and that ownership and labeling is
22163     * correct for all installed apps. If there is an ownership mismatch, this
22164     * will try recovering system apps by wiping data; third-party app data is
22165     * left intact.
22166     */
22167    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22168        if (pkg == null) {
22169            Slog.wtf(TAG, "Package was null!", new Throwable());
22170            return;
22171        }
22172        prepareAppDataLeafLIF(pkg, userId, flags);
22173        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22174        for (int i = 0; i < childCount; i++) {
22175            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22176        }
22177    }
22178
22179    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22180            boolean maybeMigrateAppData) {
22181        prepareAppDataLIF(pkg, userId, flags);
22182
22183        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22184            // We may have just shuffled around app data directories, so
22185            // prepare them one more time
22186            prepareAppDataLIF(pkg, userId, flags);
22187        }
22188    }
22189
22190    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22191        if (DEBUG_APP_DATA) {
22192            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22193                    + Integer.toHexString(flags));
22194        }
22195
22196        final String volumeUuid = pkg.volumeUuid;
22197        final String packageName = pkg.packageName;
22198        final ApplicationInfo app = pkg.applicationInfo;
22199        final int appId = UserHandle.getAppId(app.uid);
22200
22201        Preconditions.checkNotNull(app.seInfo);
22202
22203        long ceDataInode = -1;
22204        try {
22205            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22206                    appId, app.seInfo, app.targetSdkVersion);
22207        } catch (InstallerException e) {
22208            if (app.isSystemApp()) {
22209                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22210                        + ", but trying to recover: " + e);
22211                destroyAppDataLeafLIF(pkg, userId, flags);
22212                try {
22213                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22214                            appId, app.seInfo, app.targetSdkVersion);
22215                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22216                } catch (InstallerException e2) {
22217                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22218                }
22219            } else {
22220                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22221            }
22222        }
22223        // Prepare the application profiles.
22224        mArtManagerService.prepareAppProfiles(pkg, userId);
22225
22226        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22227            // TODO: mark this structure as dirty so we persist it!
22228            synchronized (mPackages) {
22229                final PackageSetting ps = mSettings.mPackages.get(packageName);
22230                if (ps != null) {
22231                    ps.setCeDataInode(ceDataInode, userId);
22232                }
22233            }
22234        }
22235
22236        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22237    }
22238
22239    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22240        if (pkg == null) {
22241            Slog.wtf(TAG, "Package was null!", new Throwable());
22242            return;
22243        }
22244        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22245        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22246        for (int i = 0; i < childCount; i++) {
22247            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22248        }
22249    }
22250
22251    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22252        final String volumeUuid = pkg.volumeUuid;
22253        final String packageName = pkg.packageName;
22254        final ApplicationInfo app = pkg.applicationInfo;
22255
22256        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22257            // Create a native library symlink only if we have native libraries
22258            // and if the native libraries are 32 bit libraries. We do not provide
22259            // this symlink for 64 bit libraries.
22260            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22261                final String nativeLibPath = app.nativeLibraryDir;
22262                try {
22263                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22264                            nativeLibPath, userId);
22265                } catch (InstallerException e) {
22266                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22267                }
22268            }
22269        }
22270    }
22271
22272    /**
22273     * For system apps on non-FBE devices, this method migrates any existing
22274     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22275     * requested by the app.
22276     */
22277    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22278        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22279                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22280            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22281                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22282            try {
22283                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22284                        storageTarget);
22285            } catch (InstallerException e) {
22286                logCriticalInfo(Log.WARN,
22287                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22288            }
22289            return true;
22290        } else {
22291            return false;
22292        }
22293    }
22294
22295    public PackageFreezer freezePackage(String packageName, String killReason) {
22296        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22297    }
22298
22299    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22300        return new PackageFreezer(packageName, userId, killReason);
22301    }
22302
22303    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22304            String killReason) {
22305        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22306    }
22307
22308    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22309            String killReason) {
22310        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22311            return new PackageFreezer();
22312        } else {
22313            return freezePackage(packageName, userId, killReason);
22314        }
22315    }
22316
22317    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22318            String killReason) {
22319        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22320    }
22321
22322    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22323            String killReason) {
22324        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22325            return new PackageFreezer();
22326        } else {
22327            return freezePackage(packageName, userId, killReason);
22328        }
22329    }
22330
22331    /**
22332     * Class that freezes and kills the given package upon creation, and
22333     * unfreezes it upon closing. This is typically used when doing surgery on
22334     * app code/data to prevent the app from running while you're working.
22335     */
22336    private class PackageFreezer implements AutoCloseable {
22337        private final String mPackageName;
22338        private final PackageFreezer[] mChildren;
22339
22340        private final boolean mWeFroze;
22341
22342        private final AtomicBoolean mClosed = new AtomicBoolean();
22343        private final CloseGuard mCloseGuard = CloseGuard.get();
22344
22345        /**
22346         * Create and return a stub freezer that doesn't actually do anything,
22347         * typically used when someone requested
22348         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22349         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22350         */
22351        public PackageFreezer() {
22352            mPackageName = null;
22353            mChildren = null;
22354            mWeFroze = false;
22355            mCloseGuard.open("close");
22356        }
22357
22358        public PackageFreezer(String packageName, int userId, String killReason) {
22359            synchronized (mPackages) {
22360                mPackageName = packageName;
22361                mWeFroze = mFrozenPackages.add(mPackageName);
22362
22363                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22364                if (ps != null) {
22365                    killApplication(ps.name, ps.appId, userId, killReason);
22366                }
22367
22368                final PackageParser.Package p = mPackages.get(packageName);
22369                if (p != null && p.childPackages != null) {
22370                    final int N = p.childPackages.size();
22371                    mChildren = new PackageFreezer[N];
22372                    for (int i = 0; i < N; i++) {
22373                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22374                                userId, killReason);
22375                    }
22376                } else {
22377                    mChildren = null;
22378                }
22379            }
22380            mCloseGuard.open("close");
22381        }
22382
22383        @Override
22384        protected void finalize() throws Throwable {
22385            try {
22386                if (mCloseGuard != null) {
22387                    mCloseGuard.warnIfOpen();
22388                }
22389
22390                close();
22391            } finally {
22392                super.finalize();
22393            }
22394        }
22395
22396        @Override
22397        public void close() {
22398            mCloseGuard.close();
22399            if (mClosed.compareAndSet(false, true)) {
22400                synchronized (mPackages) {
22401                    if (mWeFroze) {
22402                        mFrozenPackages.remove(mPackageName);
22403                    }
22404
22405                    if (mChildren != null) {
22406                        for (PackageFreezer freezer : mChildren) {
22407                            freezer.close();
22408                        }
22409                    }
22410                }
22411            }
22412        }
22413    }
22414
22415    /**
22416     * Verify that given package is currently frozen.
22417     */
22418    private void checkPackageFrozen(String packageName) {
22419        synchronized (mPackages) {
22420            if (!mFrozenPackages.contains(packageName)) {
22421                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22422            }
22423        }
22424    }
22425
22426    @Override
22427    public int movePackage(final String packageName, final String volumeUuid) {
22428        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22429
22430        final int callingUid = Binder.getCallingUid();
22431        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22432        final int moveId = mNextMoveId.getAndIncrement();
22433        mHandler.post(new Runnable() {
22434            @Override
22435            public void run() {
22436                try {
22437                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22438                } catch (PackageManagerException e) {
22439                    Slog.w(TAG, "Failed to move " + packageName, e);
22440                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22441                }
22442            }
22443        });
22444        return moveId;
22445    }
22446
22447    private void movePackageInternal(final String packageName, final String volumeUuid,
22448            final int moveId, final int callingUid, UserHandle user)
22449                    throws PackageManagerException {
22450        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22451        final PackageManager pm = mContext.getPackageManager();
22452
22453        final boolean currentAsec;
22454        final String currentVolumeUuid;
22455        final File codeFile;
22456        final String installerPackageName;
22457        final String packageAbiOverride;
22458        final int appId;
22459        final String seinfo;
22460        final String label;
22461        final int targetSdkVersion;
22462        final PackageFreezer freezer;
22463        final int[] installedUserIds;
22464
22465        // reader
22466        synchronized (mPackages) {
22467            final PackageParser.Package pkg = mPackages.get(packageName);
22468            final PackageSetting ps = mSettings.mPackages.get(packageName);
22469            if (pkg == null
22470                    || ps == null
22471                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22472                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22473            }
22474            if (pkg.applicationInfo.isSystemApp()) {
22475                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22476                        "Cannot move system application");
22477            }
22478
22479            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22480            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22481                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22482            if (isInternalStorage && !allow3rdPartyOnInternal) {
22483                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22484                        "3rd party apps are not allowed on internal storage");
22485            }
22486
22487            if (pkg.applicationInfo.isExternalAsec()) {
22488                currentAsec = true;
22489                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22490            } else if (pkg.applicationInfo.isForwardLocked()) {
22491                currentAsec = true;
22492                currentVolumeUuid = "forward_locked";
22493            } else {
22494                currentAsec = false;
22495                currentVolumeUuid = ps.volumeUuid;
22496
22497                final File probe = new File(pkg.codePath);
22498                final File probeOat = new File(probe, "oat");
22499                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22500                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22501                            "Move only supported for modern cluster style installs");
22502                }
22503            }
22504
22505            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22506                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22507                        "Package already moved to " + volumeUuid);
22508            }
22509            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22510                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22511                        "Device admin cannot be moved");
22512            }
22513
22514            if (mFrozenPackages.contains(packageName)) {
22515                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22516                        "Failed to move already frozen package");
22517            }
22518
22519            codeFile = new File(pkg.codePath);
22520            installerPackageName = ps.installerPackageName;
22521            packageAbiOverride = ps.cpuAbiOverrideString;
22522            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22523            seinfo = pkg.applicationInfo.seInfo;
22524            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22525            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22526            freezer = freezePackage(packageName, "movePackageInternal");
22527            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22528        }
22529
22530        final Bundle extras = new Bundle();
22531        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22532        extras.putString(Intent.EXTRA_TITLE, label);
22533        mMoveCallbacks.notifyCreated(moveId, extras);
22534
22535        int installFlags;
22536        final boolean moveCompleteApp;
22537        final File measurePath;
22538
22539        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22540            installFlags = INSTALL_INTERNAL;
22541            moveCompleteApp = !currentAsec;
22542            measurePath = Environment.getDataAppDirectory(volumeUuid);
22543        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22544            installFlags = INSTALL_EXTERNAL;
22545            moveCompleteApp = false;
22546            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22547        } else {
22548            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22549            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22550                    || !volume.isMountedWritable()) {
22551                freezer.close();
22552                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22553                        "Move location not mounted private volume");
22554            }
22555
22556            Preconditions.checkState(!currentAsec);
22557
22558            installFlags = INSTALL_INTERNAL;
22559            moveCompleteApp = true;
22560            measurePath = Environment.getDataAppDirectory(volumeUuid);
22561        }
22562
22563        // If we're moving app data around, we need all the users unlocked
22564        if (moveCompleteApp) {
22565            for (int userId : installedUserIds) {
22566                if (StorageManager.isFileEncryptedNativeOrEmulated()
22567                        && !StorageManager.isUserKeyUnlocked(userId)) {
22568                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22569                            "User " + userId + " must be unlocked");
22570                }
22571            }
22572        }
22573
22574        final PackageStats stats = new PackageStats(null, -1);
22575        synchronized (mInstaller) {
22576            for (int userId : installedUserIds) {
22577                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22578                    freezer.close();
22579                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22580                            "Failed to measure package size");
22581                }
22582            }
22583        }
22584
22585        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22586                + stats.dataSize);
22587
22588        final long startFreeBytes = measurePath.getUsableSpace();
22589        final long sizeBytes;
22590        if (moveCompleteApp) {
22591            sizeBytes = stats.codeSize + stats.dataSize;
22592        } else {
22593            sizeBytes = stats.codeSize;
22594        }
22595
22596        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22597            freezer.close();
22598            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22599                    "Not enough free space to move");
22600        }
22601
22602        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22603
22604        final CountDownLatch installedLatch = new CountDownLatch(1);
22605        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22606            @Override
22607            public void onUserActionRequired(Intent intent) throws RemoteException {
22608                throw new IllegalStateException();
22609            }
22610
22611            @Override
22612            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22613                    Bundle extras) throws RemoteException {
22614                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22615                        + PackageManager.installStatusToString(returnCode, msg));
22616
22617                installedLatch.countDown();
22618                freezer.close();
22619
22620                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22621                switch (status) {
22622                    case PackageInstaller.STATUS_SUCCESS:
22623                        mMoveCallbacks.notifyStatusChanged(moveId,
22624                                PackageManager.MOVE_SUCCEEDED);
22625                        break;
22626                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22627                        mMoveCallbacks.notifyStatusChanged(moveId,
22628                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22629                        break;
22630                    default:
22631                        mMoveCallbacks.notifyStatusChanged(moveId,
22632                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22633                        break;
22634                }
22635            }
22636        };
22637
22638        final MoveInfo move;
22639        if (moveCompleteApp) {
22640            // Kick off a thread to report progress estimates
22641            new Thread() {
22642                @Override
22643                public void run() {
22644                    while (true) {
22645                        try {
22646                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22647                                break;
22648                            }
22649                        } catch (InterruptedException ignored) {
22650                        }
22651
22652                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22653                        final int progress = 10 + (int) MathUtils.constrain(
22654                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22655                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22656                    }
22657                }
22658            }.start();
22659
22660            final String dataAppName = codeFile.getName();
22661            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22662                    dataAppName, appId, seinfo, targetSdkVersion);
22663        } else {
22664            move = null;
22665        }
22666
22667        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22668
22669        final Message msg = mHandler.obtainMessage(INIT_COPY);
22670        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22671        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22672                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22673                packageAbiOverride, null /*grantedPermissions*/,
22674                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22675        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22676        msg.obj = params;
22677
22678        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22679                System.identityHashCode(msg.obj));
22680        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22681                System.identityHashCode(msg.obj));
22682
22683        mHandler.sendMessage(msg);
22684    }
22685
22686    @Override
22687    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22688        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22689
22690        final int realMoveId = mNextMoveId.getAndIncrement();
22691        final Bundle extras = new Bundle();
22692        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22693        mMoveCallbacks.notifyCreated(realMoveId, extras);
22694
22695        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22696            @Override
22697            public void onCreated(int moveId, Bundle extras) {
22698                // Ignored
22699            }
22700
22701            @Override
22702            public void onStatusChanged(int moveId, int status, long estMillis) {
22703                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22704            }
22705        };
22706
22707        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22708        storage.setPrimaryStorageUuid(volumeUuid, callback);
22709        return realMoveId;
22710    }
22711
22712    @Override
22713    public int getMoveStatus(int moveId) {
22714        mContext.enforceCallingOrSelfPermission(
22715                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22716        return mMoveCallbacks.mLastStatus.get(moveId);
22717    }
22718
22719    @Override
22720    public void registerMoveCallback(IPackageMoveObserver callback) {
22721        mContext.enforceCallingOrSelfPermission(
22722                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22723        mMoveCallbacks.register(callback);
22724    }
22725
22726    @Override
22727    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22728        mContext.enforceCallingOrSelfPermission(
22729                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22730        mMoveCallbacks.unregister(callback);
22731    }
22732
22733    @Override
22734    public boolean setInstallLocation(int loc) {
22735        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22736                null);
22737        if (getInstallLocation() == loc) {
22738            return true;
22739        }
22740        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22741                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22742            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22743                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22744            return true;
22745        }
22746        return false;
22747   }
22748
22749    @Override
22750    public int getInstallLocation() {
22751        // allow instant app access
22752        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22753                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22754                PackageHelper.APP_INSTALL_AUTO);
22755    }
22756
22757    /** Called by UserManagerService */
22758    void cleanUpUser(UserManagerService userManager, int userHandle) {
22759        synchronized (mPackages) {
22760            mDirtyUsers.remove(userHandle);
22761            mUserNeedsBadging.delete(userHandle);
22762            mSettings.removeUserLPw(userHandle);
22763            mPendingBroadcasts.remove(userHandle);
22764            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22765            removeUnusedPackagesLPw(userManager, userHandle);
22766        }
22767    }
22768
22769    /**
22770     * We're removing userHandle and would like to remove any downloaded packages
22771     * that are no longer in use by any other user.
22772     * @param userHandle the user being removed
22773     */
22774    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22775        final boolean DEBUG_CLEAN_APKS = false;
22776        int [] users = userManager.getUserIds();
22777        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22778        while (psit.hasNext()) {
22779            PackageSetting ps = psit.next();
22780            if (ps.pkg == null) {
22781                continue;
22782            }
22783            final String packageName = ps.pkg.packageName;
22784            // Skip over if system app
22785            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22786                continue;
22787            }
22788            if (DEBUG_CLEAN_APKS) {
22789                Slog.i(TAG, "Checking package " + packageName);
22790            }
22791            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22792            if (keep) {
22793                if (DEBUG_CLEAN_APKS) {
22794                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22795                }
22796            } else {
22797                for (int i = 0; i < users.length; i++) {
22798                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22799                        keep = true;
22800                        if (DEBUG_CLEAN_APKS) {
22801                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22802                                    + users[i]);
22803                        }
22804                        break;
22805                    }
22806                }
22807            }
22808            if (!keep) {
22809                if (DEBUG_CLEAN_APKS) {
22810                    Slog.i(TAG, "  Removing package " + packageName);
22811                }
22812                mHandler.post(new Runnable() {
22813                    public void run() {
22814                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22815                                userHandle, 0);
22816                    } //end run
22817                });
22818            }
22819        }
22820    }
22821
22822    /** Called by UserManagerService */
22823    void createNewUser(int userId, String[] disallowedPackages) {
22824        synchronized (mInstallLock) {
22825            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22826        }
22827        synchronized (mPackages) {
22828            scheduleWritePackageRestrictionsLocked(userId);
22829            scheduleWritePackageListLocked(userId);
22830            applyFactoryDefaultBrowserLPw(userId);
22831            primeDomainVerificationsLPw(userId);
22832        }
22833    }
22834
22835    void onNewUserCreated(final int userId) {
22836        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22837        synchronized(mPackages) {
22838            // If permission review for legacy apps is required, we represent
22839            // dagerous permissions for such apps as always granted runtime
22840            // permissions to keep per user flag state whether review is needed.
22841            // Hence, if a new user is added we have to propagate dangerous
22842            // permission grants for these legacy apps.
22843            if (mSettings.mPermissions.mPermissionReviewRequired) {
22844// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22845                mPermissionManager.updateAllPermissions(
22846                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22847                        mPermissionCallback);
22848            }
22849        }
22850    }
22851
22852    @Override
22853    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22854        mContext.enforceCallingOrSelfPermission(
22855                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22856                "Only package verification agents can read the verifier device identity");
22857
22858        synchronized (mPackages) {
22859            return mSettings.getVerifierDeviceIdentityLPw();
22860        }
22861    }
22862
22863    @Override
22864    public void setPermissionEnforced(String permission, boolean enforced) {
22865        // TODO: Now that we no longer change GID for storage, this should to away.
22866        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22867                "setPermissionEnforced");
22868        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22869            synchronized (mPackages) {
22870                if (mSettings.mReadExternalStorageEnforced == null
22871                        || mSettings.mReadExternalStorageEnforced != enforced) {
22872                    mSettings.mReadExternalStorageEnforced =
22873                            enforced ? Boolean.TRUE : Boolean.FALSE;
22874                    mSettings.writeLPr();
22875                }
22876            }
22877            // kill any non-foreground processes so we restart them and
22878            // grant/revoke the GID.
22879            final IActivityManager am = ActivityManager.getService();
22880            if (am != null) {
22881                final long token = Binder.clearCallingIdentity();
22882                try {
22883                    am.killProcessesBelowForeground("setPermissionEnforcement");
22884                } catch (RemoteException e) {
22885                } finally {
22886                    Binder.restoreCallingIdentity(token);
22887                }
22888            }
22889        } else {
22890            throw new IllegalArgumentException("No selective enforcement for " + permission);
22891        }
22892    }
22893
22894    @Override
22895    @Deprecated
22896    public boolean isPermissionEnforced(String permission) {
22897        // allow instant applications
22898        return true;
22899    }
22900
22901    @Override
22902    public boolean isStorageLow() {
22903        // allow instant applications
22904        final long token = Binder.clearCallingIdentity();
22905        try {
22906            final DeviceStorageMonitorInternal
22907                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22908            if (dsm != null) {
22909                return dsm.isMemoryLow();
22910            } else {
22911                return false;
22912            }
22913        } finally {
22914            Binder.restoreCallingIdentity(token);
22915        }
22916    }
22917
22918    @Override
22919    public IPackageInstaller getPackageInstaller() {
22920        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22921            return null;
22922        }
22923        return mInstallerService;
22924    }
22925
22926    @Override
22927    public IArtManager getArtManager() {
22928        return mArtManagerService;
22929    }
22930
22931    private boolean userNeedsBadging(int userId) {
22932        int index = mUserNeedsBadging.indexOfKey(userId);
22933        if (index < 0) {
22934            final UserInfo userInfo;
22935            final long token = Binder.clearCallingIdentity();
22936            try {
22937                userInfo = sUserManager.getUserInfo(userId);
22938            } finally {
22939                Binder.restoreCallingIdentity(token);
22940            }
22941            final boolean b;
22942            if (userInfo != null && userInfo.isManagedProfile()) {
22943                b = true;
22944            } else {
22945                b = false;
22946            }
22947            mUserNeedsBadging.put(userId, b);
22948            return b;
22949        }
22950        return mUserNeedsBadging.valueAt(index);
22951    }
22952
22953    @Override
22954    public KeySet getKeySetByAlias(String packageName, String alias) {
22955        if (packageName == null || alias == null) {
22956            return null;
22957        }
22958        synchronized(mPackages) {
22959            final PackageParser.Package pkg = mPackages.get(packageName);
22960            if (pkg == null) {
22961                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22962                throw new IllegalArgumentException("Unknown package: " + packageName);
22963            }
22964            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22965            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22966                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22967                throw new IllegalArgumentException("Unknown package: " + packageName);
22968            }
22969            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22970            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22971        }
22972    }
22973
22974    @Override
22975    public KeySet getSigningKeySet(String packageName) {
22976        if (packageName == null) {
22977            return null;
22978        }
22979        synchronized(mPackages) {
22980            final int callingUid = Binder.getCallingUid();
22981            final int callingUserId = UserHandle.getUserId(callingUid);
22982            final PackageParser.Package pkg = mPackages.get(packageName);
22983            if (pkg == null) {
22984                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22985                throw new IllegalArgumentException("Unknown package: " + packageName);
22986            }
22987            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22988            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22989                // filter and pretend the package doesn't exist
22990                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22991                        + ", uid:" + callingUid);
22992                throw new IllegalArgumentException("Unknown package: " + packageName);
22993            }
22994            if (pkg.applicationInfo.uid != callingUid
22995                    && Process.SYSTEM_UID != callingUid) {
22996                throw new SecurityException("May not access signing KeySet of other apps.");
22997            }
22998            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22999            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23000        }
23001    }
23002
23003    @Override
23004    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23005        final int callingUid = Binder.getCallingUid();
23006        if (getInstantAppPackageName(callingUid) != null) {
23007            return false;
23008        }
23009        if (packageName == null || ks == null) {
23010            return false;
23011        }
23012        synchronized(mPackages) {
23013            final PackageParser.Package pkg = mPackages.get(packageName);
23014            if (pkg == null
23015                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23016                            UserHandle.getUserId(callingUid))) {
23017                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23018                throw new IllegalArgumentException("Unknown package: " + packageName);
23019            }
23020            IBinder ksh = ks.getToken();
23021            if (ksh instanceof KeySetHandle) {
23022                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23023                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23024            }
23025            return false;
23026        }
23027    }
23028
23029    @Override
23030    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23031        final int callingUid = Binder.getCallingUid();
23032        if (getInstantAppPackageName(callingUid) != null) {
23033            return false;
23034        }
23035        if (packageName == null || ks == null) {
23036            return false;
23037        }
23038        synchronized(mPackages) {
23039            final PackageParser.Package pkg = mPackages.get(packageName);
23040            if (pkg == null
23041                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23042                            UserHandle.getUserId(callingUid))) {
23043                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23044                throw new IllegalArgumentException("Unknown package: " + packageName);
23045            }
23046            IBinder ksh = ks.getToken();
23047            if (ksh instanceof KeySetHandle) {
23048                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23049                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23050            }
23051            return false;
23052        }
23053    }
23054
23055    private void deletePackageIfUnusedLPr(final String packageName) {
23056        PackageSetting ps = mSettings.mPackages.get(packageName);
23057        if (ps == null) {
23058            return;
23059        }
23060        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23061            // TODO Implement atomic delete if package is unused
23062            // It is currently possible that the package will be deleted even if it is installed
23063            // after this method returns.
23064            mHandler.post(new Runnable() {
23065                public void run() {
23066                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23067                            0, PackageManager.DELETE_ALL_USERS);
23068                }
23069            });
23070        }
23071    }
23072
23073    /**
23074     * Check and throw if the given before/after packages would be considered a
23075     * downgrade.
23076     */
23077    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23078            throws PackageManagerException {
23079        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23080            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23081                    "Update version code " + after.versionCode + " is older than current "
23082                    + before.getLongVersionCode());
23083        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23084            if (after.baseRevisionCode < before.baseRevisionCode) {
23085                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23086                        "Update base revision code " + after.baseRevisionCode
23087                        + " is older than current " + before.baseRevisionCode);
23088            }
23089
23090            if (!ArrayUtils.isEmpty(after.splitNames)) {
23091                for (int i = 0; i < after.splitNames.length; i++) {
23092                    final String splitName = after.splitNames[i];
23093                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23094                    if (j != -1) {
23095                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23096                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23097                                    "Update split " + splitName + " revision code "
23098                                    + after.splitRevisionCodes[i] + " is older than current "
23099                                    + before.splitRevisionCodes[j]);
23100                        }
23101                    }
23102                }
23103            }
23104        }
23105    }
23106
23107    private static class MoveCallbacks extends Handler {
23108        private static final int MSG_CREATED = 1;
23109        private static final int MSG_STATUS_CHANGED = 2;
23110
23111        private final RemoteCallbackList<IPackageMoveObserver>
23112                mCallbacks = new RemoteCallbackList<>();
23113
23114        private final SparseIntArray mLastStatus = new SparseIntArray();
23115
23116        public MoveCallbacks(Looper looper) {
23117            super(looper);
23118        }
23119
23120        public void register(IPackageMoveObserver callback) {
23121            mCallbacks.register(callback);
23122        }
23123
23124        public void unregister(IPackageMoveObserver callback) {
23125            mCallbacks.unregister(callback);
23126        }
23127
23128        @Override
23129        public void handleMessage(Message msg) {
23130            final SomeArgs args = (SomeArgs) msg.obj;
23131            final int n = mCallbacks.beginBroadcast();
23132            for (int i = 0; i < n; i++) {
23133                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23134                try {
23135                    invokeCallback(callback, msg.what, args);
23136                } catch (RemoteException ignored) {
23137                }
23138            }
23139            mCallbacks.finishBroadcast();
23140            args.recycle();
23141        }
23142
23143        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23144                throws RemoteException {
23145            switch (what) {
23146                case MSG_CREATED: {
23147                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23148                    break;
23149                }
23150                case MSG_STATUS_CHANGED: {
23151                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23152                    break;
23153                }
23154            }
23155        }
23156
23157        private void notifyCreated(int moveId, Bundle extras) {
23158            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23159
23160            final SomeArgs args = SomeArgs.obtain();
23161            args.argi1 = moveId;
23162            args.arg2 = extras;
23163            obtainMessage(MSG_CREATED, args).sendToTarget();
23164        }
23165
23166        private void notifyStatusChanged(int moveId, int status) {
23167            notifyStatusChanged(moveId, status, -1);
23168        }
23169
23170        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23171            Slog.v(TAG, "Move " + moveId + " status " + status);
23172
23173            final SomeArgs args = SomeArgs.obtain();
23174            args.argi1 = moveId;
23175            args.argi2 = status;
23176            args.arg3 = estMillis;
23177            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23178
23179            synchronized (mLastStatus) {
23180                mLastStatus.put(moveId, status);
23181            }
23182        }
23183    }
23184
23185    private final static class OnPermissionChangeListeners extends Handler {
23186        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23187
23188        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23189                new RemoteCallbackList<>();
23190
23191        public OnPermissionChangeListeners(Looper looper) {
23192            super(looper);
23193        }
23194
23195        @Override
23196        public void handleMessage(Message msg) {
23197            switch (msg.what) {
23198                case MSG_ON_PERMISSIONS_CHANGED: {
23199                    final int uid = msg.arg1;
23200                    handleOnPermissionsChanged(uid);
23201                } break;
23202            }
23203        }
23204
23205        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23206            mPermissionListeners.register(listener);
23207
23208        }
23209
23210        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23211            mPermissionListeners.unregister(listener);
23212        }
23213
23214        public void onPermissionsChanged(int uid) {
23215            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23216                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23217            }
23218        }
23219
23220        private void handleOnPermissionsChanged(int uid) {
23221            final int count = mPermissionListeners.beginBroadcast();
23222            try {
23223                for (int i = 0; i < count; i++) {
23224                    IOnPermissionsChangeListener callback = mPermissionListeners
23225                            .getBroadcastItem(i);
23226                    try {
23227                        callback.onPermissionsChanged(uid);
23228                    } catch (RemoteException e) {
23229                        Log.e(TAG, "Permission listener is dead", e);
23230                    }
23231                }
23232            } finally {
23233                mPermissionListeners.finishBroadcast();
23234            }
23235        }
23236    }
23237
23238    private class PackageManagerNative extends IPackageManagerNative.Stub {
23239        @Override
23240        public String[] getNamesForUids(int[] uids) throws RemoteException {
23241            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23242            // massage results so they can be parsed by the native binder
23243            for (int i = results.length - 1; i >= 0; --i) {
23244                if (results[i] == null) {
23245                    results[i] = "";
23246                }
23247            }
23248            return results;
23249        }
23250
23251        // NB: this differentiates between preloads and sideloads
23252        @Override
23253        public String getInstallerForPackage(String packageName) throws RemoteException {
23254            final String installerName = getInstallerPackageName(packageName);
23255            if (!TextUtils.isEmpty(installerName)) {
23256                return installerName;
23257            }
23258            // differentiate between preload and sideload
23259            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23260            ApplicationInfo appInfo = getApplicationInfo(packageName,
23261                                    /*flags*/ 0,
23262                                    /*userId*/ callingUser);
23263            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23264                return "preload";
23265            }
23266            return "";
23267        }
23268
23269        @Override
23270        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23271            try {
23272                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23273                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23274                if (pInfo != null) {
23275                    return pInfo.getLongVersionCode();
23276                }
23277            } catch (Exception e) {
23278            }
23279            return 0;
23280        }
23281    }
23282
23283    private class PackageManagerInternalImpl extends PackageManagerInternal {
23284        @Override
23285        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23286                int flagValues, int userId) {
23287            PackageManagerService.this.updatePermissionFlags(
23288                    permName, packageName, flagMask, flagValues, userId);
23289        }
23290
23291        @Override
23292        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23293            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23294        }
23295
23296        @Override
23297        public boolean isInstantApp(String packageName, int userId) {
23298            return PackageManagerService.this.isInstantApp(packageName, userId);
23299        }
23300
23301        @Override
23302        public String getInstantAppPackageName(int uid) {
23303            return PackageManagerService.this.getInstantAppPackageName(uid);
23304        }
23305
23306        @Override
23307        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23308            synchronized (mPackages) {
23309                return PackageManagerService.this.filterAppAccessLPr(
23310                        (PackageSetting) pkg.mExtras, callingUid, userId);
23311            }
23312        }
23313
23314        @Override
23315        public PackageParser.Package getPackage(String packageName) {
23316            synchronized (mPackages) {
23317                packageName = resolveInternalPackageNameLPr(
23318                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23319                return mPackages.get(packageName);
23320            }
23321        }
23322
23323        @Override
23324        public PackageList getPackageList(PackageListObserver observer) {
23325            synchronized (mPackages) {
23326                final int N = mPackages.size();
23327                final ArrayList<String> list = new ArrayList<>(N);
23328                for (int i = 0; i < N; i++) {
23329                    list.add(mPackages.keyAt(i));
23330                }
23331                final PackageList packageList = new PackageList(list, observer);
23332                if (observer != null) {
23333                    mPackageListObservers.add(packageList);
23334                }
23335                return packageList;
23336            }
23337        }
23338
23339        @Override
23340        public void removePackageListObserver(PackageListObserver observer) {
23341            synchronized (mPackages) {
23342                mPackageListObservers.remove(observer);
23343            }
23344        }
23345
23346        @Override
23347        public PackageParser.Package getDisabledPackage(String packageName) {
23348            synchronized (mPackages) {
23349                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23350                return (ps != null) ? ps.pkg : null;
23351            }
23352        }
23353
23354        @Override
23355        public String getKnownPackageName(int knownPackage, int userId) {
23356            switch(knownPackage) {
23357                case PackageManagerInternal.PACKAGE_BROWSER:
23358                    return getDefaultBrowserPackageName(userId);
23359                case PackageManagerInternal.PACKAGE_INSTALLER:
23360                    return mRequiredInstallerPackage;
23361                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23362                    return mSetupWizardPackage;
23363                case PackageManagerInternal.PACKAGE_SYSTEM:
23364                    return "android";
23365                case PackageManagerInternal.PACKAGE_VERIFIER:
23366                    return mRequiredVerifierPackage;
23367            }
23368            return null;
23369        }
23370
23371        @Override
23372        public boolean isResolveActivityComponent(ComponentInfo component) {
23373            return mResolveActivity.packageName.equals(component.packageName)
23374                    && mResolveActivity.name.equals(component.name);
23375        }
23376
23377        @Override
23378        public void setLocationPackagesProvider(PackagesProvider provider) {
23379            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23380        }
23381
23382        @Override
23383        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23384            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23385        }
23386
23387        @Override
23388        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23389            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23390        }
23391
23392        @Override
23393        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23394            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23395        }
23396
23397        @Override
23398        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23399            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23400        }
23401
23402        @Override
23403        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23404            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23405        }
23406
23407        @Override
23408        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23409            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23410        }
23411
23412        @Override
23413        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23414            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23415        }
23416
23417        @Override
23418        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23419            synchronized (mPackages) {
23420                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23421            }
23422            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23423        }
23424
23425        @Override
23426        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23427            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23428                    packageName, userId);
23429        }
23430
23431        @Override
23432        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23433            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23434                    packageName, userId);
23435        }
23436
23437        @Override
23438        public void setKeepUninstalledPackages(final List<String> packageList) {
23439            Preconditions.checkNotNull(packageList);
23440            List<String> removedFromList = null;
23441            synchronized (mPackages) {
23442                if (mKeepUninstalledPackages != null) {
23443                    final int packagesCount = mKeepUninstalledPackages.size();
23444                    for (int i = 0; i < packagesCount; i++) {
23445                        String oldPackage = mKeepUninstalledPackages.get(i);
23446                        if (packageList != null && packageList.contains(oldPackage)) {
23447                            continue;
23448                        }
23449                        if (removedFromList == null) {
23450                            removedFromList = new ArrayList<>();
23451                        }
23452                        removedFromList.add(oldPackage);
23453                    }
23454                }
23455                mKeepUninstalledPackages = new ArrayList<>(packageList);
23456                if (removedFromList != null) {
23457                    final int removedCount = removedFromList.size();
23458                    for (int i = 0; i < removedCount; i++) {
23459                        deletePackageIfUnusedLPr(removedFromList.get(i));
23460                    }
23461                }
23462            }
23463        }
23464
23465        @Override
23466        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23467            synchronized (mPackages) {
23468                return mPermissionManager.isPermissionsReviewRequired(
23469                        mPackages.get(packageName), userId);
23470            }
23471        }
23472
23473        @Override
23474        public PackageInfo getPackageInfo(
23475                String packageName, int flags, int filterCallingUid, int userId) {
23476            return PackageManagerService.this
23477                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23478                            flags, filterCallingUid, userId);
23479        }
23480
23481        @Override
23482        public int getPackageUid(String packageName, int flags, int userId) {
23483            return PackageManagerService.this
23484                    .getPackageUid(packageName, flags, userId);
23485        }
23486
23487        @Override
23488        public ApplicationInfo getApplicationInfo(
23489                String packageName, int flags, int filterCallingUid, int userId) {
23490            return PackageManagerService.this
23491                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23492        }
23493
23494        @Override
23495        public ActivityInfo getActivityInfo(
23496                ComponentName component, int flags, int filterCallingUid, int userId) {
23497            return PackageManagerService.this
23498                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23499        }
23500
23501        @Override
23502        public List<ResolveInfo> queryIntentActivities(
23503                Intent intent, int flags, int filterCallingUid, int userId) {
23504            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23505            return PackageManagerService.this
23506                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23507                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23508        }
23509
23510        @Override
23511        public List<ResolveInfo> queryIntentServices(
23512                Intent intent, int flags, int callingUid, int userId) {
23513            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23514            return PackageManagerService.this
23515                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23516                            false);
23517        }
23518
23519        @Override
23520        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23521                int userId) {
23522            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23523        }
23524
23525        @Override
23526        public void setDeviceAndProfileOwnerPackages(
23527                int deviceOwnerUserId, String deviceOwnerPackage,
23528                SparseArray<String> profileOwnerPackages) {
23529            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23530                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23531        }
23532
23533        @Override
23534        public boolean isPackageDataProtected(int userId, String packageName) {
23535            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23536        }
23537
23538        @Override
23539        public boolean isPackageEphemeral(int userId, String packageName) {
23540            synchronized (mPackages) {
23541                final PackageSetting ps = mSettings.mPackages.get(packageName);
23542                return ps != null ? ps.getInstantApp(userId) : false;
23543            }
23544        }
23545
23546        @Override
23547        public boolean wasPackageEverLaunched(String packageName, int userId) {
23548            synchronized (mPackages) {
23549                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23550            }
23551        }
23552
23553        @Override
23554        public void grantRuntimePermission(String packageName, String permName, int userId,
23555                boolean overridePolicy) {
23556            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23557                    permName, packageName, overridePolicy, getCallingUid(), userId,
23558                    mPermissionCallback);
23559        }
23560
23561        @Override
23562        public void revokeRuntimePermission(String packageName, String permName, int userId,
23563                boolean overridePolicy) {
23564            mPermissionManager.revokeRuntimePermission(
23565                    permName, packageName, overridePolicy, getCallingUid(), userId,
23566                    mPermissionCallback);
23567        }
23568
23569        @Override
23570        public String getNameForUid(int uid) {
23571            return PackageManagerService.this.getNameForUid(uid);
23572        }
23573
23574        @Override
23575        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23576                Intent origIntent, String resolvedType, String callingPackage,
23577                Bundle verificationBundle, int userId) {
23578            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23579                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23580                    userId);
23581        }
23582
23583        @Override
23584        public void grantEphemeralAccess(int userId, Intent intent,
23585                int targetAppId, int ephemeralAppId) {
23586            synchronized (mPackages) {
23587                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23588                        targetAppId, ephemeralAppId);
23589            }
23590        }
23591
23592        @Override
23593        public boolean isInstantAppInstallerComponent(ComponentName component) {
23594            synchronized (mPackages) {
23595                return mInstantAppInstallerActivity != null
23596                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23597            }
23598        }
23599
23600        @Override
23601        public void pruneInstantApps() {
23602            mInstantAppRegistry.pruneInstantApps();
23603        }
23604
23605        @Override
23606        public String getSetupWizardPackageName() {
23607            return mSetupWizardPackage;
23608        }
23609
23610        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23611            if (policy != null) {
23612                mExternalSourcesPolicy = policy;
23613            }
23614        }
23615
23616        @Override
23617        public boolean isPackagePersistent(String packageName) {
23618            synchronized (mPackages) {
23619                PackageParser.Package pkg = mPackages.get(packageName);
23620                return pkg != null
23621                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23622                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23623                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23624                        : false;
23625            }
23626        }
23627
23628        @Override
23629        public boolean isLegacySystemApp(Package pkg) {
23630            synchronized (mPackages) {
23631                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23632                return mPromoteSystemApps
23633                        && ps.isSystem()
23634                        && mExistingSystemPackages.contains(ps.name);
23635            }
23636        }
23637
23638        @Override
23639        public List<PackageInfo> getOverlayPackages(int userId) {
23640            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23641            synchronized (mPackages) {
23642                for (PackageParser.Package p : mPackages.values()) {
23643                    if (p.mOverlayTarget != null) {
23644                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23645                        if (pkg != null) {
23646                            overlayPackages.add(pkg);
23647                        }
23648                    }
23649                }
23650            }
23651            return overlayPackages;
23652        }
23653
23654        @Override
23655        public List<String> getTargetPackageNames(int userId) {
23656            List<String> targetPackages = new ArrayList<>();
23657            synchronized (mPackages) {
23658                for (PackageParser.Package p : mPackages.values()) {
23659                    if (p.mOverlayTarget == null) {
23660                        targetPackages.add(p.packageName);
23661                    }
23662                }
23663            }
23664            return targetPackages;
23665        }
23666
23667        @Override
23668        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23669                @Nullable List<String> overlayPackageNames) {
23670            synchronized (mPackages) {
23671                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23672                    Slog.e(TAG, "failed to find package " + targetPackageName);
23673                    return false;
23674                }
23675                ArrayList<String> overlayPaths = null;
23676                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23677                    final int N = overlayPackageNames.size();
23678                    overlayPaths = new ArrayList<>(N);
23679                    for (int i = 0; i < N; i++) {
23680                        final String packageName = overlayPackageNames.get(i);
23681                        final PackageParser.Package pkg = mPackages.get(packageName);
23682                        if (pkg == null) {
23683                            Slog.e(TAG, "failed to find package " + packageName);
23684                            return false;
23685                        }
23686                        overlayPaths.add(pkg.baseCodePath);
23687                    }
23688                }
23689
23690                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23691                ps.setOverlayPaths(overlayPaths, userId);
23692                return true;
23693            }
23694        }
23695
23696        @Override
23697        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23698                int flags, int userId, boolean resolveForStart) {
23699            return resolveIntentInternal(
23700                    intent, resolvedType, flags, userId, resolveForStart);
23701        }
23702
23703        @Override
23704        public ResolveInfo resolveService(Intent intent, String resolvedType,
23705                int flags, int userId, int callingUid) {
23706            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23707        }
23708
23709        @Override
23710        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23711            return PackageManagerService.this.resolveContentProviderInternal(
23712                    name, flags, userId);
23713        }
23714
23715        @Override
23716        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23717            synchronized (mPackages) {
23718                mIsolatedOwners.put(isolatedUid, ownerUid);
23719            }
23720        }
23721
23722        @Override
23723        public void removeIsolatedUid(int isolatedUid) {
23724            synchronized (mPackages) {
23725                mIsolatedOwners.delete(isolatedUid);
23726            }
23727        }
23728
23729        @Override
23730        public int getUidTargetSdkVersion(int uid) {
23731            synchronized (mPackages) {
23732                return getUidTargetSdkVersionLockedLPr(uid);
23733            }
23734        }
23735
23736        @Override
23737        public int getPackageTargetSdkVersion(String packageName) {
23738            synchronized (mPackages) {
23739                return getPackageTargetSdkVersionLockedLPr(packageName);
23740            }
23741        }
23742
23743        @Override
23744        public boolean canAccessInstantApps(int callingUid, int userId) {
23745            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23746        }
23747
23748        @Override
23749        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23750            synchronized (mPackages) {
23751                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23752            }
23753        }
23754
23755        @Override
23756        public void notifyPackageUse(String packageName, int reason) {
23757            synchronized (mPackages) {
23758                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23759            }
23760        }
23761    }
23762
23763    @Override
23764    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23765        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23766        synchronized (mPackages) {
23767            final long identity = Binder.clearCallingIdentity();
23768            try {
23769                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23770                        packageNames, userId);
23771            } finally {
23772                Binder.restoreCallingIdentity(identity);
23773            }
23774        }
23775    }
23776
23777    @Override
23778    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23779        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23780        synchronized (mPackages) {
23781            final long identity = Binder.clearCallingIdentity();
23782            try {
23783                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23784                        packageNames, userId);
23785            } finally {
23786                Binder.restoreCallingIdentity(identity);
23787            }
23788        }
23789    }
23790
23791    private static void enforceSystemOrPhoneCaller(String tag) {
23792        int callingUid = Binder.getCallingUid();
23793        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23794            throw new SecurityException(
23795                    "Cannot call " + tag + " from UID " + callingUid);
23796        }
23797    }
23798
23799    boolean isHistoricalPackageUsageAvailable() {
23800        return mPackageUsage.isHistoricalPackageUsageAvailable();
23801    }
23802
23803    /**
23804     * Return a <b>copy</b> of the collection of packages known to the package manager.
23805     * @return A copy of the values of mPackages.
23806     */
23807    Collection<PackageParser.Package> getPackages() {
23808        synchronized (mPackages) {
23809            return new ArrayList<>(mPackages.values());
23810        }
23811    }
23812
23813    /**
23814     * Logs process start information (including base APK hash) to the security log.
23815     * @hide
23816     */
23817    @Override
23818    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23819            String apkFile, int pid) {
23820        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23821            return;
23822        }
23823        if (!SecurityLog.isLoggingEnabled()) {
23824            return;
23825        }
23826        Bundle data = new Bundle();
23827        data.putLong("startTimestamp", System.currentTimeMillis());
23828        data.putString("processName", processName);
23829        data.putInt("uid", uid);
23830        data.putString("seinfo", seinfo);
23831        data.putString("apkFile", apkFile);
23832        data.putInt("pid", pid);
23833        Message msg = mProcessLoggingHandler.obtainMessage(
23834                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23835        msg.setData(data);
23836        mProcessLoggingHandler.sendMessage(msg);
23837    }
23838
23839    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23840        return mCompilerStats.getPackageStats(pkgName);
23841    }
23842
23843    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23844        return getOrCreateCompilerPackageStats(pkg.packageName);
23845    }
23846
23847    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23848        return mCompilerStats.getOrCreatePackageStats(pkgName);
23849    }
23850
23851    public void deleteCompilerPackageStats(String pkgName) {
23852        mCompilerStats.deletePackageStats(pkgName);
23853    }
23854
23855    @Override
23856    public int getInstallReason(String packageName, int userId) {
23857        final int callingUid = Binder.getCallingUid();
23858        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23859                true /* requireFullPermission */, false /* checkShell */,
23860                "get install reason");
23861        synchronized (mPackages) {
23862            final PackageSetting ps = mSettings.mPackages.get(packageName);
23863            if (filterAppAccessLPr(ps, callingUid, userId)) {
23864                return PackageManager.INSTALL_REASON_UNKNOWN;
23865            }
23866            if (ps != null) {
23867                return ps.getInstallReason(userId);
23868            }
23869        }
23870        return PackageManager.INSTALL_REASON_UNKNOWN;
23871    }
23872
23873    @Override
23874    public boolean canRequestPackageInstalls(String packageName, int userId) {
23875        return canRequestPackageInstallsInternal(packageName, 0, userId,
23876                true /* throwIfPermNotDeclared*/);
23877    }
23878
23879    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23880            boolean throwIfPermNotDeclared) {
23881        int callingUid = Binder.getCallingUid();
23882        int uid = getPackageUid(packageName, 0, userId);
23883        if (callingUid != uid && callingUid != Process.ROOT_UID
23884                && callingUid != Process.SYSTEM_UID) {
23885            throw new SecurityException(
23886                    "Caller uid " + callingUid + " does not own package " + packageName);
23887        }
23888        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23889        if (info == null) {
23890            return false;
23891        }
23892        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23893            return false;
23894        }
23895        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23896        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23897        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23898            if (throwIfPermNotDeclared) {
23899                throw new SecurityException("Need to declare " + appOpPermission
23900                        + " to call this api");
23901            } else {
23902                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23903                return false;
23904            }
23905        }
23906        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23907            return false;
23908        }
23909        if (mExternalSourcesPolicy != null) {
23910            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23911            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23912                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23913            }
23914        }
23915        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23916    }
23917
23918    @Override
23919    public ComponentName getInstantAppResolverSettingsComponent() {
23920        return mInstantAppResolverSettingsComponent;
23921    }
23922
23923    @Override
23924    public ComponentName getInstantAppInstallerComponent() {
23925        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23926            return null;
23927        }
23928        return mInstantAppInstallerActivity == null
23929                ? null : mInstantAppInstallerActivity.getComponentName();
23930    }
23931
23932    @Override
23933    public String getInstantAppAndroidId(String packageName, int userId) {
23934        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23935                "getInstantAppAndroidId");
23936        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23937                true /* requireFullPermission */, false /* checkShell */,
23938                "getInstantAppAndroidId");
23939        // Make sure the target is an Instant App.
23940        if (!isInstantApp(packageName, userId)) {
23941            return null;
23942        }
23943        synchronized (mPackages) {
23944            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23945        }
23946    }
23947
23948    boolean canHaveOatDir(String packageName) {
23949        synchronized (mPackages) {
23950            PackageParser.Package p = mPackages.get(packageName);
23951            if (p == null) {
23952                return false;
23953            }
23954            return p.canHaveOatDir();
23955        }
23956    }
23957
23958    private String getOatDir(PackageParser.Package pkg) {
23959        if (!pkg.canHaveOatDir()) {
23960            return null;
23961        }
23962        File codePath = new File(pkg.codePath);
23963        if (codePath.isDirectory()) {
23964            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23965        }
23966        return null;
23967    }
23968
23969    void deleteOatArtifactsOfPackage(String packageName) {
23970        final String[] instructionSets;
23971        final List<String> codePaths;
23972        final String oatDir;
23973        final PackageParser.Package pkg;
23974        synchronized (mPackages) {
23975            pkg = mPackages.get(packageName);
23976        }
23977        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23978        codePaths = pkg.getAllCodePaths();
23979        oatDir = getOatDir(pkg);
23980
23981        for (String codePath : codePaths) {
23982            for (String isa : instructionSets) {
23983                try {
23984                    mInstaller.deleteOdex(codePath, isa, oatDir);
23985                } catch (InstallerException e) {
23986                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23987                }
23988            }
23989        }
23990    }
23991
23992    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23993        Set<String> unusedPackages = new HashSet<>();
23994        long currentTimeInMillis = System.currentTimeMillis();
23995        synchronized (mPackages) {
23996            for (PackageParser.Package pkg : mPackages.values()) {
23997                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23998                if (ps == null) {
23999                    continue;
24000                }
24001                PackageDexUsage.PackageUseInfo packageUseInfo =
24002                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24003                if (PackageManagerServiceUtils
24004                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24005                                downgradeTimeThresholdMillis, packageUseInfo,
24006                                pkg.getLatestPackageUseTimeInMills(),
24007                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24008                    unusedPackages.add(pkg.packageName);
24009                }
24010            }
24011        }
24012        return unusedPackages;
24013    }
24014
24015    @Override
24016    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24017            int userId) {
24018        final int callingUid = Binder.getCallingUid();
24019        final int callingAppId = UserHandle.getAppId(callingUid);
24020
24021        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24022                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24023
24024        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24025                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24026            throw new SecurityException("Caller must have the "
24027                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24028        }
24029
24030        synchronized(mPackages) {
24031            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24032            scheduleWritePackageRestrictionsLocked(userId);
24033        }
24034    }
24035
24036    @Nullable
24037    @Override
24038    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24039        final int callingUid = Binder.getCallingUid();
24040        final int callingAppId = UserHandle.getAppId(callingUid);
24041
24042        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24043                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24044
24045        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24046                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24047            throw new SecurityException("Caller must have the "
24048                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24049        }
24050
24051        synchronized(mPackages) {
24052            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24053        }
24054    }
24055}
24056
24057interface PackageSender {
24058    /**
24059     * @param userIds User IDs where the action occurred on a full application
24060     * @param instantUserIds User IDs where the action occurred on an instant application
24061     */
24062    void sendPackageBroadcast(final String action, final String pkg,
24063        final Bundle extras, final int flags, final String targetPkg,
24064        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24065    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24066        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24067    void notifyPackageAdded(String packageName);
24068    void notifyPackageRemoved(String packageName);
24069}
24070