PackageManagerService.java revision 662504f941e621e9f871915485cf077aad27628d
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.service.textclassifier.TextClassifierService;
241import android.system.ErrnoException;
242import android.system.Os;
243import android.text.TextUtils;
244import android.text.format.DateUtils;
245import android.util.ArrayMap;
246import android.util.ArraySet;
247import android.util.Base64;
248import android.util.ByteStringUtils;
249import android.util.DisplayMetrics;
250import android.util.EventLog;
251import android.util.ExceptionUtils;
252import android.util.Log;
253import android.util.LogPrinter;
254import android.util.LongSparseArray;
255import android.util.LongSparseLongArray;
256import android.util.MathUtils;
257import android.util.PackageUtils;
258import android.util.Pair;
259import android.util.PrintStreamPrinter;
260import android.util.Slog;
261import android.util.SparseArray;
262import android.util.SparseBooleanArray;
263import android.util.SparseIntArray;
264import android.util.TimingsTraceLog;
265import android.util.Xml;
266import android.util.jar.StrictJarFile;
267import android.util.proto.ProtoOutputStream;
268import android.view.Display;
269
270import com.android.internal.R;
271import com.android.internal.annotations.GuardedBy;
272import com.android.internal.app.IMediaContainerService;
273import com.android.internal.app.ResolverActivity;
274import com.android.internal.content.NativeLibraryHelper;
275import com.android.internal.content.PackageHelper;
276import com.android.internal.logging.MetricsLogger;
277import com.android.internal.os.IParcelFileDescriptorFactory;
278import com.android.internal.os.SomeArgs;
279import com.android.internal.os.Zygote;
280import com.android.internal.telephony.CarrierAppUtils;
281import com.android.internal.util.ArrayUtils;
282import com.android.internal.util.ConcurrentUtils;
283import com.android.internal.util.DumpUtils;
284import com.android.internal.util.FastXmlSerializer;
285import com.android.internal.util.IndentingPrintWriter;
286import com.android.internal.util.Preconditions;
287import com.android.internal.util.XmlUtils;
288import com.android.server.AttributeCache;
289import com.android.server.DeviceIdleController;
290import com.android.server.EventLogTags;
291import com.android.server.FgThread;
292import com.android.server.IntentResolver;
293import com.android.server.LocalServices;
294import com.android.server.LockGuard;
295import com.android.server.ServiceThread;
296import com.android.server.SystemConfig;
297import com.android.server.SystemServerInitThreadPool;
298import com.android.server.Watchdog;
299import com.android.server.net.NetworkPolicyManagerInternal;
300import com.android.server.pm.Installer.InstallerException;
301import com.android.server.pm.Settings.DatabaseVersion;
302import com.android.server.pm.Settings.VersionInfo;
303import com.android.server.pm.dex.ArtManagerService;
304import com.android.server.pm.dex.DexLogger;
305import com.android.server.pm.dex.DexManager;
306import com.android.server.pm.dex.DexoptOptions;
307import com.android.server.pm.dex.PackageDexUsage;
308import com.android.server.pm.permission.BasePermission;
309import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
310import com.android.server.pm.permission.PermissionManagerService;
311import com.android.server.pm.permission.PermissionManagerInternal;
312import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
313import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
314import com.android.server.pm.permission.PermissionsState;
315import com.android.server.pm.permission.PermissionsState.PermissionState;
316import com.android.server.security.VerityUtils;
317import com.android.server.storage.DeviceStorageMonitorInternal;
318
319import dalvik.system.CloseGuard;
320import dalvik.system.VMRuntime;
321
322import libcore.io.IoUtils;
323
324import org.xmlpull.v1.XmlPullParser;
325import org.xmlpull.v1.XmlPullParserException;
326import org.xmlpull.v1.XmlSerializer;
327
328import java.io.BufferedOutputStream;
329import java.io.ByteArrayInputStream;
330import java.io.ByteArrayOutputStream;
331import java.io.File;
332import java.io.FileDescriptor;
333import java.io.FileInputStream;
334import java.io.FileOutputStream;
335import java.io.FilenameFilter;
336import java.io.IOException;
337import java.io.PrintWriter;
338import java.lang.annotation.Retention;
339import java.lang.annotation.RetentionPolicy;
340import java.nio.charset.StandardCharsets;
341import java.security.DigestException;
342import java.security.DigestInputStream;
343import java.security.MessageDigest;
344import java.security.NoSuchAlgorithmException;
345import java.security.PublicKey;
346import java.security.SecureRandom;
347import java.security.cert.CertificateException;
348import java.util.ArrayList;
349import java.util.Arrays;
350import java.util.Collection;
351import java.util.Collections;
352import java.util.Comparator;
353import java.util.HashMap;
354import java.util.HashSet;
355import java.util.Iterator;
356import java.util.LinkedHashSet;
357import java.util.List;
358import java.util.Map;
359import java.util.Objects;
360import java.util.Set;
361import java.util.concurrent.CountDownLatch;
362import java.util.concurrent.Future;
363import java.util.concurrent.TimeUnit;
364import java.util.concurrent.atomic.AtomicBoolean;
365import java.util.concurrent.atomic.AtomicInteger;
366
367/**
368 * Keep track of all those APKs everywhere.
369 * <p>
370 * Internally there are two important locks:
371 * <ul>
372 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
373 * and other related state. It is a fine-grained lock that should only be held
374 * momentarily, as it's one of the most contended locks in the system.
375 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
376 * operations typically involve heavy lifting of application data on disk. Since
377 * {@code installd} is single-threaded, and it's operations can often be slow,
378 * this lock should never be acquired while already holding {@link #mPackages}.
379 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
380 * holding {@link #mInstallLock}.
381 * </ul>
382 * Many internal methods rely on the caller to hold the appropriate locks, and
383 * this contract is expressed through method name suffixes:
384 * <ul>
385 * <li>fooLI(): the caller must hold {@link #mInstallLock}
386 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
387 * being modified must be frozen
388 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
389 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
390 * </ul>
391 * <p>
392 * Because this class is very central to the platform's security; please run all
393 * CTS and unit tests whenever making modifications:
394 *
395 * <pre>
396 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
397 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
398 * </pre>
399 */
400public class PackageManagerService extends IPackageManager.Stub
401        implements PackageSender {
402    static final String TAG = "PackageManager";
403    public static final boolean DEBUG_SETTINGS = false;
404    static final boolean DEBUG_PREFERRED = false;
405    static final boolean DEBUG_UPGRADE = false;
406    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
407    private static final boolean DEBUG_BACKUP = false;
408    public static final boolean DEBUG_INSTALL = false;
409    public static final boolean DEBUG_REMOVE = false;
410    private static final boolean DEBUG_BROADCASTS = false;
411    private static final boolean DEBUG_SHOW_INFO = false;
412    private static final boolean DEBUG_PACKAGE_INFO = false;
413    private static final boolean DEBUG_INTENT_MATCHING = false;
414    public static final boolean DEBUG_PACKAGE_SCANNING = false;
415    private static final boolean DEBUG_VERIFY = false;
416    private static final boolean DEBUG_FILTERS = false;
417    public static final boolean DEBUG_PERMISSIONS = false;
418    private static final boolean DEBUG_SHARED_LIBRARIES = false;
419    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
420
421    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
422    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
423    // user, but by default initialize to this.
424    public static final boolean DEBUG_DEXOPT = false;
425
426    private static final boolean DEBUG_ABI_SELECTION = false;
427    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
428    private static final boolean DEBUG_TRIAGED_MISSING = false;
429    private static final boolean DEBUG_APP_DATA = false;
430
431    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
432    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
433
434    private static final boolean HIDE_EPHEMERAL_APIS = false;
435
436    private static final boolean ENABLE_FREE_CACHE_V2 =
437            SystemProperties.getBoolean("fw.free_cache_v2", true);
438
439    private static final int RADIO_UID = Process.PHONE_UID;
440    private static final int LOG_UID = Process.LOG_UID;
441    private static final int NFC_UID = Process.NFC_UID;
442    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
443    private static final int SHELL_UID = Process.SHELL_UID;
444    private static final int SE_UID = Process.SE_UID;
445
446    // Suffix used during package installation when copying/moving
447    // package apks to install directory.
448    private static final String INSTALL_PACKAGE_SUFFIX = "-";
449
450    static final int SCAN_NO_DEX = 1<<0;
451    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
452    static final int SCAN_NEW_INSTALL = 1<<2;
453    static final int SCAN_UPDATE_TIME = 1<<3;
454    static final int SCAN_BOOTING = 1<<4;
455    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
456    static final int SCAN_REQUIRE_KNOWN = 1<<7;
457    static final int SCAN_MOVE = 1<<8;
458    static final int SCAN_INITIAL = 1<<9;
459    static final int SCAN_CHECK_ONLY = 1<<10;
460    static final int SCAN_DONT_KILL_APP = 1<<11;
461    static final int SCAN_IGNORE_FROZEN = 1<<12;
462    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
463    static final int SCAN_AS_INSTANT_APP = 1<<14;
464    static final int SCAN_AS_FULL_APP = 1<<15;
465    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
466    static final int SCAN_AS_SYSTEM = 1<<17;
467    static final int SCAN_AS_PRIVILEGED = 1<<18;
468    static final int SCAN_AS_OEM = 1<<19;
469    static final int SCAN_AS_VENDOR = 1<<20;
470    static final int SCAN_AS_PRODUCT = 1<<21;
471
472    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
473            SCAN_NO_DEX,
474            SCAN_UPDATE_SIGNATURE,
475            SCAN_NEW_INSTALL,
476            SCAN_UPDATE_TIME,
477            SCAN_BOOTING,
478            SCAN_DELETE_DATA_ON_FAILURES,
479            SCAN_REQUIRE_KNOWN,
480            SCAN_MOVE,
481            SCAN_INITIAL,
482            SCAN_CHECK_ONLY,
483            SCAN_DONT_KILL_APP,
484            SCAN_IGNORE_FROZEN,
485            SCAN_FIRST_BOOT_OR_UPGRADE,
486            SCAN_AS_INSTANT_APP,
487            SCAN_AS_FULL_APP,
488            SCAN_AS_VIRTUAL_PRELOAD,
489    })
490    @Retention(RetentionPolicy.SOURCE)
491    public @interface ScanFlags {}
492
493    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
494    /** Extension of the compressed packages */
495    public final static String COMPRESSED_EXTENSION = ".gz";
496    /** Suffix of stub packages on the system partition */
497    public final static String STUB_SUFFIX = "-Stub";
498
499    private static final int[] EMPTY_INT_ARRAY = new int[0];
500
501    private static final int TYPE_UNKNOWN = 0;
502    private static final int TYPE_ACTIVITY = 1;
503    private static final int TYPE_RECEIVER = 2;
504    private static final int TYPE_SERVICE = 3;
505    private static final int TYPE_PROVIDER = 4;
506    @IntDef(prefix = { "TYPE_" }, value = {
507            TYPE_UNKNOWN,
508            TYPE_ACTIVITY,
509            TYPE_RECEIVER,
510            TYPE_SERVICE,
511            TYPE_PROVIDER,
512    })
513    @Retention(RetentionPolicy.SOURCE)
514    public @interface ComponentType {}
515
516    /**
517     * Timeout (in milliseconds) after which the watchdog should declare that
518     * our handler thread is wedged.  The usual default for such things is one
519     * minute but we sometimes do very lengthy I/O operations on this thread,
520     * such as installing multi-gigabyte applications, so ours needs to be longer.
521     */
522    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
523
524    /**
525     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
526     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
527     * settings entry if available, otherwise we use the hardcoded default.  If it's been
528     * more than this long since the last fstrim, we force one during the boot sequence.
529     *
530     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
531     * one gets run at the next available charging+idle time.  This final mandatory
532     * no-fstrim check kicks in only of the other scheduling criteria is never met.
533     */
534    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
535
536    /**
537     * Whether verification is enabled by default.
538     */
539    private static final boolean DEFAULT_VERIFY_ENABLE = true;
540
541    /**
542     * The default maximum time to wait for the verification agent to return in
543     * milliseconds.
544     */
545    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
546
547    /**
548     * The default response for package verification timeout.
549     *
550     * This can be either PackageManager.VERIFICATION_ALLOW or
551     * PackageManager.VERIFICATION_REJECT.
552     */
553    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
554
555    public static final String PLATFORM_PACKAGE_NAME = "android";
556
557    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
558
559    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
560            DEFAULT_CONTAINER_PACKAGE,
561            "com.android.defcontainer.DefaultContainerService");
562
563    private static final String KILL_APP_REASON_GIDS_CHANGED =
564            "permission grant or revoke changed gids";
565
566    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
567            "permissions revoked";
568
569    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
570
571    private static final String PACKAGE_SCHEME = "package";
572
573    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
574
575    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
576
577    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
578
579    /** Canonical intent used to identify what counts as a "web browser" app */
580    private static final Intent sBrowserIntent;
581    static {
582        sBrowserIntent = new Intent();
583        sBrowserIntent.setAction(Intent.ACTION_VIEW);
584        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
585        sBrowserIntent.setData(Uri.parse("http:"));
586        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
587    }
588
589    /**
590     * The set of all protected actions [i.e. those actions for which a high priority
591     * intent filter is disallowed].
592     */
593    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
594    static {
595        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
596        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
597        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
598        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
599    }
600
601    // Compilation reasons.
602    public static final int REASON_UNKNOWN = -1;
603    public static final int REASON_FIRST_BOOT = 0;
604    public static final int REASON_BOOT = 1;
605    public static final int REASON_INSTALL = 2;
606    public static final int REASON_BACKGROUND_DEXOPT = 3;
607    public static final int REASON_AB_OTA = 4;
608    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
609    public static final int REASON_SHARED = 6;
610
611    public static final int REASON_LAST = REASON_SHARED;
612
613    /**
614     * Version number for the package parser cache. Increment this whenever the format or
615     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
616     */
617    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
618
619    /**
620     * Whether the package parser cache is enabled.
621     */
622    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
623
624    /**
625     * Permissions required in order to receive instant application lifecycle broadcasts.
626     */
627    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
628            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
629
630    final ServiceThread mHandlerThread;
631
632    final PackageHandler mHandler;
633
634    private final ProcessLoggingHandler mProcessLoggingHandler;
635
636    /**
637     * Messages for {@link #mHandler} that need to wait for system ready before
638     * being dispatched.
639     */
640    private ArrayList<Message> mPostSystemReadyMessages;
641
642    final int mSdkVersion = Build.VERSION.SDK_INT;
643
644    final Context mContext;
645    final boolean mFactoryTest;
646    final boolean mOnlyCore;
647    final DisplayMetrics mMetrics;
648    final int mDefParseFlags;
649    final String[] mSeparateProcesses;
650    final boolean mIsUpgrade;
651    final boolean mIsPreNUpgrade;
652    final boolean mIsPreNMR1Upgrade;
653
654    // Have we told the Activity Manager to whitelist the default container service by uid yet?
655    @GuardedBy("mPackages")
656    boolean mDefaultContainerWhitelisted = false;
657
658    @GuardedBy("mPackages")
659    private boolean mDexOptDialogShown;
660
661    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
662    // LOCK HELD.  Can be called with mInstallLock held.
663    @GuardedBy("mInstallLock")
664    final Installer mInstaller;
665
666    /** Directory where installed applications are stored */
667    private static final File sAppInstallDir =
668            new File(Environment.getDataDirectory(), "app");
669    /** Directory where installed application's 32-bit native libraries are copied. */
670    private static final File sAppLib32InstallDir =
671            new File(Environment.getDataDirectory(), "app-lib");
672    /** Directory where code and non-resource assets of forward-locked applications are stored */
673    private static final File sDrmAppPrivateInstallDir =
674            new File(Environment.getDataDirectory(), "app-private");
675
676    // ----------------------------------------------------------------
677
678    // Lock for state used when installing and doing other long running
679    // operations.  Methods that must be called with this lock held have
680    // the suffix "LI".
681    final Object mInstallLock = new Object();
682
683    // ----------------------------------------------------------------
684
685    // Keys are String (package name), values are Package.  This also serves
686    // as the lock for the global state.  Methods that must be called with
687    // this lock held have the prefix "LP".
688    @GuardedBy("mPackages")
689    final ArrayMap<String, PackageParser.Package> mPackages =
690            new ArrayMap<String, PackageParser.Package>();
691
692    final ArrayMap<String, Set<String>> mKnownCodebase =
693            new ArrayMap<String, Set<String>>();
694
695    // Keys are isolated uids and values are the uid of the application
696    // that created the isolated proccess.
697    @GuardedBy("mPackages")
698    final SparseIntArray mIsolatedOwners = new SparseIntArray();
699
700    /**
701     * Tracks new system packages [received in an OTA] that we expect to
702     * find updated user-installed versions. Keys are package name, values
703     * are package location.
704     */
705    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
706    /**
707     * Tracks high priority intent filters for protected actions. During boot, certain
708     * filter actions are protected and should never be allowed to have a high priority
709     * intent filter for them. However, there is one, and only one exception -- the
710     * setup wizard. It must be able to define a high priority intent filter for these
711     * actions to ensure there are no escapes from the wizard. We need to delay processing
712     * of these during boot as we need to look at all of the system packages in order
713     * to know which component is the setup wizard.
714     */
715    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
716    /**
717     * Whether or not processing protected filters should be deferred.
718     */
719    private boolean mDeferProtectedFilters = true;
720
721    /**
722     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
723     */
724    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
725    /**
726     * Whether or not system app permissions should be promoted from install to runtime.
727     */
728    boolean mPromoteSystemApps;
729
730    @GuardedBy("mPackages")
731    final Settings mSettings;
732
733    /**
734     * Set of package names that are currently "frozen", which means active
735     * surgery is being done on the code/data for that package. The platform
736     * will refuse to launch frozen packages to avoid race conditions.
737     *
738     * @see PackageFreezer
739     */
740    @GuardedBy("mPackages")
741    final ArraySet<String> mFrozenPackages = new ArraySet<>();
742
743    final ProtectedPackages mProtectedPackages;
744
745    @GuardedBy("mLoadedVolumes")
746    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
747
748    boolean mFirstBoot;
749
750    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
751
752    @GuardedBy("mAvailableFeatures")
753    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
754
755    private final InstantAppRegistry mInstantAppRegistry;
756
757    @GuardedBy("mPackages")
758    int mChangedPackagesSequenceNumber;
759    /**
760     * List of changed [installed, removed or updated] packages.
761     * mapping from user id -> sequence number -> package name
762     */
763    @GuardedBy("mPackages")
764    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
765    /**
766     * The sequence number of the last change to a package.
767     * mapping from user id -> package name -> sequence number
768     */
769    @GuardedBy("mPackages")
770    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
771
772    @GuardedBy("mPackages")
773    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
774
775    class PackageParserCallback implements PackageParser.Callback {
776        @Override public final boolean hasFeature(String feature) {
777            return PackageManagerService.this.hasSystemFeature(feature, 0);
778        }
779
780        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
781                Collection<PackageParser.Package> allPackages, String targetPackageName) {
782            List<PackageParser.Package> overlayPackages = null;
783            for (PackageParser.Package p : allPackages) {
784                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
785                    if (overlayPackages == null) {
786                        overlayPackages = new ArrayList<PackageParser.Package>();
787                    }
788                    overlayPackages.add(p);
789                }
790            }
791            if (overlayPackages != null) {
792                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
793                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
794                        return p1.mOverlayPriority - p2.mOverlayPriority;
795                    }
796                };
797                Collections.sort(overlayPackages, cmp);
798            }
799            return overlayPackages;
800        }
801
802        @GuardedBy("mInstallLock")
803        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
804                String targetPackageName, String targetPath) {
805            if ("android".equals(targetPackageName)) {
806                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
807                // native AssetManager.
808                return null;
809            }
810            List<PackageParser.Package> overlayPackages =
811                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
812            if (overlayPackages == null || overlayPackages.isEmpty()) {
813                return null;
814            }
815            List<String> overlayPathList = null;
816            for (PackageParser.Package overlayPackage : overlayPackages) {
817                if (targetPath == null) {
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                    continue;
823                }
824
825                try {
826                    // Creates idmaps for system to parse correctly the Android manifest of the
827                    // target package.
828                    //
829                    // OverlayManagerService will update each of them with a correct gid from its
830                    // target package app id.
831                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
832                            UserHandle.getSharedAppGid(
833                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
834                    if (overlayPathList == null) {
835                        overlayPathList = new ArrayList<String>();
836                    }
837                    overlayPathList.add(overlayPackage.baseCodePath);
838                } catch (InstallerException e) {
839                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
840                            overlayPackage.baseCodePath);
841                }
842            }
843            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
844        }
845
846        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
847            synchronized (mPackages) {
848                return getStaticOverlayPathsLocked(
849                        mPackages.values(), targetPackageName, targetPath);
850            }
851        }
852
853        @Override public final String[] getOverlayApks(String targetPackageName) {
854            return getStaticOverlayPaths(targetPackageName, null);
855        }
856
857        @Override public final String[] getOverlayPaths(String targetPackageName,
858                String targetPath) {
859            return getStaticOverlayPaths(targetPackageName, targetPath);
860        }
861    }
862
863    class ParallelPackageParserCallback extends PackageParserCallback {
864        List<PackageParser.Package> mOverlayPackages = null;
865
866        void findStaticOverlayPackages() {
867            synchronized (mPackages) {
868                for (PackageParser.Package p : mPackages.values()) {
869                    if (p.mOverlayIsStatic) {
870                        if (mOverlayPackages == null) {
871                            mOverlayPackages = new ArrayList<PackageParser.Package>();
872                        }
873                        mOverlayPackages.add(p);
874                    }
875                }
876            }
877        }
878
879        @Override
880        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
881            // We can trust mOverlayPackages without holding mPackages because package uninstall
882            // can't happen while running parallel parsing.
883            // Moreover holding mPackages on each parsing thread causes dead-lock.
884            return mOverlayPackages == null ? null :
885                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
886        }
887    }
888
889    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
890    final ParallelPackageParserCallback mParallelPackageParserCallback =
891            new ParallelPackageParserCallback();
892
893    public static final class SharedLibraryEntry {
894        public final @Nullable String path;
895        public final @Nullable String apk;
896        public final @NonNull SharedLibraryInfo info;
897
898        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
899                String declaringPackageName, long declaringPackageVersionCode) {
900            path = _path;
901            apk = _apk;
902            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
903                    declaringPackageName, declaringPackageVersionCode), null);
904        }
905    }
906
907    // Currently known shared libraries.
908    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
909    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
910            new ArrayMap<>();
911
912    // All available activities, for your resolving pleasure.
913    final ActivityIntentResolver mActivities =
914            new ActivityIntentResolver();
915
916    // All available receivers, for your resolving pleasure.
917    final ActivityIntentResolver mReceivers =
918            new ActivityIntentResolver();
919
920    // All available services, for your resolving pleasure.
921    final ServiceIntentResolver mServices = new ServiceIntentResolver();
922
923    // All available providers, for your resolving pleasure.
924    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
925
926    // Mapping from provider base names (first directory in content URI codePath)
927    // to the provider information.
928    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
929            new ArrayMap<String, PackageParser.Provider>();
930
931    // Mapping from instrumentation class names to info about them.
932    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
933            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
934
935    // Packages whose data we have transfered into another package, thus
936    // should no longer exist.
937    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
938
939    // Broadcast actions that are only available to the system.
940    @GuardedBy("mProtectedBroadcasts")
941    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
942
943    /** List of packages waiting for verification. */
944    final SparseArray<PackageVerificationState> mPendingVerification
945            = new SparseArray<PackageVerificationState>();
946
947    final PackageInstallerService mInstallerService;
948
949    final ArtManagerService mArtManagerService;
950
951    private final PackageDexOptimizer mPackageDexOptimizer;
952    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
953    // is used by other apps).
954    private final DexManager mDexManager;
955
956    private AtomicInteger mNextMoveId = new AtomicInteger();
957    private final MoveCallbacks mMoveCallbacks;
958
959    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
960
961    // Cache of users who need badging.
962    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
963
964    /** Token for keys in mPendingVerification. */
965    private int mPendingVerificationToken = 0;
966
967    volatile boolean mSystemReady;
968    volatile boolean mSafeMode;
969    volatile boolean mHasSystemUidErrors;
970    private volatile boolean mWebInstantAppsDisabled;
971
972    ApplicationInfo mAndroidApplication;
973    final ActivityInfo mResolveActivity = new ActivityInfo();
974    final ResolveInfo mResolveInfo = new ResolveInfo();
975    ComponentName mResolveComponentName;
976    PackageParser.Package mPlatformPackage;
977    ComponentName mCustomResolverComponentName;
978
979    boolean mResolverReplaced = false;
980
981    private final @Nullable ComponentName mIntentFilterVerifierComponent;
982    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
983
984    private int mIntentFilterVerificationToken = 0;
985
986    /** The service connection to the ephemeral resolver */
987    final InstantAppResolverConnection mInstantAppResolverConnection;
988    /** Component used to show resolver settings for Instant Apps */
989    final ComponentName mInstantAppResolverSettingsComponent;
990
991    /** Activity used to install instant applications */
992    ActivityInfo mInstantAppInstallerActivity;
993    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
994
995    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
996            = new SparseArray<IntentFilterVerificationState>();
997
998    // TODO remove this and go through mPermissonManager directly
999    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1000    private final PermissionManagerInternal mPermissionManager;
1001
1002    // List of packages names to keep cached, even if they are uninstalled for all users
1003    private List<String> mKeepUninstalledPackages;
1004
1005    private UserManagerInternal mUserManagerInternal;
1006    private ActivityManagerInternal mActivityManagerInternal;
1007
1008    private DeviceIdleController.LocalService mDeviceIdleController;
1009
1010    private File mCacheDir;
1011
1012    private Future<?> mPrepareAppDataFuture;
1013
1014    private static class IFVerificationParams {
1015        PackageParser.Package pkg;
1016        boolean replacing;
1017        int userId;
1018        int verifierUid;
1019
1020        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1021                int _userId, int _verifierUid) {
1022            pkg = _pkg;
1023            replacing = _replacing;
1024            userId = _userId;
1025            replacing = _replacing;
1026            verifierUid = _verifierUid;
1027        }
1028    }
1029
1030    private interface IntentFilterVerifier<T extends IntentFilter> {
1031        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1032                                               T filter, String packageName);
1033        void startVerifications(int userId);
1034        void receiveVerificationResponse(int verificationId);
1035    }
1036
1037    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1038        private Context mContext;
1039        private ComponentName mIntentFilterVerifierComponent;
1040        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1041
1042        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1043            mContext = context;
1044            mIntentFilterVerifierComponent = verifierComponent;
1045        }
1046
1047        private String getDefaultScheme() {
1048            return IntentFilter.SCHEME_HTTPS;
1049        }
1050
1051        @Override
1052        public void startVerifications(int userId) {
1053            // Launch verifications requests
1054            int count = mCurrentIntentFilterVerifications.size();
1055            for (int n=0; n<count; n++) {
1056                int verificationId = mCurrentIntentFilterVerifications.get(n);
1057                final IntentFilterVerificationState ivs =
1058                        mIntentFilterVerificationStates.get(verificationId);
1059
1060                String packageName = ivs.getPackageName();
1061
1062                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1063                final int filterCount = filters.size();
1064                ArraySet<String> domainsSet = new ArraySet<>();
1065                for (int m=0; m<filterCount; m++) {
1066                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1067                    domainsSet.addAll(filter.getHostsList());
1068                }
1069                synchronized (mPackages) {
1070                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1071                            packageName, domainsSet) != null) {
1072                        scheduleWriteSettingsLocked();
1073                    }
1074                }
1075                sendVerificationRequest(verificationId, ivs);
1076            }
1077            mCurrentIntentFilterVerifications.clear();
1078        }
1079
1080        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1081            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1084                    verificationId);
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1087                    getDefaultScheme());
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1090                    ivs.getHostsString());
1091            verificationIntent.putExtra(
1092                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1093                    ivs.getPackageName());
1094            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1095            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1096
1097            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1098            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1099                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1100                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1101
1102            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1103            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1104                    "Sending IntentFilter verification broadcast");
1105        }
1106
1107        public void receiveVerificationResponse(int verificationId) {
1108            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1109
1110            final boolean verified = ivs.isVerified();
1111
1112            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1113            final int count = filters.size();
1114            if (DEBUG_DOMAIN_VERIFICATION) {
1115                Slog.i(TAG, "Received verification response " + verificationId
1116                        + " for " + count + " filters, verified=" + verified);
1117            }
1118            for (int n=0; n<count; n++) {
1119                PackageParser.ActivityIntentInfo filter = filters.get(n);
1120                filter.setVerified(verified);
1121
1122                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1123                        + " verified with result:" + verified + " and hosts:"
1124                        + ivs.getHostsString());
1125            }
1126
1127            mIntentFilterVerificationStates.remove(verificationId);
1128
1129            final String packageName = ivs.getPackageName();
1130            IntentFilterVerificationInfo ivi = null;
1131
1132            synchronized (mPackages) {
1133                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1134            }
1135            if (ivi == null) {
1136                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1137                        + verificationId + " packageName:" + packageName);
1138                return;
1139            }
1140            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1141                    "Updating IntentFilterVerificationInfo for package " + packageName
1142                            +" verificationId:" + verificationId);
1143
1144            synchronized (mPackages) {
1145                if (verified) {
1146                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1147                } else {
1148                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1149                }
1150                scheduleWriteSettingsLocked();
1151
1152                final int userId = ivs.getUserId();
1153                if (userId != UserHandle.USER_ALL) {
1154                    final int userStatus =
1155                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1156
1157                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1158                    boolean needUpdate = false;
1159
1160                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1161                    // already been set by the User thru the Disambiguation dialog
1162                    switch (userStatus) {
1163                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1164                            if (verified) {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1166                            } else {
1167                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1168                            }
1169                            needUpdate = true;
1170                            break;
1171
1172                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1173                            if (verified) {
1174                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1175                                needUpdate = true;
1176                            }
1177                            break;
1178
1179                        default:
1180                            // Nothing to do
1181                    }
1182
1183                    if (needUpdate) {
1184                        mSettings.updateIntentFilterVerificationStatusLPw(
1185                                packageName, updatedStatus, userId);
1186                        scheduleWritePackageRestrictionsLocked(userId);
1187                    }
1188                }
1189            }
1190        }
1191
1192        @Override
1193        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1194                    ActivityIntentInfo filter, String packageName) {
1195            if (!hasValidDomains(filter)) {
1196                return false;
1197            }
1198            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1199            if (ivs == null) {
1200                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1201                        packageName);
1202            }
1203            if (DEBUG_DOMAIN_VERIFICATION) {
1204                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1205            }
1206            ivs.addFilter(filter);
1207            return true;
1208        }
1209
1210        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1211                int userId, int verificationId, String packageName) {
1212            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1213                    verifierUid, userId, packageName);
1214            ivs.setPendingState();
1215            synchronized (mPackages) {
1216                mIntentFilterVerificationStates.append(verificationId, ivs);
1217                mCurrentIntentFilterVerifications.add(verificationId);
1218            }
1219            return ivs;
1220        }
1221    }
1222
1223    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1224        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1225                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1226                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1227    }
1228
1229    // Set of pending broadcasts for aggregating enable/disable of components.
1230    static class PendingPackageBroadcasts {
1231        // for each user id, a map of <package name -> components within that package>
1232        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1233
1234        public PendingPackageBroadcasts() {
1235            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1236        }
1237
1238        public ArrayList<String> get(int userId, String packageName) {
1239            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1240            return packages.get(packageName);
1241        }
1242
1243        public void put(int userId, String packageName, ArrayList<String> components) {
1244            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1245            packages.put(packageName, components);
1246        }
1247
1248        public void remove(int userId, String packageName) {
1249            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1250            if (packages != null) {
1251                packages.remove(packageName);
1252            }
1253        }
1254
1255        public void remove(int userId) {
1256            mUidMap.remove(userId);
1257        }
1258
1259        public int userIdCount() {
1260            return mUidMap.size();
1261        }
1262
1263        public int userIdAt(int n) {
1264            return mUidMap.keyAt(n);
1265        }
1266
1267        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1268            return mUidMap.get(userId);
1269        }
1270
1271        public int size() {
1272            // total number of pending broadcast entries across all userIds
1273            int num = 0;
1274            for (int i = 0; i< mUidMap.size(); i++) {
1275                num += mUidMap.valueAt(i).size();
1276            }
1277            return num;
1278        }
1279
1280        public void clear() {
1281            mUidMap.clear();
1282        }
1283
1284        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1285            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1286            if (map == null) {
1287                map = new ArrayMap<String, ArrayList<String>>();
1288                mUidMap.put(userId, map);
1289            }
1290            return map;
1291        }
1292    }
1293    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1294
1295    // Service Connection to remote media container service to copy
1296    // package uri's from external media onto secure containers
1297    // or internal storage.
1298    private IMediaContainerService mContainerService = null;
1299
1300    static final int SEND_PENDING_BROADCAST = 1;
1301    static final int MCS_BOUND = 3;
1302    static final int END_COPY = 4;
1303    static final int INIT_COPY = 5;
1304    static final int MCS_UNBIND = 6;
1305    static final int START_CLEANING_PACKAGE = 7;
1306    static final int FIND_INSTALL_LOC = 8;
1307    static final int POST_INSTALL = 9;
1308    static final int MCS_RECONNECT = 10;
1309    static final int MCS_GIVE_UP = 11;
1310    static final int WRITE_SETTINGS = 13;
1311    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1312    static final int PACKAGE_VERIFIED = 15;
1313    static final int CHECK_PENDING_VERIFICATION = 16;
1314    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1315    static final int INTENT_FILTER_VERIFIED = 18;
1316    static final int WRITE_PACKAGE_LIST = 19;
1317    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1318
1319    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1320
1321    // Delay time in millisecs
1322    static final int BROADCAST_DELAY = 10 * 1000;
1323
1324    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1325            2 * 60 * 60 * 1000L; /* two hours */
1326
1327    static UserManagerService sUserManager;
1328
1329    // Stores a list of users whose package restrictions file needs to be updated
1330    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1331
1332    final private DefaultContainerConnection mDefContainerConn =
1333            new DefaultContainerConnection();
1334    class DefaultContainerConnection implements ServiceConnection {
1335        public void onServiceConnected(ComponentName name, IBinder service) {
1336            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1337            final IMediaContainerService imcs = IMediaContainerService.Stub
1338                    .asInterface(Binder.allowBlocking(service));
1339            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1340        }
1341
1342        public void onServiceDisconnected(ComponentName name) {
1343            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1344        }
1345    }
1346
1347    // Recordkeeping of restore-after-install operations that are currently in flight
1348    // between the Package Manager and the Backup Manager
1349    static class PostInstallData {
1350        public InstallArgs args;
1351        public PackageInstalledInfo res;
1352
1353        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1354            args = _a;
1355            res = _r;
1356        }
1357    }
1358
1359    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1360    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1361
1362    // XML tags for backup/restore of various bits of state
1363    private static final String TAG_PREFERRED_BACKUP = "pa";
1364    private static final String TAG_DEFAULT_APPS = "da";
1365    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1366
1367    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1368    private static final String TAG_ALL_GRANTS = "rt-grants";
1369    private static final String TAG_GRANT = "grant";
1370    private static final String ATTR_PACKAGE_NAME = "pkg";
1371
1372    private static final String TAG_PERMISSION = "perm";
1373    private static final String ATTR_PERMISSION_NAME = "name";
1374    private static final String ATTR_IS_GRANTED = "g";
1375    private static final String ATTR_USER_SET = "set";
1376    private static final String ATTR_USER_FIXED = "fixed";
1377    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1378
1379    // System/policy permission grants are not backed up
1380    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1381            FLAG_PERMISSION_POLICY_FIXED
1382            | FLAG_PERMISSION_SYSTEM_FIXED
1383            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1384
1385    // And we back up these user-adjusted states
1386    private static final int USER_RUNTIME_GRANT_MASK =
1387            FLAG_PERMISSION_USER_SET
1388            | FLAG_PERMISSION_USER_FIXED
1389            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1390
1391    final @Nullable String mRequiredVerifierPackage;
1392    final @NonNull String mRequiredInstallerPackage;
1393    final @NonNull String mRequiredUninstallerPackage;
1394    final @Nullable String mSetupWizardPackage;
1395    final @Nullable String mStorageManagerPackage;
1396    final @Nullable String mSystemTextClassifierPackage;
1397    final @NonNull String mServicesSystemSharedLibraryPackageName;
1398    final @NonNull String mSharedSystemSharedLibraryPackageName;
1399
1400    private final PackageUsage mPackageUsage = new PackageUsage();
1401    private final CompilerStats mCompilerStats = new CompilerStats();
1402
1403    class PackageHandler extends Handler {
1404        private boolean mBound = false;
1405        final ArrayList<HandlerParams> mPendingInstalls =
1406            new ArrayList<HandlerParams>();
1407
1408        private boolean connectToService() {
1409            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1410                    " DefaultContainerService");
1411            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1412            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1413            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1414                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1415                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416                mBound = true;
1417                return true;
1418            }
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1420            return false;
1421        }
1422
1423        private void disconnectService() {
1424            mContainerService = null;
1425            mBound = false;
1426            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1427            mContext.unbindService(mDefContainerConn);
1428            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429        }
1430
1431        PackageHandler(Looper looper) {
1432            super(looper);
1433        }
1434
1435        public void handleMessage(Message msg) {
1436            try {
1437                doHandleMessage(msg);
1438            } finally {
1439                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1440            }
1441        }
1442
1443        void doHandleMessage(Message msg) {
1444            switch (msg.what) {
1445                case INIT_COPY: {
1446                    HandlerParams params = (HandlerParams) msg.obj;
1447                    int idx = mPendingInstalls.size();
1448                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1449                    // If a bind was already initiated we dont really
1450                    // need to do anything. The pending install
1451                    // will be processed later on.
1452                    if (!mBound) {
1453                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1454                                System.identityHashCode(mHandler));
1455                        // If this is the only one pending we might
1456                        // have to bind to the service again.
1457                        if (!connectToService()) {
1458                            Slog.e(TAG, "Failed to bind to media container service");
1459                            params.serviceError();
1460                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1461                                    System.identityHashCode(mHandler));
1462                            if (params.traceMethod != null) {
1463                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1464                                        params.traceCookie);
1465                            }
1466                            return;
1467                        } else {
1468                            // Once we bind to the service, the first
1469                            // pending request will be processed.
1470                            mPendingInstalls.add(idx, params);
1471                        }
1472                    } else {
1473                        mPendingInstalls.add(idx, params);
1474                        // Already bound to the service. Just make
1475                        // sure we trigger off processing the first request.
1476                        if (idx == 0) {
1477                            mHandler.sendEmptyMessage(MCS_BOUND);
1478                        }
1479                    }
1480                    break;
1481                }
1482                case MCS_BOUND: {
1483                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1484                    if (msg.obj != null) {
1485                        mContainerService = (IMediaContainerService) msg.obj;
1486                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1487                                System.identityHashCode(mHandler));
1488                    }
1489                    if (mContainerService == null) {
1490                        if (!mBound) {
1491                            // Something seriously wrong since we are not bound and we are not
1492                            // waiting for connection. Bail out.
1493                            Slog.e(TAG, "Cannot bind to media container service");
1494                            for (HandlerParams params : mPendingInstalls) {
1495                                // Indicate service bind error
1496                                params.serviceError();
1497                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1498                                        System.identityHashCode(params));
1499                                if (params.traceMethod != null) {
1500                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1501                                            params.traceMethod, params.traceCookie);
1502                                }
1503                                return;
1504                            }
1505                            mPendingInstalls.clear();
1506                        } else {
1507                            Slog.w(TAG, "Waiting to connect to media container service");
1508                        }
1509                    } else if (mPendingInstalls.size() > 0) {
1510                        HandlerParams params = mPendingInstalls.get(0);
1511                        if (params != null) {
1512                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1513                                    System.identityHashCode(params));
1514                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1515                            if (params.startCopy()) {
1516                                // We are done...  look for more work or to
1517                                // go idle.
1518                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1519                                        "Checking for more work or unbind...");
1520                                // Delete pending install
1521                                if (mPendingInstalls.size() > 0) {
1522                                    mPendingInstalls.remove(0);
1523                                }
1524                                if (mPendingInstalls.size() == 0) {
1525                                    if (mBound) {
1526                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1527                                                "Posting delayed MCS_UNBIND");
1528                                        removeMessages(MCS_UNBIND);
1529                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1530                                        // Unbind after a little delay, to avoid
1531                                        // continual thrashing.
1532                                        sendMessageDelayed(ubmsg, 10000);
1533                                    }
1534                                } else {
1535                                    // There are more pending requests in queue.
1536                                    // Just post MCS_BOUND message to trigger processing
1537                                    // of next pending install.
1538                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1539                                            "Posting MCS_BOUND for next work");
1540                                    mHandler.sendEmptyMessage(MCS_BOUND);
1541                                }
1542                            }
1543                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1544                        }
1545                    } else {
1546                        // Should never happen ideally.
1547                        Slog.w(TAG, "Empty queue");
1548                    }
1549                    break;
1550                }
1551                case MCS_RECONNECT: {
1552                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1553                    if (mPendingInstalls.size() > 0) {
1554                        if (mBound) {
1555                            disconnectService();
1556                        }
1557                        if (!connectToService()) {
1558                            Slog.e(TAG, "Failed to bind to media container service");
1559                            for (HandlerParams params : mPendingInstalls) {
1560                                // Indicate service bind error
1561                                params.serviceError();
1562                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1563                                        System.identityHashCode(params));
1564                            }
1565                            mPendingInstalls.clear();
1566                        }
1567                    }
1568                    break;
1569                }
1570                case MCS_UNBIND: {
1571                    // If there is no actual work left, then time to unbind.
1572                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1573
1574                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1575                        if (mBound) {
1576                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1577
1578                            disconnectService();
1579                        }
1580                    } else if (mPendingInstalls.size() > 0) {
1581                        // There are more pending requests in queue.
1582                        // Just post MCS_BOUND message to trigger processing
1583                        // of next pending install.
1584                        mHandler.sendEmptyMessage(MCS_BOUND);
1585                    }
1586
1587                    break;
1588                }
1589                case MCS_GIVE_UP: {
1590                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1591                    HandlerParams params = mPendingInstalls.remove(0);
1592                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1593                            System.identityHashCode(params));
1594                    break;
1595                }
1596                case SEND_PENDING_BROADCAST: {
1597                    String packages[];
1598                    ArrayList<String> components[];
1599                    int size = 0;
1600                    int uids[];
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1602                    synchronized (mPackages) {
1603                        if (mPendingBroadcasts == null) {
1604                            return;
1605                        }
1606                        size = mPendingBroadcasts.size();
1607                        if (size <= 0) {
1608                            // Nothing to be done. Just return
1609                            return;
1610                        }
1611                        packages = new String[size];
1612                        components = new ArrayList[size];
1613                        uids = new int[size];
1614                        int i = 0;  // filling out the above arrays
1615
1616                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1617                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1618                            Iterator<Map.Entry<String, ArrayList<String>>> it
1619                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1620                                            .entrySet().iterator();
1621                            while (it.hasNext() && i < size) {
1622                                Map.Entry<String, ArrayList<String>> ent = it.next();
1623                                packages[i] = ent.getKey();
1624                                components[i] = ent.getValue();
1625                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1626                                uids[i] = (ps != null)
1627                                        ? UserHandle.getUid(packageUserId, ps.appId)
1628                                        : -1;
1629                                i++;
1630                            }
1631                        }
1632                        size = i;
1633                        mPendingBroadcasts.clear();
1634                    }
1635                    // Send broadcasts
1636                    for (int i = 0; i < size; i++) {
1637                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1638                    }
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1640                    break;
1641                }
1642                case START_CLEANING_PACKAGE: {
1643                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1644                    final String packageName = (String)msg.obj;
1645                    final int userId = msg.arg1;
1646                    final boolean andCode = msg.arg2 != 0;
1647                    synchronized (mPackages) {
1648                        if (userId == UserHandle.USER_ALL) {
1649                            int[] users = sUserManager.getUserIds();
1650                            for (int user : users) {
1651                                mSettings.addPackageToCleanLPw(
1652                                        new PackageCleanItem(user, packageName, andCode));
1653                            }
1654                        } else {
1655                            mSettings.addPackageToCleanLPw(
1656                                    new PackageCleanItem(userId, packageName, andCode));
1657                        }
1658                    }
1659                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1660                    startCleaningPackages();
1661                } break;
1662                case POST_INSTALL: {
1663                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1664
1665                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1666                    final boolean didRestore = (msg.arg2 != 0);
1667                    mRunningInstalls.delete(msg.arg1);
1668
1669                    if (data != null) {
1670                        InstallArgs args = data.args;
1671                        PackageInstalledInfo parentRes = data.res;
1672
1673                        final boolean grantPermissions = (args.installFlags
1674                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1675                        final boolean killApp = (args.installFlags
1676                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1677                        final boolean virtualPreload = ((args.installFlags
1678                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1679                        final String[] grantedPermissions = args.installGrantPermissions;
1680
1681                        // Handle the parent package
1682                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1683                                virtualPreload, grantedPermissions, didRestore,
1684                                args.installerPackageName, args.observer);
1685
1686                        // Handle the child packages
1687                        final int childCount = (parentRes.addedChildPackages != null)
1688                                ? parentRes.addedChildPackages.size() : 0;
1689                        for (int i = 0; i < childCount; i++) {
1690                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1691                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1692                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1693                                    args.installerPackageName, args.observer);
1694                        }
1695
1696                        // Log tracing if needed
1697                        if (args.traceMethod != null) {
1698                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1699                                    args.traceCookie);
1700                        }
1701                    } else {
1702                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1703                    }
1704
1705                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1706                } break;
1707                case WRITE_SETTINGS: {
1708                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1709                    synchronized (mPackages) {
1710                        removeMessages(WRITE_SETTINGS);
1711                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1712                        mSettings.writeLPr();
1713                        mDirtyUsers.clear();
1714                    }
1715                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1716                } break;
1717                case WRITE_PACKAGE_RESTRICTIONS: {
1718                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1719                    synchronized (mPackages) {
1720                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1721                        for (int userId : mDirtyUsers) {
1722                            mSettings.writePackageRestrictionsLPr(userId);
1723                        }
1724                        mDirtyUsers.clear();
1725                    }
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1727                } break;
1728                case WRITE_PACKAGE_LIST: {
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1730                    synchronized (mPackages) {
1731                        removeMessages(WRITE_PACKAGE_LIST);
1732                        mSettings.writePackageListLPr(msg.arg1);
1733                    }
1734                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1735                } break;
1736                case CHECK_PENDING_VERIFICATION: {
1737                    final int verificationId = msg.arg1;
1738                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1739
1740                    if ((state != null) && !state.timeoutExtended()) {
1741                        final InstallArgs args = state.getInstallArgs();
1742                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1743
1744                        Slog.i(TAG, "Verification timed out for " + originUri);
1745                        mPendingVerification.remove(verificationId);
1746
1747                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1748
1749                        final UserHandle user = args.getUser();
1750                        if (getDefaultVerificationResponse(user)
1751                                == PackageManager.VERIFICATION_ALLOW) {
1752                            Slog.i(TAG, "Continuing with installation of " + originUri);
1753                            state.setVerifierResponse(Binder.getCallingUid(),
1754                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1755                            broadcastPackageVerified(verificationId, originUri,
1756                                    PackageManager.VERIFICATION_ALLOW, user);
1757                            try {
1758                                ret = args.copyApk(mContainerService, true);
1759                            } catch (RemoteException e) {
1760                                Slog.e(TAG, "Could not contact the ContainerService");
1761                            }
1762                        } else {
1763                            broadcastPackageVerified(verificationId, originUri,
1764                                    PackageManager.VERIFICATION_REJECT, user);
1765                        }
1766
1767                        Trace.asyncTraceEnd(
1768                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1769
1770                        processPendingInstall(args, ret);
1771                        mHandler.sendEmptyMessage(MCS_UNBIND);
1772                    }
1773                    break;
1774                }
1775                case PACKAGE_VERIFIED: {
1776                    final int verificationId = msg.arg1;
1777
1778                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1779                    if (state == null) {
1780                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1781                        break;
1782                    }
1783
1784                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1785
1786                    state.setVerifierResponse(response.callerUid, response.code);
1787
1788                    if (state.isVerificationComplete()) {
1789                        mPendingVerification.remove(verificationId);
1790
1791                        final InstallArgs args = state.getInstallArgs();
1792                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1793
1794                        int ret;
1795                        if (state.isInstallAllowed()) {
1796                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1797                            broadcastPackageVerified(verificationId, originUri,
1798                                    response.code, state.getInstallArgs().getUser());
1799                            try {
1800                                ret = args.copyApk(mContainerService, true);
1801                            } catch (RemoteException e) {
1802                                Slog.e(TAG, "Could not contact the ContainerService");
1803                            }
1804                        } else {
1805                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1806                        }
1807
1808                        Trace.asyncTraceEnd(
1809                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1810
1811                        processPendingInstall(args, ret);
1812                        mHandler.sendEmptyMessage(MCS_UNBIND);
1813                    }
1814
1815                    break;
1816                }
1817                case START_INTENT_FILTER_VERIFICATIONS: {
1818                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1819                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1820                            params.replacing, params.pkg);
1821                    break;
1822                }
1823                case INTENT_FILTER_VERIFIED: {
1824                    final int verificationId = msg.arg1;
1825
1826                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1827                            verificationId);
1828                    if (state == null) {
1829                        Slog.w(TAG, "Invalid IntentFilter verification token "
1830                                + verificationId + " received");
1831                        break;
1832                    }
1833
1834                    final int userId = state.getUserId();
1835
1836                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1837                            "Processing IntentFilter verification with token:"
1838                            + verificationId + " and userId:" + userId);
1839
1840                    final IntentFilterVerificationResponse response =
1841                            (IntentFilterVerificationResponse) msg.obj;
1842
1843                    state.setVerifierResponse(response.callerUid, response.code);
1844
1845                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1846                            "IntentFilter verification with token:" + verificationId
1847                            + " and userId:" + userId
1848                            + " is settings verifier response with response code:"
1849                            + response.code);
1850
1851                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1852                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1853                                + response.getFailedDomainsString());
1854                    }
1855
1856                    if (state.isVerificationComplete()) {
1857                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1858                    } else {
1859                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1860                                "IntentFilter verification with token:" + verificationId
1861                                + " was not said to be complete");
1862                    }
1863
1864                    break;
1865                }
1866                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1867                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1868                            mInstantAppResolverConnection,
1869                            (InstantAppRequest) msg.obj,
1870                            mInstantAppInstallerActivity,
1871                            mHandler);
1872                }
1873            }
1874        }
1875    }
1876
1877    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1878        @Override
1879        public void onGidsChanged(int appId, int userId) {
1880            mHandler.post(new Runnable() {
1881                @Override
1882                public void run() {
1883                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1884                }
1885            });
1886        }
1887        @Override
1888        public void onPermissionGranted(int uid, int userId) {
1889            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1890
1891            // Not critical; if this is lost, the application has to request again.
1892            synchronized (mPackages) {
1893                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1894            }
1895        }
1896        @Override
1897        public void onInstallPermissionGranted() {
1898            synchronized (mPackages) {
1899                scheduleWriteSettingsLocked();
1900            }
1901        }
1902        @Override
1903        public void onPermissionRevoked(int uid, int userId) {
1904            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1905
1906            synchronized (mPackages) {
1907                // Critical; after this call the application should never have the permission
1908                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1909            }
1910
1911            final int appId = UserHandle.getAppId(uid);
1912            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1913        }
1914        @Override
1915        public void onInstallPermissionRevoked() {
1916            synchronized (mPackages) {
1917                scheduleWriteSettingsLocked();
1918            }
1919        }
1920        @Override
1921        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1922            synchronized (mPackages) {
1923                for (int userId : updatedUserIds) {
1924                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1925                }
1926            }
1927        }
1928        @Override
1929        public void onInstallPermissionUpdated() {
1930            synchronized (mPackages) {
1931                scheduleWriteSettingsLocked();
1932            }
1933        }
1934        @Override
1935        public void onPermissionRemoved() {
1936            synchronized (mPackages) {
1937                mSettings.writeLPr();
1938            }
1939        }
1940    };
1941
1942    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1943            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1944            boolean launchedForRestore, String installerPackage,
1945            IPackageInstallObserver2 installObserver) {
1946        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1947            // Send the removed broadcasts
1948            if (res.removedInfo != null) {
1949                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1950            }
1951
1952            // Now that we successfully installed the package, grant runtime
1953            // permissions if requested before broadcasting the install. Also
1954            // for legacy apps in permission review mode we clear the permission
1955            // review flag which is used to emulate runtime permissions for
1956            // legacy apps.
1957            if (grantPermissions) {
1958                final int callingUid = Binder.getCallingUid();
1959                mPermissionManager.grantRequestedRuntimePermissions(
1960                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1961                        mPermissionCallback);
1962            }
1963
1964            final boolean update = res.removedInfo != null
1965                    && res.removedInfo.removedPackage != null;
1966            final String installerPackageName =
1967                    res.installerPackageName != null
1968                            ? res.installerPackageName
1969                            : res.removedInfo != null
1970                                    ? res.removedInfo.installerPackageName
1971                                    : null;
1972
1973            // If this is the first time we have child packages for a disabled privileged
1974            // app that had no children, we grant requested runtime permissions to the new
1975            // children if the parent on the system image had them already granted.
1976            if (res.pkg.parentPackage != null) {
1977                final int callingUid = Binder.getCallingUid();
1978                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1979                        res.pkg, callingUid, mPermissionCallback);
1980            }
1981
1982            synchronized (mPackages) {
1983                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1984            }
1985
1986            final String packageName = res.pkg.applicationInfo.packageName;
1987
1988            // Determine the set of users who are adding this package for
1989            // the first time vs. those who are seeing an update.
1990            int[] firstUserIds = EMPTY_INT_ARRAY;
1991            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1992            int[] updateUserIds = EMPTY_INT_ARRAY;
1993            int[] instantUserIds = EMPTY_INT_ARRAY;
1994            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1995            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1996            for (int newUser : res.newUsers) {
1997                final boolean isInstantApp = ps.getInstantApp(newUser);
1998                if (allNewUsers) {
1999                    if (isInstantApp) {
2000                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2001                    } else {
2002                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2003                    }
2004                    continue;
2005                }
2006                boolean isNew = true;
2007                for (int origUser : res.origUsers) {
2008                    if (origUser == newUser) {
2009                        isNew = false;
2010                        break;
2011                    }
2012                }
2013                if (isNew) {
2014                    if (isInstantApp) {
2015                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2016                    } else {
2017                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2018                    }
2019                } else {
2020                    if (isInstantApp) {
2021                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2022                    } else {
2023                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2024                    }
2025                }
2026            }
2027
2028            // Send installed broadcasts if the package is not a static shared lib.
2029            if (res.pkg.staticSharedLibName == null) {
2030                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2031
2032                // Send added for users that see the package for the first time
2033                // sendPackageAddedForNewUsers also deals with system apps
2034                int appId = UserHandle.getAppId(res.uid);
2035                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2036                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2037                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2038
2039                // Send added for users that don't see the package for the first time
2040                Bundle extras = new Bundle(1);
2041                extras.putInt(Intent.EXTRA_UID, res.uid);
2042                if (update) {
2043                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2044                }
2045                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2046                        extras, 0 /*flags*/,
2047                        null /*targetPackage*/, null /*finishedReceiver*/,
2048                        updateUserIds, instantUserIds);
2049                if (installerPackageName != null) {
2050                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2051                            extras, 0 /*flags*/,
2052                            installerPackageName, null /*finishedReceiver*/,
2053                            updateUserIds, instantUserIds);
2054                }
2055
2056                // Send replaced for users that don't see the package for the first time
2057                if (update) {
2058                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2059                            packageName, extras, 0 /*flags*/,
2060                            null /*targetPackage*/, null /*finishedReceiver*/,
2061                            updateUserIds, instantUserIds);
2062                    if (installerPackageName != null) {
2063                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2064                                extras, 0 /*flags*/,
2065                                installerPackageName, null /*finishedReceiver*/,
2066                                updateUserIds, instantUserIds);
2067                    }
2068                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2069                            null /*package*/, null /*extras*/, 0 /*flags*/,
2070                            packageName /*targetPackage*/,
2071                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2072                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2073                    // First-install and we did a restore, so we're responsible for the
2074                    // first-launch broadcast.
2075                    if (DEBUG_BACKUP) {
2076                        Slog.i(TAG, "Post-restore of " + packageName
2077                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2078                    }
2079                    sendFirstLaunchBroadcast(packageName, installerPackage,
2080                            firstUserIds, firstInstantUserIds);
2081                }
2082
2083                // Send broadcast package appeared if forward locked/external for all users
2084                // treat asec-hosted packages like removable media on upgrade
2085                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2086                    if (DEBUG_INSTALL) {
2087                        Slog.i(TAG, "upgrading pkg " + res.pkg
2088                                + " is ASEC-hosted -> AVAILABLE");
2089                    }
2090                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2091                    ArrayList<String> pkgList = new ArrayList<>(1);
2092                    pkgList.add(packageName);
2093                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2094                }
2095            }
2096
2097            // Work that needs to happen on first install within each user
2098            if (firstUserIds != null && firstUserIds.length > 0) {
2099                synchronized (mPackages) {
2100                    for (int userId : firstUserIds) {
2101                        // If this app is a browser and it's newly-installed for some
2102                        // users, clear any default-browser state in those users. The
2103                        // app's nature doesn't depend on the user, so we can just check
2104                        // its browser nature in any user and generalize.
2105                        if (packageIsBrowser(packageName, userId)) {
2106                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2107                        }
2108
2109                        // We may also need to apply pending (restored) runtime
2110                        // permission grants within these users.
2111                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2112                    }
2113                }
2114            }
2115
2116            if (allNewUsers && !update) {
2117                notifyPackageAdded(packageName);
2118            }
2119
2120            // Log current value of "unknown sources" setting
2121            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2122                    getUnknownSourcesSettings());
2123
2124            // Remove the replaced package's older resources safely now
2125            // We delete after a gc for applications  on sdcard.
2126            if (res.removedInfo != null && res.removedInfo.args != null) {
2127                Runtime.getRuntime().gc();
2128                synchronized (mInstallLock) {
2129                    res.removedInfo.args.doPostDeleteLI(true);
2130                }
2131            } else {
2132                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2133                // and not block here.
2134                VMRuntime.getRuntime().requestConcurrentGC();
2135            }
2136
2137            // Notify DexManager that the package was installed for new users.
2138            // The updated users should already be indexed and the package code paths
2139            // should not change.
2140            // Don't notify the manager for ephemeral apps as they are not expected to
2141            // survive long enough to benefit of background optimizations.
2142            for (int userId : firstUserIds) {
2143                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2144                // There's a race currently where some install events may interleave with an uninstall.
2145                // This can lead to package info being null (b/36642664).
2146                if (info != null) {
2147                    mDexManager.notifyPackageInstalled(info, userId);
2148                }
2149            }
2150        }
2151
2152        // If someone is watching installs - notify them
2153        if (installObserver != null) {
2154            try {
2155                Bundle extras = extrasForInstallResult(res);
2156                installObserver.onPackageInstalled(res.name, res.returnCode,
2157                        res.returnMsg, extras);
2158            } catch (RemoteException e) {
2159                Slog.i(TAG, "Observer no longer exists.");
2160            }
2161        }
2162    }
2163
2164    private StorageEventListener mStorageListener = new StorageEventListener() {
2165        @Override
2166        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2167            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2168                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2169                    final String volumeUuid = vol.getFsUuid();
2170
2171                    // Clean up any users or apps that were removed or recreated
2172                    // while this volume was missing
2173                    sUserManager.reconcileUsers(volumeUuid);
2174                    reconcileApps(volumeUuid);
2175
2176                    // Clean up any install sessions that expired or were
2177                    // cancelled while this volume was missing
2178                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2179
2180                    loadPrivatePackages(vol);
2181
2182                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2183                    unloadPrivatePackages(vol);
2184                }
2185            }
2186        }
2187
2188        @Override
2189        public void onVolumeForgotten(String fsUuid) {
2190            if (TextUtils.isEmpty(fsUuid)) {
2191                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2192                return;
2193            }
2194
2195            // Remove any apps installed on the forgotten volume
2196            synchronized (mPackages) {
2197                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2198                for (PackageSetting ps : packages) {
2199                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2200                    deletePackageVersioned(new VersionedPackage(ps.name,
2201                            PackageManager.VERSION_CODE_HIGHEST),
2202                            new LegacyPackageDeleteObserver(null).getBinder(),
2203                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2204                    // Try very hard to release any references to this package
2205                    // so we don't risk the system server being killed due to
2206                    // open FDs
2207                    AttributeCache.instance().removePackage(ps.name);
2208                }
2209
2210                mSettings.onVolumeForgotten(fsUuid);
2211                mSettings.writeLPr();
2212            }
2213        }
2214    };
2215
2216    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2217        Bundle extras = null;
2218        switch (res.returnCode) {
2219            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2220                extras = new Bundle();
2221                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2222                        res.origPermission);
2223                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2224                        res.origPackage);
2225                break;
2226            }
2227            case PackageManager.INSTALL_SUCCEEDED: {
2228                extras = new Bundle();
2229                extras.putBoolean(Intent.EXTRA_REPLACING,
2230                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2231                break;
2232            }
2233        }
2234        return extras;
2235    }
2236
2237    void scheduleWriteSettingsLocked() {
2238        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2239            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2240        }
2241    }
2242
2243    void scheduleWritePackageListLocked(int userId) {
2244        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2245            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2246            msg.arg1 = userId;
2247            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2248        }
2249    }
2250
2251    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2252        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2253        scheduleWritePackageRestrictionsLocked(userId);
2254    }
2255
2256    void scheduleWritePackageRestrictionsLocked(int userId) {
2257        final int[] userIds = (userId == UserHandle.USER_ALL)
2258                ? sUserManager.getUserIds() : new int[]{userId};
2259        for (int nextUserId : userIds) {
2260            if (!sUserManager.exists(nextUserId)) return;
2261            mDirtyUsers.add(nextUserId);
2262            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2263                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2264            }
2265        }
2266    }
2267
2268    public static PackageManagerService main(Context context, Installer installer,
2269            boolean factoryTest, boolean onlyCore) {
2270        // Self-check for initial settings.
2271        PackageManagerServiceCompilerMapping.checkProperties();
2272
2273        PackageManagerService m = new PackageManagerService(context, installer,
2274                factoryTest, onlyCore);
2275        m.enableSystemUserPackages();
2276        ServiceManager.addService("package", m);
2277        final PackageManagerNative pmn = m.new PackageManagerNative();
2278        ServiceManager.addService("package_native", pmn);
2279        return m;
2280    }
2281
2282    private void enableSystemUserPackages() {
2283        if (!UserManager.isSplitSystemUser()) {
2284            return;
2285        }
2286        // For system user, enable apps based on the following conditions:
2287        // - app is whitelisted or belong to one of these groups:
2288        //   -- system app which has no launcher icons
2289        //   -- system app which has INTERACT_ACROSS_USERS permission
2290        //   -- system IME app
2291        // - app is not in the blacklist
2292        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2293        Set<String> enableApps = new ArraySet<>();
2294        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2295                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2296                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2297        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2298        enableApps.addAll(wlApps);
2299        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2300                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2301        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2302        enableApps.removeAll(blApps);
2303        Log.i(TAG, "Applications installed for system user: " + enableApps);
2304        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2305                UserHandle.SYSTEM);
2306        final int allAppsSize = allAps.size();
2307        synchronized (mPackages) {
2308            for (int i = 0; i < allAppsSize; i++) {
2309                String pName = allAps.get(i);
2310                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2311                // Should not happen, but we shouldn't be failing if it does
2312                if (pkgSetting == null) {
2313                    continue;
2314                }
2315                boolean install = enableApps.contains(pName);
2316                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2317                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2318                            + " for system user");
2319                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2320                }
2321            }
2322            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2323        }
2324    }
2325
2326    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2327        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2328                Context.DISPLAY_SERVICE);
2329        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2330    }
2331
2332    /**
2333     * Requests that files preopted on a secondary system partition be copied to the data partition
2334     * if possible.  Note that the actual copying of the files is accomplished by init for security
2335     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2336     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2337     */
2338    private static void requestCopyPreoptedFiles() {
2339        final int WAIT_TIME_MS = 100;
2340        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2341        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2342            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2343            // We will wait for up to 100 seconds.
2344            final long timeStart = SystemClock.uptimeMillis();
2345            final long timeEnd = timeStart + 100 * 1000;
2346            long timeNow = timeStart;
2347            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2348                try {
2349                    Thread.sleep(WAIT_TIME_MS);
2350                } catch (InterruptedException e) {
2351                    // Do nothing
2352                }
2353                timeNow = SystemClock.uptimeMillis();
2354                if (timeNow > timeEnd) {
2355                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2356                    Slog.wtf(TAG, "cppreopt did not finish!");
2357                    break;
2358                }
2359            }
2360
2361            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2362        }
2363    }
2364
2365    public PackageManagerService(Context context, Installer installer,
2366            boolean factoryTest, boolean onlyCore) {
2367        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2368        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2369        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2370                SystemClock.uptimeMillis());
2371
2372        if (mSdkVersion <= 0) {
2373            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2374        }
2375
2376        mContext = context;
2377
2378        mFactoryTest = factoryTest;
2379        mOnlyCore = onlyCore;
2380        mMetrics = new DisplayMetrics();
2381        mInstaller = installer;
2382
2383        // Create sub-components that provide services / data. Order here is important.
2384        synchronized (mInstallLock) {
2385        synchronized (mPackages) {
2386            // Expose private service for system components to use.
2387            LocalServices.addService(
2388                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2389            sUserManager = new UserManagerService(context, this,
2390                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2391            mPermissionManager = PermissionManagerService.create(context,
2392                    new DefaultPermissionGrantedCallback() {
2393                        @Override
2394                        public void onDefaultRuntimePermissionsGranted(int userId) {
2395                            synchronized(mPackages) {
2396                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2397                            }
2398                        }
2399                    }, mPackages /*externalLock*/);
2400            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2401            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2402        }
2403        }
2404        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2415                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2416        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2417                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2418
2419        String separateProcesses = SystemProperties.get("debug.separate_processes");
2420        if (separateProcesses != null && separateProcesses.length() > 0) {
2421            if ("*".equals(separateProcesses)) {
2422                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2423                mSeparateProcesses = null;
2424                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2425            } else {
2426                mDefParseFlags = 0;
2427                mSeparateProcesses = separateProcesses.split(",");
2428                Slog.w(TAG, "Running with debug.separate_processes: "
2429                        + separateProcesses);
2430            }
2431        } else {
2432            mDefParseFlags = 0;
2433            mSeparateProcesses = null;
2434        }
2435
2436        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2437                "*dexopt*");
2438        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2439                installer, mInstallLock);
2440        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2441                dexManagerListener);
2442        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2443        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2444
2445        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2446                FgThread.get().getLooper());
2447
2448        getDefaultDisplayMetrics(context, mMetrics);
2449
2450        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2451        SystemConfig systemConfig = SystemConfig.getInstance();
2452        mAvailableFeatures = systemConfig.getAvailableFeatures();
2453        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2454
2455        mProtectedPackages = new ProtectedPackages(mContext);
2456
2457        synchronized (mInstallLock) {
2458        // writer
2459        synchronized (mPackages) {
2460            mHandlerThread = new ServiceThread(TAG,
2461                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2462            mHandlerThread.start();
2463            mHandler = new PackageHandler(mHandlerThread.getLooper());
2464            mProcessLoggingHandler = new ProcessLoggingHandler();
2465            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2466            mInstantAppRegistry = new InstantAppRegistry(this);
2467
2468            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2469            final int builtInLibCount = libConfig.size();
2470            for (int i = 0; i < builtInLibCount; i++) {
2471                String name = libConfig.keyAt(i);
2472                String path = libConfig.valueAt(i);
2473                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2474                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2475            }
2476
2477            SELinuxMMAC.readInstallPolicy();
2478
2479            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2480            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2481            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2482
2483            // Clean up orphaned packages for which the code path doesn't exist
2484            // and they are an update to a system app - caused by bug/32321269
2485            final int packageSettingCount = mSettings.mPackages.size();
2486            for (int i = packageSettingCount - 1; i >= 0; i--) {
2487                PackageSetting ps = mSettings.mPackages.valueAt(i);
2488                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2489                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2490                    mSettings.mPackages.removeAt(i);
2491                    mSettings.enableSystemPackageLPw(ps.name);
2492                }
2493            }
2494
2495            if (mFirstBoot) {
2496                requestCopyPreoptedFiles();
2497            }
2498
2499            String customResolverActivity = Resources.getSystem().getString(
2500                    R.string.config_customResolverActivity);
2501            if (TextUtils.isEmpty(customResolverActivity)) {
2502                customResolverActivity = null;
2503            } else {
2504                mCustomResolverComponentName = ComponentName.unflattenFromString(
2505                        customResolverActivity);
2506            }
2507
2508            long startTime = SystemClock.uptimeMillis();
2509
2510            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2511                    startTime);
2512
2513            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2514            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2515
2516            if (bootClassPath == null) {
2517                Slog.w(TAG, "No BOOTCLASSPATH found!");
2518            }
2519
2520            if (systemServerClassPath == null) {
2521                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2522            }
2523
2524            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2525
2526            final VersionInfo ver = mSettings.getInternalVersion();
2527            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2528            if (mIsUpgrade) {
2529                logCriticalInfo(Log.INFO,
2530                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2531            }
2532
2533            // when upgrading from pre-M, promote system app permissions from install to runtime
2534            mPromoteSystemApps =
2535                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2536
2537            // When upgrading from pre-N, we need to handle package extraction like first boot,
2538            // as there is no profiling data available.
2539            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2540
2541            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2542
2543            // save off the names of pre-existing system packages prior to scanning; we don't
2544            // want to automatically grant runtime permissions for new system apps
2545            if (mPromoteSystemApps) {
2546                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2547                while (pkgSettingIter.hasNext()) {
2548                    PackageSetting ps = pkgSettingIter.next();
2549                    if (isSystemApp(ps)) {
2550                        mExistingSystemPackages.add(ps.name);
2551                    }
2552                }
2553            }
2554
2555            mCacheDir = preparePackageParserCache(mIsUpgrade);
2556
2557            // Set flag to monitor and not change apk file paths when
2558            // scanning install directories.
2559            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2560
2561            if (mIsUpgrade || mFirstBoot) {
2562                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2563            }
2564
2565            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2566            // For security and version matching reason, only consider
2567            // overlay packages if they reside in the right directory.
2568            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2569                    mDefParseFlags
2570                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2571                    scanFlags
2572                    | SCAN_AS_SYSTEM
2573                    | SCAN_AS_VENDOR,
2574                    0);
2575            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2576                    mDefParseFlags
2577                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2578                    scanFlags
2579                    | SCAN_AS_SYSTEM
2580                    | SCAN_AS_PRODUCT,
2581                    0);
2582
2583            mParallelPackageParserCallback.findStaticOverlayPackages();
2584
2585            // Find base frameworks (resource packages without code).
2586            scanDirTracedLI(frameworkDir,
2587                    mDefParseFlags
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2589                    scanFlags
2590                    | SCAN_NO_DEX
2591                    | SCAN_AS_SYSTEM
2592                    | SCAN_AS_PRIVILEGED,
2593                    0);
2594
2595            // Collect privileged system packages.
2596            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2597            scanDirTracedLI(privilegedAppDir,
2598                    mDefParseFlags
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2600                    scanFlags
2601                    | SCAN_AS_SYSTEM
2602                    | SCAN_AS_PRIVILEGED,
2603                    0);
2604
2605            // Collect ordinary system packages.
2606            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2607            scanDirTracedLI(systemAppDir,
2608                    mDefParseFlags
2609                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2610                    scanFlags
2611                    | SCAN_AS_SYSTEM,
2612                    0);
2613
2614            // Collect privileged vendor packages.
2615            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2616            try {
2617                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2618            } catch (IOException e) {
2619                // failed to look up canonical path, continue with original one
2620            }
2621            scanDirTracedLI(privilegedVendorAppDir,
2622                    mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2624                    scanFlags
2625                    | SCAN_AS_SYSTEM
2626                    | SCAN_AS_VENDOR
2627                    | SCAN_AS_PRIVILEGED,
2628                    0);
2629
2630            // Collect ordinary vendor packages.
2631            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2632            try {
2633                vendorAppDir = vendorAppDir.getCanonicalFile();
2634            } catch (IOException e) {
2635                // failed to look up canonical path, continue with original one
2636            }
2637            scanDirTracedLI(vendorAppDir,
2638                    mDefParseFlags
2639                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2640                    scanFlags
2641                    | SCAN_AS_SYSTEM
2642                    | SCAN_AS_VENDOR,
2643                    0);
2644
2645            // Collect privileged odm packages. /odm is another vendor partition
2646            // other than /vendor.
2647            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2648                        "priv-app");
2649            try {
2650                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2651            } catch (IOException e) {
2652                // failed to look up canonical path, continue with original one
2653            }
2654            scanDirTracedLI(privilegedOdmAppDir,
2655                    mDefParseFlags
2656                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2657                    scanFlags
2658                    | SCAN_AS_SYSTEM
2659                    | SCAN_AS_VENDOR
2660                    | SCAN_AS_PRIVILEGED,
2661                    0);
2662
2663            // Collect ordinary odm packages. /odm is another vendor partition
2664            // other than /vendor.
2665            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2666            try {
2667                odmAppDir = odmAppDir.getCanonicalFile();
2668            } catch (IOException e) {
2669                // failed to look up canonical path, continue with original one
2670            }
2671            scanDirTracedLI(odmAppDir,
2672                    mDefParseFlags
2673                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2674                    scanFlags
2675                    | SCAN_AS_SYSTEM
2676                    | SCAN_AS_VENDOR,
2677                    0);
2678
2679            // Collect all OEM packages.
2680            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2681            scanDirTracedLI(oemAppDir,
2682                    mDefParseFlags
2683                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2684                    scanFlags
2685                    | SCAN_AS_SYSTEM
2686                    | SCAN_AS_OEM,
2687                    0);
2688
2689            // Collected privileged product packages.
2690            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2691            try {
2692                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2693            } catch (IOException e) {
2694                // failed to look up canonical path, continue with original one
2695            }
2696            scanDirTracedLI(privilegedProductAppDir,
2697                    mDefParseFlags
2698                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2699                    scanFlags
2700                    | SCAN_AS_SYSTEM
2701                    | SCAN_AS_PRODUCT
2702                    | SCAN_AS_PRIVILEGED,
2703                    0);
2704
2705            // Collect ordinary product packages.
2706            File productAppDir = new File(Environment.getProductDirectory(), "app");
2707            try {
2708                productAppDir = productAppDir.getCanonicalFile();
2709            } catch (IOException e) {
2710                // failed to look up canonical path, continue with original one
2711            }
2712            scanDirTracedLI(productAppDir,
2713                    mDefParseFlags
2714                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2715                    scanFlags
2716                    | SCAN_AS_SYSTEM
2717                    | SCAN_AS_PRODUCT,
2718                    0);
2719
2720            // Prune any system packages that no longer exist.
2721            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2722            // Stub packages must either be replaced with full versions in the /data
2723            // partition or be disabled.
2724            final List<String> stubSystemApps = new ArrayList<>();
2725            if (!mOnlyCore) {
2726                // do this first before mucking with mPackages for the "expecting better" case
2727                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2728                while (pkgIterator.hasNext()) {
2729                    final PackageParser.Package pkg = pkgIterator.next();
2730                    if (pkg.isStub) {
2731                        stubSystemApps.add(pkg.packageName);
2732                    }
2733                }
2734
2735                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2736                while (psit.hasNext()) {
2737                    PackageSetting ps = psit.next();
2738
2739                    /*
2740                     * If this is not a system app, it can't be a
2741                     * disable system app.
2742                     */
2743                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2744                        continue;
2745                    }
2746
2747                    /*
2748                     * If the package is scanned, it's not erased.
2749                     */
2750                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2751                    if (scannedPkg != null) {
2752                        /*
2753                         * If the system app is both scanned and in the
2754                         * disabled packages list, then it must have been
2755                         * added via OTA. Remove it from the currently
2756                         * scanned package so the previously user-installed
2757                         * application can be scanned.
2758                         */
2759                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2760                            logCriticalInfo(Log.WARN,
2761                                    "Expecting better updated system app for " + ps.name
2762                                    + "; removing system app.  Last known"
2763                                    + " codePath=" + ps.codePathString
2764                                    + ", versionCode=" + ps.versionCode
2765                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2766                            removePackageLI(scannedPkg, true);
2767                            mExpectingBetter.put(ps.name, ps.codePath);
2768                        }
2769
2770                        continue;
2771                    }
2772
2773                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2774                        psit.remove();
2775                        logCriticalInfo(Log.WARN, "System package " + ps.name
2776                                + " no longer exists; it's data will be wiped");
2777                        // Actual deletion of code and data will be handled by later
2778                        // reconciliation step
2779                    } else {
2780                        // we still have a disabled system package, but, it still might have
2781                        // been removed. check the code path still exists and check there's
2782                        // still a package. the latter can happen if an OTA keeps the same
2783                        // code path, but, changes the package name.
2784                        final PackageSetting disabledPs =
2785                                mSettings.getDisabledSystemPkgLPr(ps.name);
2786                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2787                                || disabledPs.pkg == null) {
2788                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2789                        }
2790                    }
2791                }
2792            }
2793
2794            //delete tmp files
2795            deleteTempPackageFiles();
2796
2797            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2798
2799            // Remove any shared userIDs that have no associated packages
2800            mSettings.pruneSharedUsersLPw();
2801            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2802            final int systemPackagesCount = mPackages.size();
2803            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2804                    + " ms, packageCount: " + systemPackagesCount
2805                    + " , timePerPackage: "
2806                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2807                    + " , cached: " + cachedSystemApps);
2808            if (mIsUpgrade && systemPackagesCount > 0) {
2809                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2810                        ((int) systemScanTime) / systemPackagesCount);
2811            }
2812            if (!mOnlyCore) {
2813                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2814                        SystemClock.uptimeMillis());
2815                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2816
2817                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2818                        | PackageParser.PARSE_FORWARD_LOCK,
2819                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2820
2821                // Remove disable package settings for updated system apps that were
2822                // removed via an OTA. If the update is no longer present, remove the
2823                // app completely. Otherwise, revoke their system privileges.
2824                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2825                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2826                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2827                    final String msg;
2828                    if (deletedPkg == null) {
2829                        // should have found an update, but, we didn't; remove everything
2830                        msg = "Updated system package " + deletedAppName
2831                                + " no longer exists; removing its data";
2832                        // Actual deletion of code and data will be handled by later
2833                        // reconciliation step
2834                    } else {
2835                        // found an update; revoke system privileges
2836                        msg = "Updated system package + " + deletedAppName
2837                                + " no longer exists; revoking system privileges";
2838
2839                        // Don't do anything if a stub is removed from the system image. If
2840                        // we were to remove the uncompressed version from the /data partition,
2841                        // this is where it'd be done.
2842
2843                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2844                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2845                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2846                    }
2847                    logCriticalInfo(Log.WARN, msg);
2848                }
2849
2850                /*
2851                 * Make sure all system apps that we expected to appear on
2852                 * the userdata partition actually showed up. If they never
2853                 * appeared, crawl back and revive the system version.
2854                 */
2855                for (int i = 0; i < mExpectingBetter.size(); i++) {
2856                    final String packageName = mExpectingBetter.keyAt(i);
2857                    if (!mPackages.containsKey(packageName)) {
2858                        final File scanFile = mExpectingBetter.valueAt(i);
2859
2860                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2861                                + " but never showed up; reverting to system");
2862
2863                        final @ParseFlags int reparseFlags;
2864                        final @ScanFlags int rescanFlags;
2865                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2866                            reparseFlags =
2867                                    mDefParseFlags |
2868                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2869                            rescanFlags =
2870                                    scanFlags
2871                                    | SCAN_AS_SYSTEM
2872                                    | SCAN_AS_PRIVILEGED;
2873                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2874                            reparseFlags =
2875                                    mDefParseFlags |
2876                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2877                            rescanFlags =
2878                                    scanFlags
2879                                    | SCAN_AS_SYSTEM;
2880                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2881                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2882                            reparseFlags =
2883                                    mDefParseFlags |
2884                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2885                            rescanFlags =
2886                                    scanFlags
2887                                    | SCAN_AS_SYSTEM
2888                                    | SCAN_AS_VENDOR
2889                                    | SCAN_AS_PRIVILEGED;
2890                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2891                                || FileUtils.contains(odmAppDir, scanFile)) {
2892                            reparseFlags =
2893                                    mDefParseFlags |
2894                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2895                            rescanFlags =
2896                                    scanFlags
2897                                    | SCAN_AS_SYSTEM
2898                                    | SCAN_AS_VENDOR;
2899                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2900                            reparseFlags =
2901                                    mDefParseFlags |
2902                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2903                            rescanFlags =
2904                                    scanFlags
2905                                    | SCAN_AS_SYSTEM
2906                                    | SCAN_AS_OEM;
2907                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2908                            reparseFlags =
2909                                    mDefParseFlags |
2910                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2911                            rescanFlags =
2912                                    scanFlags
2913                                    | SCAN_AS_SYSTEM
2914                                    | SCAN_AS_PRODUCT
2915                                    | SCAN_AS_PRIVILEGED;
2916                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2917                            reparseFlags =
2918                                    mDefParseFlags |
2919                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2920                            rescanFlags =
2921                                    scanFlags
2922                                    | SCAN_AS_SYSTEM
2923                                    | SCAN_AS_PRODUCT;
2924                        } else {
2925                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2926                            continue;
2927                        }
2928
2929                        mSettings.enableSystemPackageLPw(packageName);
2930
2931                        try {
2932                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2933                        } catch (PackageManagerException e) {
2934                            Slog.e(TAG, "Failed to parse original system package: "
2935                                    + e.getMessage());
2936                        }
2937                    }
2938                }
2939
2940                // Uncompress and install any stubbed system applications.
2941                // This must be done last to ensure all stubs are replaced or disabled.
2942                decompressSystemApplications(stubSystemApps, scanFlags);
2943
2944                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2945                                - cachedSystemApps;
2946
2947                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2948                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2949                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2950                        + " ms, packageCount: " + dataPackagesCount
2951                        + " , timePerPackage: "
2952                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2953                        + " , cached: " + cachedNonSystemApps);
2954                if (mIsUpgrade && dataPackagesCount > 0) {
2955                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2956                            ((int) dataScanTime) / dataPackagesCount);
2957                }
2958            }
2959            mExpectingBetter.clear();
2960
2961            // Resolve the storage manager.
2962            mStorageManagerPackage = getStorageManagerPackageName();
2963
2964            // Resolve protected action filters. Only the setup wizard is allowed to
2965            // have a high priority filter for these actions.
2966            mSetupWizardPackage = getSetupWizardPackageName();
2967            if (mProtectedFilters.size() > 0) {
2968                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2969                    Slog.i(TAG, "No setup wizard;"
2970                        + " All protected intents capped to priority 0");
2971                }
2972                for (ActivityIntentInfo filter : mProtectedFilters) {
2973                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2974                        if (DEBUG_FILTERS) {
2975                            Slog.i(TAG, "Found setup wizard;"
2976                                + " allow priority " + filter.getPriority() + ";"
2977                                + " package: " + filter.activity.info.packageName
2978                                + " activity: " + filter.activity.className
2979                                + " priority: " + filter.getPriority());
2980                        }
2981                        // skip setup wizard; allow it to keep the high priority filter
2982                        continue;
2983                    }
2984                    if (DEBUG_FILTERS) {
2985                        Slog.i(TAG, "Protected action; cap priority to 0;"
2986                                + " package: " + filter.activity.info.packageName
2987                                + " activity: " + filter.activity.className
2988                                + " origPrio: " + filter.getPriority());
2989                    }
2990                    filter.setPriority(0);
2991                }
2992            }
2993
2994            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
2995
2996            mDeferProtectedFilters = false;
2997            mProtectedFilters.clear();
2998
2999            // Now that we know all of the shared libraries, update all clients to have
3000            // the correct library paths.
3001            updateAllSharedLibrariesLPw(null);
3002
3003            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3004                // NOTE: We ignore potential failures here during a system scan (like
3005                // the rest of the commands above) because there's precious little we
3006                // can do about it. A settings error is reported, though.
3007                final List<String> changedAbiCodePath =
3008                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3009                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3010                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3011                        final String codePathString = changedAbiCodePath.get(i);
3012                        try {
3013                            mInstaller.rmdex(codePathString,
3014                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3015                        } catch (InstallerException ignored) {
3016                        }
3017                    }
3018                }
3019                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3020                // SELinux domain.
3021                setting.fixSeInfoLocked();
3022            }
3023
3024            // Now that we know all the packages we are keeping,
3025            // read and update their last usage times.
3026            mPackageUsage.read(mPackages);
3027            mCompilerStats.read();
3028
3029            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3030                    SystemClock.uptimeMillis());
3031            Slog.i(TAG, "Time to scan packages: "
3032                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3033                    + " seconds");
3034
3035            // If the platform SDK has changed since the last time we booted,
3036            // we need to re-grant app permission to catch any new ones that
3037            // appear.  This is really a hack, and means that apps can in some
3038            // cases get permissions that the user didn't initially explicitly
3039            // allow...  it would be nice to have some better way to handle
3040            // this situation.
3041            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3042            if (sdkUpdated) {
3043                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3044                        + mSdkVersion + "; regranting permissions for internal storage");
3045            }
3046            mPermissionManager.updateAllPermissions(
3047                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3048                    mPermissionCallback);
3049            ver.sdkVersion = mSdkVersion;
3050
3051            // If this is the first boot or an update from pre-M, and it is a normal
3052            // boot, then we need to initialize the default preferred apps across
3053            // all defined users.
3054            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3055                for (UserInfo user : sUserManager.getUsers(true)) {
3056                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3057                    applyFactoryDefaultBrowserLPw(user.id);
3058                    primeDomainVerificationsLPw(user.id);
3059                }
3060            }
3061
3062            // Prepare storage for system user really early during boot,
3063            // since core system apps like SettingsProvider and SystemUI
3064            // can't wait for user to start
3065            final int storageFlags;
3066            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3067                storageFlags = StorageManager.FLAG_STORAGE_DE;
3068            } else {
3069                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3070            }
3071            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3072                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3073                    true /* onlyCoreApps */);
3074            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3075                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3076                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3077                traceLog.traceBegin("AppDataFixup");
3078                try {
3079                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3080                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3081                } catch (InstallerException e) {
3082                    Slog.w(TAG, "Trouble fixing GIDs", e);
3083                }
3084                traceLog.traceEnd();
3085
3086                traceLog.traceBegin("AppDataPrepare");
3087                if (deferPackages == null || deferPackages.isEmpty()) {
3088                    return;
3089                }
3090                int count = 0;
3091                for (String pkgName : deferPackages) {
3092                    PackageParser.Package pkg = null;
3093                    synchronized (mPackages) {
3094                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3095                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3096                            pkg = ps.pkg;
3097                        }
3098                    }
3099                    if (pkg != null) {
3100                        synchronized (mInstallLock) {
3101                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3102                                    true /* maybeMigrateAppData */);
3103                        }
3104                        count++;
3105                    }
3106                }
3107                traceLog.traceEnd();
3108                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3109            }, "prepareAppData");
3110
3111            // If this is first boot after an OTA, and a normal boot, then
3112            // we need to clear code cache directories.
3113            // Note that we do *not* clear the application profiles. These remain valid
3114            // across OTAs and are used to drive profile verification (post OTA) and
3115            // profile compilation (without waiting to collect a fresh set of profiles).
3116            if (mIsUpgrade && !onlyCore) {
3117                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3118                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3119                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3120                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3121                        // No apps are running this early, so no need to freeze
3122                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3123                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3124                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3125                    }
3126                }
3127                ver.fingerprint = Build.FINGERPRINT;
3128            }
3129
3130            checkDefaultBrowser();
3131
3132            // clear only after permissions and other defaults have been updated
3133            mExistingSystemPackages.clear();
3134            mPromoteSystemApps = false;
3135
3136            // All the changes are done during package scanning.
3137            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3138
3139            // can downgrade to reader
3140            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3141            mSettings.writeLPr();
3142            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3143            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3144                    SystemClock.uptimeMillis());
3145
3146            if (!mOnlyCore) {
3147                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3148                mRequiredInstallerPackage = getRequiredInstallerLPr();
3149                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3150                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3151                if (mIntentFilterVerifierComponent != null) {
3152                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3153                            mIntentFilterVerifierComponent);
3154                } else {
3155                    mIntentFilterVerifier = null;
3156                }
3157                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3158                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3159                        SharedLibraryInfo.VERSION_UNDEFINED);
3160                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3161                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3162                        SharedLibraryInfo.VERSION_UNDEFINED);
3163            } else {
3164                mRequiredVerifierPackage = null;
3165                mRequiredInstallerPackage = null;
3166                mRequiredUninstallerPackage = null;
3167                mIntentFilterVerifierComponent = null;
3168                mIntentFilterVerifier = null;
3169                mServicesSystemSharedLibraryPackageName = null;
3170                mSharedSystemSharedLibraryPackageName = null;
3171            }
3172
3173            mInstallerService = new PackageInstallerService(context, this);
3174            final Pair<ComponentName, String> instantAppResolverComponent =
3175                    getInstantAppResolverLPr();
3176            if (instantAppResolverComponent != null) {
3177                if (DEBUG_INSTANT) {
3178                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3179                }
3180                mInstantAppResolverConnection = new InstantAppResolverConnection(
3181                        mContext, instantAppResolverComponent.first,
3182                        instantAppResolverComponent.second);
3183                mInstantAppResolverSettingsComponent =
3184                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3185            } else {
3186                mInstantAppResolverConnection = null;
3187                mInstantAppResolverSettingsComponent = null;
3188            }
3189            updateInstantAppInstallerLocked(null);
3190
3191            // Read and update the usage of dex files.
3192            // Do this at the end of PM init so that all the packages have their
3193            // data directory reconciled.
3194            // At this point we know the code paths of the packages, so we can validate
3195            // the disk file and build the internal cache.
3196            // The usage file is expected to be small so loading and verifying it
3197            // should take a fairly small time compare to the other activities (e.g. package
3198            // scanning).
3199            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3200            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3201            for (int userId : currentUserIds) {
3202                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3203            }
3204            mDexManager.load(userPackages);
3205            if (mIsUpgrade) {
3206                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3207                        (int) (SystemClock.uptimeMillis() - startTime));
3208            }
3209        } // synchronized (mPackages)
3210        } // synchronized (mInstallLock)
3211
3212        // Now after opening every single application zip, make sure they
3213        // are all flushed.  Not really needed, but keeps things nice and
3214        // tidy.
3215        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3216        Runtime.getRuntime().gc();
3217        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3218
3219        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3220        FallbackCategoryProvider.loadFallbacks();
3221        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3222
3223        // The initial scanning above does many calls into installd while
3224        // holding the mPackages lock, but we're mostly interested in yelling
3225        // once we have a booted system.
3226        mInstaller.setWarnIfHeld(mPackages);
3227
3228        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3229    }
3230
3231    /**
3232     * Uncompress and install stub applications.
3233     * <p>In order to save space on the system partition, some applications are shipped in a
3234     * compressed form. In addition the compressed bits for the full application, the
3235     * system image contains a tiny stub comprised of only the Android manifest.
3236     * <p>During the first boot, attempt to uncompress and install the full application. If
3237     * the application can't be installed for any reason, disable the stub and prevent
3238     * uncompressing the full application during future boots.
3239     * <p>In order to forcefully attempt an installation of a full application, go to app
3240     * settings and enable the application.
3241     */
3242    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3243        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3244            final String pkgName = stubSystemApps.get(i);
3245            // skip if the system package is already disabled
3246            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3247                stubSystemApps.remove(i);
3248                continue;
3249            }
3250            // skip if the package isn't installed (?!); this should never happen
3251            final PackageParser.Package pkg = mPackages.get(pkgName);
3252            if (pkg == null) {
3253                stubSystemApps.remove(i);
3254                continue;
3255            }
3256            // skip if the package has been disabled by the user
3257            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3258            if (ps != null) {
3259                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3260                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3261                    stubSystemApps.remove(i);
3262                    continue;
3263                }
3264            }
3265
3266            if (DEBUG_COMPRESSION) {
3267                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3268            }
3269
3270            // uncompress the binary to its eventual destination on /data
3271            final File scanFile = decompressPackage(pkg);
3272            if (scanFile == null) {
3273                continue;
3274            }
3275
3276            // install the package to replace the stub on /system
3277            try {
3278                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3279                removePackageLI(pkg, true /*chatty*/);
3280                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3281                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3282                        UserHandle.USER_SYSTEM, "android");
3283                stubSystemApps.remove(i);
3284                continue;
3285            } catch (PackageManagerException e) {
3286                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3287            }
3288
3289            // any failed attempt to install the package will be cleaned up later
3290        }
3291
3292        // disable any stub still left; these failed to install the full application
3293        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3294            final String pkgName = stubSystemApps.get(i);
3295            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3296            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3297                    UserHandle.USER_SYSTEM, "android");
3298            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3299        }
3300    }
3301
3302    /**
3303     * Decompresses the given package on the system image onto
3304     * the /data partition.
3305     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3306     */
3307    private File decompressPackage(PackageParser.Package pkg) {
3308        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3309        if (compressedFiles == null || compressedFiles.length == 0) {
3310            if (DEBUG_COMPRESSION) {
3311                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3312            }
3313            return null;
3314        }
3315        final File dstCodePath =
3316                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3317        int ret = PackageManager.INSTALL_SUCCEEDED;
3318        try {
3319            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3320            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3321            for (File srcFile : compressedFiles) {
3322                final String srcFileName = srcFile.getName();
3323                final String dstFileName = srcFileName.substring(
3324                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3325                final File dstFile = new File(dstCodePath, dstFileName);
3326                ret = decompressFile(srcFile, dstFile);
3327                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3328                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3329                            + "; pkg: " + pkg.packageName
3330                            + ", file: " + dstFileName);
3331                    break;
3332                }
3333            }
3334        } catch (ErrnoException e) {
3335            logCriticalInfo(Log.ERROR, "Failed to decompress"
3336                    + "; pkg: " + pkg.packageName
3337                    + ", err: " + e.errno);
3338        }
3339        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3340            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3341            NativeLibraryHelper.Handle handle = null;
3342            try {
3343                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3344                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3345                        null /*abiOverride*/);
3346            } catch (IOException e) {
3347                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3348                        + "; pkg: " + pkg.packageName);
3349                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3350            } finally {
3351                IoUtils.closeQuietly(handle);
3352            }
3353        }
3354        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3355            if (dstCodePath == null || !dstCodePath.exists()) {
3356                return null;
3357            }
3358            removeCodePathLI(dstCodePath);
3359            return null;
3360        }
3361
3362        return dstCodePath;
3363    }
3364
3365    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3366        // we're only interested in updating the installer appliction when 1) it's not
3367        // already set or 2) the modified package is the installer
3368        if (mInstantAppInstallerActivity != null
3369                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3370                        .equals(modifiedPackage)) {
3371            return;
3372        }
3373        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3374    }
3375
3376    private static File preparePackageParserCache(boolean isUpgrade) {
3377        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3378            return null;
3379        }
3380
3381        // Disable package parsing on eng builds to allow for faster incremental development.
3382        if (Build.IS_ENG) {
3383            return null;
3384        }
3385
3386        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3387            Slog.i(TAG, "Disabling package parser cache due to system property.");
3388            return null;
3389        }
3390
3391        // The base directory for the package parser cache lives under /data/system/.
3392        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3393                "package_cache");
3394        if (cacheBaseDir == null) {
3395            return null;
3396        }
3397
3398        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3399        // This also serves to "GC" unused entries when the package cache version changes (which
3400        // can only happen during upgrades).
3401        if (isUpgrade) {
3402            FileUtils.deleteContents(cacheBaseDir);
3403        }
3404
3405
3406        // Return the versioned package cache directory. This is something like
3407        // "/data/system/package_cache/1"
3408        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3409
3410        if (cacheDir == null) {
3411            // Something went wrong. Attempt to delete everything and return.
3412            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3413            FileUtils.deleteContentsAndDir(cacheBaseDir);
3414            return null;
3415        }
3416
3417        // The following is a workaround to aid development on non-numbered userdebug
3418        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3419        // the system partition is newer.
3420        //
3421        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3422        // that starts with "eng." to signify that this is an engineering build and not
3423        // destined for release.
3424        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3425            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3426
3427            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3428            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3429            // in general and should not be used for production changes. In this specific case,
3430            // we know that they will work.
3431            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3432            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3433                FileUtils.deleteContents(cacheBaseDir);
3434                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3435            }
3436        }
3437
3438        return cacheDir;
3439    }
3440
3441    @Override
3442    public boolean isFirstBoot() {
3443        // allow instant applications
3444        return mFirstBoot;
3445    }
3446
3447    @Override
3448    public boolean isOnlyCoreApps() {
3449        // allow instant applications
3450        return mOnlyCore;
3451    }
3452
3453    @Override
3454    public boolean isUpgrade() {
3455        // allow instant applications
3456        // The system property allows testing ota flow when upgraded to the same image.
3457        return mIsUpgrade || SystemProperties.getBoolean(
3458                "persist.pm.mock-upgrade", false /* default */);
3459    }
3460
3461    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3462        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3463
3464        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3465                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3466                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3467        if (matches.size() == 1) {
3468            return matches.get(0).getComponentInfo().packageName;
3469        } else if (matches.size() == 0) {
3470            Log.e(TAG, "There should probably be a verifier, but, none were found");
3471            return null;
3472        }
3473        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3474    }
3475
3476    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3477        synchronized (mPackages) {
3478            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3479            if (libraryEntry == null) {
3480                throw new IllegalStateException("Missing required shared library:" + name);
3481            }
3482            return libraryEntry.apk;
3483        }
3484    }
3485
3486    private @NonNull String getRequiredInstallerLPr() {
3487        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3488        intent.addCategory(Intent.CATEGORY_DEFAULT);
3489        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3490
3491        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3492                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3493                UserHandle.USER_SYSTEM);
3494        if (matches.size() == 1) {
3495            ResolveInfo resolveInfo = matches.get(0);
3496            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3497                throw new RuntimeException("The installer must be a privileged app");
3498            }
3499            return matches.get(0).getComponentInfo().packageName;
3500        } else {
3501            throw new RuntimeException("There must be exactly one installer; found " + matches);
3502        }
3503    }
3504
3505    private @NonNull String getRequiredUninstallerLPr() {
3506        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3507        intent.addCategory(Intent.CATEGORY_DEFAULT);
3508        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3509
3510        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3511                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3512                UserHandle.USER_SYSTEM);
3513        if (resolveInfo == null ||
3514                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3515            throw new RuntimeException("There must be exactly one uninstaller; found "
3516                    + resolveInfo);
3517        }
3518        return resolveInfo.getComponentInfo().packageName;
3519    }
3520
3521    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3522        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3523
3524        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3525                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3526                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3527        ResolveInfo best = null;
3528        final int N = matches.size();
3529        for (int i = 0; i < N; i++) {
3530            final ResolveInfo cur = matches.get(i);
3531            final String packageName = cur.getComponentInfo().packageName;
3532            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3533                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3534                continue;
3535            }
3536
3537            if (best == null || cur.priority > best.priority) {
3538                best = cur;
3539            }
3540        }
3541
3542        if (best != null) {
3543            return best.getComponentInfo().getComponentName();
3544        }
3545        Slog.w(TAG, "Intent filter verifier not found");
3546        return null;
3547    }
3548
3549    @Override
3550    public @Nullable ComponentName getInstantAppResolverComponent() {
3551        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3552            return null;
3553        }
3554        synchronized (mPackages) {
3555            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3556            if (instantAppResolver == null) {
3557                return null;
3558            }
3559            return instantAppResolver.first;
3560        }
3561    }
3562
3563    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3564        final String[] packageArray =
3565                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3566        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3567            if (DEBUG_INSTANT) {
3568                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3569            }
3570            return null;
3571        }
3572
3573        final int callingUid = Binder.getCallingUid();
3574        final int resolveFlags =
3575                MATCH_DIRECT_BOOT_AWARE
3576                | MATCH_DIRECT_BOOT_UNAWARE
3577                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3578        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3579        final Intent resolverIntent = new Intent(actionName);
3580        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3581                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3582        final int N = resolvers.size();
3583        if (N == 0) {
3584            if (DEBUG_INSTANT) {
3585                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3586            }
3587            return null;
3588        }
3589
3590        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3591        for (int i = 0; i < N; i++) {
3592            final ResolveInfo info = resolvers.get(i);
3593
3594            if (info.serviceInfo == null) {
3595                continue;
3596            }
3597
3598            final String packageName = info.serviceInfo.packageName;
3599            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3600                if (DEBUG_INSTANT) {
3601                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3602                            + " pkg: " + packageName + ", info:" + info);
3603                }
3604                continue;
3605            }
3606
3607            if (DEBUG_INSTANT) {
3608                Slog.v(TAG, "Ephemeral resolver found;"
3609                        + " pkg: " + packageName + ", info:" + info);
3610            }
3611            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3612        }
3613        if (DEBUG_INSTANT) {
3614            Slog.v(TAG, "Ephemeral resolver NOT found");
3615        }
3616        return null;
3617    }
3618
3619    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3620        String[] orderedActions = Build.IS_ENG
3621                ? new String[]{
3622                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3623                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3624                : new String[]{
3625                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3626
3627        final int resolveFlags =
3628                MATCH_DIRECT_BOOT_AWARE
3629                        | MATCH_DIRECT_BOOT_UNAWARE
3630                        | Intent.FLAG_IGNORE_EPHEMERAL
3631                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3632        final Intent intent = new Intent();
3633        intent.addCategory(Intent.CATEGORY_DEFAULT);
3634        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3635        List<ResolveInfo> matches = null;
3636        for (String action : orderedActions) {
3637            intent.setAction(action);
3638            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3639                    resolveFlags, UserHandle.USER_SYSTEM);
3640            if (matches.isEmpty()) {
3641                if (DEBUG_INSTANT) {
3642                    Slog.d(TAG, "Instant App installer not found with " + action);
3643                }
3644            } else {
3645                break;
3646            }
3647        }
3648        Iterator<ResolveInfo> iter = matches.iterator();
3649        while (iter.hasNext()) {
3650            final ResolveInfo rInfo = iter.next();
3651            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3652            if (ps != null) {
3653                final PermissionsState permissionsState = ps.getPermissionsState();
3654                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3655                        || Build.IS_ENG) {
3656                    continue;
3657                }
3658            }
3659            iter.remove();
3660        }
3661        if (matches.size() == 0) {
3662            return null;
3663        } else if (matches.size() == 1) {
3664            return (ActivityInfo) matches.get(0).getComponentInfo();
3665        } else {
3666            throw new RuntimeException(
3667                    "There must be at most one ephemeral installer; found " + matches);
3668        }
3669    }
3670
3671    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3672            @NonNull ComponentName resolver) {
3673        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3674                .addCategory(Intent.CATEGORY_DEFAULT)
3675                .setPackage(resolver.getPackageName());
3676        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3677        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3678                UserHandle.USER_SYSTEM);
3679        if (matches.isEmpty()) {
3680            return null;
3681        }
3682        return matches.get(0).getComponentInfo().getComponentName();
3683    }
3684
3685    private void primeDomainVerificationsLPw(int userId) {
3686        if (DEBUG_DOMAIN_VERIFICATION) {
3687            Slog.d(TAG, "Priming domain verifications in user " + userId);
3688        }
3689
3690        SystemConfig systemConfig = SystemConfig.getInstance();
3691        ArraySet<String> packages = systemConfig.getLinkedApps();
3692
3693        for (String packageName : packages) {
3694            PackageParser.Package pkg = mPackages.get(packageName);
3695            if (pkg != null) {
3696                if (!pkg.isSystem()) {
3697                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3698                    continue;
3699                }
3700
3701                ArraySet<String> domains = null;
3702                for (PackageParser.Activity a : pkg.activities) {
3703                    for (ActivityIntentInfo filter : a.intents) {
3704                        if (hasValidDomains(filter)) {
3705                            if (domains == null) {
3706                                domains = new ArraySet<String>();
3707                            }
3708                            domains.addAll(filter.getHostsList());
3709                        }
3710                    }
3711                }
3712
3713                if (domains != null && domains.size() > 0) {
3714                    if (DEBUG_DOMAIN_VERIFICATION) {
3715                        Slog.v(TAG, "      + " + packageName);
3716                    }
3717                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3718                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3719                    // and then 'always' in the per-user state actually used for intent resolution.
3720                    final IntentFilterVerificationInfo ivi;
3721                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3722                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3723                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3724                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3725                } else {
3726                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3727                            + "' does not handle web links");
3728                }
3729            } else {
3730                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3731            }
3732        }
3733
3734        scheduleWritePackageRestrictionsLocked(userId);
3735        scheduleWriteSettingsLocked();
3736    }
3737
3738    private void applyFactoryDefaultBrowserLPw(int userId) {
3739        // The default browser app's package name is stored in a string resource,
3740        // with a product-specific overlay used for vendor customization.
3741        String browserPkg = mContext.getResources().getString(
3742                com.android.internal.R.string.default_browser);
3743        if (!TextUtils.isEmpty(browserPkg)) {
3744            // non-empty string => required to be a known package
3745            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3746            if (ps == null) {
3747                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3748                browserPkg = null;
3749            } else {
3750                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3751            }
3752        }
3753
3754        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3755        // default.  If there's more than one, just leave everything alone.
3756        if (browserPkg == null) {
3757            calculateDefaultBrowserLPw(userId);
3758        }
3759    }
3760
3761    private void calculateDefaultBrowserLPw(int userId) {
3762        List<String> allBrowsers = resolveAllBrowserApps(userId);
3763        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3764        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3765    }
3766
3767    private List<String> resolveAllBrowserApps(int userId) {
3768        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3769        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3770                PackageManager.MATCH_ALL, userId);
3771
3772        final int count = list.size();
3773        List<String> result = new ArrayList<String>(count);
3774        for (int i=0; i<count; i++) {
3775            ResolveInfo info = list.get(i);
3776            if (info.activityInfo == null
3777                    || !info.handleAllWebDataURI
3778                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3779                    || result.contains(info.activityInfo.packageName)) {
3780                continue;
3781            }
3782            result.add(info.activityInfo.packageName);
3783        }
3784
3785        return result;
3786    }
3787
3788    private boolean packageIsBrowser(String packageName, int userId) {
3789        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3790                PackageManager.MATCH_ALL, userId);
3791        final int N = list.size();
3792        for (int i = 0; i < N; i++) {
3793            ResolveInfo info = list.get(i);
3794            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3795                return true;
3796            }
3797        }
3798        return false;
3799    }
3800
3801    private void checkDefaultBrowser() {
3802        final int myUserId = UserHandle.myUserId();
3803        final String packageName = getDefaultBrowserPackageName(myUserId);
3804        if (packageName != null) {
3805            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3806            if (info == null) {
3807                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3808                synchronized (mPackages) {
3809                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3810                }
3811            }
3812        }
3813    }
3814
3815    @Override
3816    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3817            throws RemoteException {
3818        try {
3819            return super.onTransact(code, data, reply, flags);
3820        } catch (RuntimeException e) {
3821            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3822                Slog.wtf(TAG, "Package Manager Crash", e);
3823            }
3824            throw e;
3825        }
3826    }
3827
3828    static int[] appendInts(int[] cur, int[] add) {
3829        if (add == null) return cur;
3830        if (cur == null) return add;
3831        final int N = add.length;
3832        for (int i=0; i<N; i++) {
3833            cur = appendInt(cur, add[i]);
3834        }
3835        return cur;
3836    }
3837
3838    /**
3839     * Returns whether or not a full application can see an instant application.
3840     * <p>
3841     * Currently, there are three cases in which this can occur:
3842     * <ol>
3843     * <li>The calling application is a "special" process. Special processes
3844     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3845     * <li>The calling application has the permission
3846     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3847     * <li>The calling application is the default launcher on the
3848     *     system partition.</li>
3849     * </ol>
3850     */
3851    private boolean canViewInstantApps(int callingUid, int userId) {
3852        if (callingUid < Process.FIRST_APPLICATION_UID) {
3853            return true;
3854        }
3855        if (mContext.checkCallingOrSelfPermission(
3856                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3857            return true;
3858        }
3859        if (mContext.checkCallingOrSelfPermission(
3860                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3861            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3862            if (homeComponent != null
3863                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3864                return true;
3865            }
3866        }
3867        return false;
3868    }
3869
3870    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3871        if (!sUserManager.exists(userId)) return null;
3872        if (ps == null) {
3873            return null;
3874        }
3875        final int callingUid = Binder.getCallingUid();
3876        // Filter out ephemeral app metadata:
3877        //   * The system/shell/root can see metadata for any app
3878        //   * An installed app can see metadata for 1) other installed apps
3879        //     and 2) ephemeral apps that have explicitly interacted with it
3880        //   * Ephemeral apps can only see their own data and exposed installed apps
3881        //   * Holding a signature permission allows seeing instant apps
3882        if (filterAppAccessLPr(ps, callingUid, userId)) {
3883            return null;
3884        }
3885
3886        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3887                && ps.isSystem()) {
3888            flags |= MATCH_ANY_USER;
3889        }
3890
3891        final PackageUserState state = ps.readUserState(userId);
3892        PackageParser.Package p = ps.pkg;
3893        if (p != null) {
3894            final PermissionsState permissionsState = ps.getPermissionsState();
3895
3896            // Compute GIDs only if requested
3897            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3898                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3899            // Compute granted permissions only if package has requested permissions
3900            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3901                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3902
3903            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3904                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3905
3906            if (packageInfo == null) {
3907                return null;
3908            }
3909
3910            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3911                    resolveExternalPackageNameLPr(p);
3912
3913            return packageInfo;
3914        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3915            PackageInfo pi = new PackageInfo();
3916            pi.packageName = ps.name;
3917            pi.setLongVersionCode(ps.versionCode);
3918            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3919            pi.firstInstallTime = ps.firstInstallTime;
3920            pi.lastUpdateTime = ps.lastUpdateTime;
3921
3922            ApplicationInfo ai = new ApplicationInfo();
3923            ai.packageName = ps.name;
3924            ai.uid = UserHandle.getUid(userId, ps.appId);
3925            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3926            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3927            ai.versionCode = ps.versionCode;
3928            ai.flags = ps.pkgFlags;
3929            ai.privateFlags = ps.pkgPrivateFlags;
3930            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3931
3932            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3933                    + ps.name + "]. Provides a minimum info.");
3934            return pi;
3935        } else {
3936            return null;
3937        }
3938    }
3939
3940    @Override
3941    public void checkPackageStartable(String packageName, int userId) {
3942        final int callingUid = Binder.getCallingUid();
3943        if (getInstantAppPackageName(callingUid) != null) {
3944            throw new SecurityException("Instant applications don't have access to this method");
3945        }
3946        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3947        synchronized (mPackages) {
3948            final PackageSetting ps = mSettings.mPackages.get(packageName);
3949            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3950                throw new SecurityException("Package " + packageName + " was not found!");
3951            }
3952
3953            if (!ps.getInstalled(userId)) {
3954                throw new SecurityException(
3955                        "Package " + packageName + " was not installed for user " + userId + "!");
3956            }
3957
3958            if (mSafeMode && !ps.isSystem()) {
3959                throw new SecurityException("Package " + packageName + " not a system app!");
3960            }
3961
3962            if (mFrozenPackages.contains(packageName)) {
3963                throw new SecurityException("Package " + packageName + " is currently frozen!");
3964            }
3965
3966            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3967                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3968            }
3969        }
3970    }
3971
3972    @Override
3973    public boolean isPackageAvailable(String packageName, int userId) {
3974        if (!sUserManager.exists(userId)) return false;
3975        final int callingUid = Binder.getCallingUid();
3976        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3977                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3978        synchronized (mPackages) {
3979            PackageParser.Package p = mPackages.get(packageName);
3980            if (p != null) {
3981                final PackageSetting ps = (PackageSetting) p.mExtras;
3982                if (filterAppAccessLPr(ps, callingUid, userId)) {
3983                    return false;
3984                }
3985                if (ps != null) {
3986                    final PackageUserState state = ps.readUserState(userId);
3987                    if (state != null) {
3988                        return PackageParser.isAvailable(state);
3989                    }
3990                }
3991            }
3992        }
3993        return false;
3994    }
3995
3996    @Override
3997    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3998        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3999                flags, Binder.getCallingUid(), userId);
4000    }
4001
4002    @Override
4003    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4004            int flags, int userId) {
4005        return getPackageInfoInternal(versionedPackage.getPackageName(),
4006                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4007    }
4008
4009    /**
4010     * Important: The provided filterCallingUid is used exclusively to filter out packages
4011     * that can be seen based on user state. It's typically the original caller uid prior
4012     * to clearing. Because it can only be provided by trusted code, it's value can be
4013     * trusted and will be used as-is; unlike userId which will be validated by this method.
4014     */
4015    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4016            int flags, int filterCallingUid, int userId) {
4017        if (!sUserManager.exists(userId)) return null;
4018        flags = updateFlagsForPackage(flags, userId, packageName);
4019        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4020                false /* requireFullPermission */, false /* checkShell */, "get package info");
4021
4022        // reader
4023        synchronized (mPackages) {
4024            // Normalize package name to handle renamed packages and static libs
4025            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4026
4027            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4028            if (matchFactoryOnly) {
4029                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4030                if (ps != null) {
4031                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4032                        return null;
4033                    }
4034                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4035                        return null;
4036                    }
4037                    return generatePackageInfo(ps, flags, userId);
4038                }
4039            }
4040
4041            PackageParser.Package p = mPackages.get(packageName);
4042            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4043                return null;
4044            }
4045            if (DEBUG_PACKAGE_INFO)
4046                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4047            if (p != null) {
4048                final PackageSetting ps = (PackageSetting) p.mExtras;
4049                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4050                    return null;
4051                }
4052                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4053                    return null;
4054                }
4055                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4056            }
4057            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4058                final PackageSetting ps = mSettings.mPackages.get(packageName);
4059                if (ps == null) return null;
4060                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4061                    return null;
4062                }
4063                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4064                    return null;
4065                }
4066                return generatePackageInfo(ps, flags, userId);
4067            }
4068        }
4069        return null;
4070    }
4071
4072    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4073        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4074            return true;
4075        }
4076        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4077            return true;
4078        }
4079        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4080            return true;
4081        }
4082        return false;
4083    }
4084
4085    private boolean isComponentVisibleToInstantApp(
4086            @Nullable ComponentName component, @ComponentType int type) {
4087        if (type == TYPE_ACTIVITY) {
4088            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4089            return activity != null
4090                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4091                    : false;
4092        } else if (type == TYPE_RECEIVER) {
4093            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4094            return activity != null
4095                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4096                    : false;
4097        } else if (type == TYPE_SERVICE) {
4098            final PackageParser.Service service = mServices.mServices.get(component);
4099            return service != null
4100                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4101                    : false;
4102        } else if (type == TYPE_PROVIDER) {
4103            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4104            return provider != null
4105                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4106                    : false;
4107        } else if (type == TYPE_UNKNOWN) {
4108            return isComponentVisibleToInstantApp(component);
4109        }
4110        return false;
4111    }
4112
4113    /**
4114     * Returns whether or not access to the application should be filtered.
4115     * <p>
4116     * Access may be limited based upon whether the calling or target applications
4117     * are instant applications.
4118     *
4119     * @see #canAccessInstantApps(int)
4120     */
4121    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4122            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4123        // if we're in an isolated process, get the real calling UID
4124        if (Process.isIsolated(callingUid)) {
4125            callingUid = mIsolatedOwners.get(callingUid);
4126        }
4127        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4128        final boolean callerIsInstantApp = instantAppPkgName != null;
4129        if (ps == null) {
4130            if (callerIsInstantApp) {
4131                // pretend the application exists, but, needs to be filtered
4132                return true;
4133            }
4134            return false;
4135        }
4136        // if the target and caller are the same application, don't filter
4137        if (isCallerSameApp(ps.name, callingUid)) {
4138            return false;
4139        }
4140        if (callerIsInstantApp) {
4141            // request for a specific component; if it hasn't been explicitly exposed through
4142            // property or instrumentation target, filter
4143            if (component != null) {
4144                final PackageParser.Instrumentation instrumentation =
4145                        mInstrumentation.get(component);
4146                if (instrumentation != null
4147                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4148                    return false;
4149                }
4150                return !isComponentVisibleToInstantApp(component, componentType);
4151            }
4152            // request for application; if no components have been explicitly exposed, filter
4153            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4154        }
4155        if (ps.getInstantApp(userId)) {
4156            // caller can see all components of all instant applications, don't filter
4157            if (canViewInstantApps(callingUid, userId)) {
4158                return false;
4159            }
4160            // request for a specific instant application component, filter
4161            if (component != null) {
4162                return true;
4163            }
4164            // request for an instant application; if the caller hasn't been granted access, filter
4165            return !mInstantAppRegistry.isInstantAccessGranted(
4166                    userId, UserHandle.getAppId(callingUid), ps.appId);
4167        }
4168        return false;
4169    }
4170
4171    /**
4172     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4173     */
4174    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4175        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4176    }
4177
4178    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4179            int flags) {
4180        // Callers can access only the libs they depend on, otherwise they need to explicitly
4181        // ask for the shared libraries given the caller is allowed to access all static libs.
4182        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4183            // System/shell/root get to see all static libs
4184            final int appId = UserHandle.getAppId(uid);
4185            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4186                    || appId == Process.ROOT_UID) {
4187                return false;
4188            }
4189        }
4190
4191        // No package means no static lib as it is always on internal storage
4192        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4193            return false;
4194        }
4195
4196        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4197                ps.pkg.staticSharedLibVersion);
4198        if (libEntry == null) {
4199            return false;
4200        }
4201
4202        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4203        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4204        if (uidPackageNames == null) {
4205            return true;
4206        }
4207
4208        for (String uidPackageName : uidPackageNames) {
4209            if (ps.name.equals(uidPackageName)) {
4210                return false;
4211            }
4212            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4213            if (uidPs != null) {
4214                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4215                        libEntry.info.getName());
4216                if (index < 0) {
4217                    continue;
4218                }
4219                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4220                    return false;
4221                }
4222            }
4223        }
4224        return true;
4225    }
4226
4227    @Override
4228    public String[] currentToCanonicalPackageNames(String[] names) {
4229        final int callingUid = Binder.getCallingUid();
4230        if (getInstantAppPackageName(callingUid) != null) {
4231            return names;
4232        }
4233        final String[] out = new String[names.length];
4234        // reader
4235        synchronized (mPackages) {
4236            final int callingUserId = UserHandle.getUserId(callingUid);
4237            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4238            for (int i=names.length-1; i>=0; i--) {
4239                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4240                boolean translateName = false;
4241                if (ps != null && ps.realName != null) {
4242                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4243                    translateName = !targetIsInstantApp
4244                            || canViewInstantApps
4245                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4246                                    UserHandle.getAppId(callingUid), ps.appId);
4247                }
4248                out[i] = translateName ? ps.realName : names[i];
4249            }
4250        }
4251        return out;
4252    }
4253
4254    @Override
4255    public String[] canonicalToCurrentPackageNames(String[] names) {
4256        final int callingUid = Binder.getCallingUid();
4257        if (getInstantAppPackageName(callingUid) != null) {
4258            return names;
4259        }
4260        final String[] out = new String[names.length];
4261        // reader
4262        synchronized (mPackages) {
4263            final int callingUserId = UserHandle.getUserId(callingUid);
4264            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4265            for (int i=names.length-1; i>=0; i--) {
4266                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4267                boolean translateName = false;
4268                if (cur != null) {
4269                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4270                    final boolean targetIsInstantApp =
4271                            ps != null && ps.getInstantApp(callingUserId);
4272                    translateName = !targetIsInstantApp
4273                            || canViewInstantApps
4274                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4275                                    UserHandle.getAppId(callingUid), ps.appId);
4276                }
4277                out[i] = translateName ? cur : names[i];
4278            }
4279        }
4280        return out;
4281    }
4282
4283    @Override
4284    public int getPackageUid(String packageName, int flags, int userId) {
4285        if (!sUserManager.exists(userId)) return -1;
4286        final int callingUid = Binder.getCallingUid();
4287        flags = updateFlagsForPackage(flags, userId, packageName);
4288        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4289                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4290
4291        // reader
4292        synchronized (mPackages) {
4293            final PackageParser.Package p = mPackages.get(packageName);
4294            if (p != null && p.isMatch(flags)) {
4295                PackageSetting ps = (PackageSetting) p.mExtras;
4296                if (filterAppAccessLPr(ps, callingUid, userId)) {
4297                    return -1;
4298                }
4299                return UserHandle.getUid(userId, p.applicationInfo.uid);
4300            }
4301            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4302                final PackageSetting ps = mSettings.mPackages.get(packageName);
4303                if (ps != null && ps.isMatch(flags)
4304                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4305                    return UserHandle.getUid(userId, ps.appId);
4306                }
4307            }
4308        }
4309
4310        return -1;
4311    }
4312
4313    @Override
4314    public int[] getPackageGids(String packageName, int flags, int userId) {
4315        if (!sUserManager.exists(userId)) return null;
4316        final int callingUid = Binder.getCallingUid();
4317        flags = updateFlagsForPackage(flags, userId, packageName);
4318        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4319                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4320
4321        // reader
4322        synchronized (mPackages) {
4323            final PackageParser.Package p = mPackages.get(packageName);
4324            if (p != null && p.isMatch(flags)) {
4325                PackageSetting ps = (PackageSetting) p.mExtras;
4326                if (filterAppAccessLPr(ps, callingUid, userId)) {
4327                    return null;
4328                }
4329                // TODO: Shouldn't this be checking for package installed state for userId and
4330                // return null?
4331                return ps.getPermissionsState().computeGids(userId);
4332            }
4333            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4334                final PackageSetting ps = mSettings.mPackages.get(packageName);
4335                if (ps != null && ps.isMatch(flags)
4336                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4337                    return ps.getPermissionsState().computeGids(userId);
4338                }
4339            }
4340        }
4341
4342        return null;
4343    }
4344
4345    @Override
4346    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4347        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4348    }
4349
4350    @Override
4351    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4352            int flags) {
4353        final List<PermissionInfo> permissionList =
4354                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4355        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4356    }
4357
4358    @Override
4359    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4360        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4361    }
4362
4363    @Override
4364    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4365        final List<PermissionGroupInfo> permissionList =
4366                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4367        return (permissionList == null)
4368                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4369    }
4370
4371    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4372            int filterCallingUid, int userId) {
4373        if (!sUserManager.exists(userId)) return null;
4374        PackageSetting ps = mSettings.mPackages.get(packageName);
4375        if (ps != null) {
4376            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4377                return null;
4378            }
4379            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4380                return null;
4381            }
4382            if (ps.pkg == null) {
4383                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4384                if (pInfo != null) {
4385                    return pInfo.applicationInfo;
4386                }
4387                return null;
4388            }
4389            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4390                    ps.readUserState(userId), userId);
4391            if (ai != null) {
4392                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4393            }
4394            return ai;
4395        }
4396        return null;
4397    }
4398
4399    @Override
4400    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4401        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4402    }
4403
4404    /**
4405     * Important: The provided filterCallingUid is used exclusively to filter out applications
4406     * that can be seen based on user state. It's typically the original caller uid prior
4407     * to clearing. Because it can only be provided by trusted code, it's value can be
4408     * trusted and will be used as-is; unlike userId which will be validated by this method.
4409     */
4410    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4411            int filterCallingUid, int userId) {
4412        if (!sUserManager.exists(userId)) return null;
4413        flags = updateFlagsForApplication(flags, userId, packageName);
4414        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4415                false /* requireFullPermission */, false /* checkShell */, "get application info");
4416
4417        // writer
4418        synchronized (mPackages) {
4419            // Normalize package name to handle renamed packages and static libs
4420            packageName = resolveInternalPackageNameLPr(packageName,
4421                    PackageManager.VERSION_CODE_HIGHEST);
4422
4423            PackageParser.Package p = mPackages.get(packageName);
4424            if (DEBUG_PACKAGE_INFO) Log.v(
4425                    TAG, "getApplicationInfo " + packageName
4426                    + ": " + p);
4427            if (p != null) {
4428                PackageSetting ps = mSettings.mPackages.get(packageName);
4429                if (ps == null) return null;
4430                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4431                    return null;
4432                }
4433                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4434                    return null;
4435                }
4436                // Note: isEnabledLP() does not apply here - always return info
4437                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4438                        p, flags, ps.readUserState(userId), userId);
4439                if (ai != null) {
4440                    ai.packageName = resolveExternalPackageNameLPr(p);
4441                }
4442                return ai;
4443            }
4444            if ("android".equals(packageName)||"system".equals(packageName)) {
4445                return mAndroidApplication;
4446            }
4447            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4448                // Already generates the external package name
4449                return generateApplicationInfoFromSettingsLPw(packageName,
4450                        flags, filterCallingUid, userId);
4451            }
4452        }
4453        return null;
4454    }
4455
4456    private String normalizePackageNameLPr(String packageName) {
4457        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4458        return normalizedPackageName != null ? normalizedPackageName : packageName;
4459    }
4460
4461    @Override
4462    public void deletePreloadsFileCache() {
4463        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4464            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4465        }
4466        File dir = Environment.getDataPreloadsFileCacheDirectory();
4467        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4468        FileUtils.deleteContents(dir);
4469    }
4470
4471    @Override
4472    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4473            final int storageFlags, final IPackageDataObserver observer) {
4474        mContext.enforceCallingOrSelfPermission(
4475                android.Manifest.permission.CLEAR_APP_CACHE, null);
4476        mHandler.post(() -> {
4477            boolean success = false;
4478            try {
4479                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4480                success = true;
4481            } catch (IOException e) {
4482                Slog.w(TAG, e);
4483            }
4484            if (observer != null) {
4485                try {
4486                    observer.onRemoveCompleted(null, success);
4487                } catch (RemoteException e) {
4488                    Slog.w(TAG, e);
4489                }
4490            }
4491        });
4492    }
4493
4494    @Override
4495    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4496            final int storageFlags, final IntentSender pi) {
4497        mContext.enforceCallingOrSelfPermission(
4498                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4499        mHandler.post(() -> {
4500            boolean success = false;
4501            try {
4502                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4503                success = true;
4504            } catch (IOException e) {
4505                Slog.w(TAG, e);
4506            }
4507            if (pi != null) {
4508                try {
4509                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4510                } catch (SendIntentException e) {
4511                    Slog.w(TAG, e);
4512                }
4513            }
4514        });
4515    }
4516
4517    /**
4518     * Blocking call to clear various types of cached data across the system
4519     * until the requested bytes are available.
4520     */
4521    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4522        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4523        final File file = storage.findPathForUuid(volumeUuid);
4524        if (file.getUsableSpace() >= bytes) return;
4525
4526        if (ENABLE_FREE_CACHE_V2) {
4527            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4528                    volumeUuid);
4529            final boolean aggressive = (storageFlags
4530                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4531            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4532
4533            // 1. Pre-flight to determine if we have any chance to succeed
4534            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4535            if (internalVolume && (aggressive || SystemProperties
4536                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4537                deletePreloadsFileCache();
4538                if (file.getUsableSpace() >= bytes) return;
4539            }
4540
4541            // 3. Consider parsed APK data (aggressive only)
4542            if (internalVolume && aggressive) {
4543                FileUtils.deleteContents(mCacheDir);
4544                if (file.getUsableSpace() >= bytes) return;
4545            }
4546
4547            // 4. Consider cached app data (above quotas)
4548            try {
4549                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4550                        Installer.FLAG_FREE_CACHE_V2);
4551            } catch (InstallerException ignored) {
4552            }
4553            if (file.getUsableSpace() >= bytes) return;
4554
4555            // 5. Consider shared libraries with refcount=0 and age>min cache period
4556            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4557                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4558                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4559                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4560                return;
4561            }
4562
4563            // 6. Consider dexopt output (aggressive only)
4564            // TODO: Implement
4565
4566            // 7. Consider installed instant apps unused longer than min cache period
4567            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4568                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4569                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4570                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4571                return;
4572            }
4573
4574            // 8. Consider cached app data (below quotas)
4575            try {
4576                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4577                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4578            } catch (InstallerException ignored) {
4579            }
4580            if (file.getUsableSpace() >= bytes) return;
4581
4582            // 9. Consider DropBox entries
4583            // TODO: Implement
4584
4585            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4586            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4587                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4588                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4589                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4590                return;
4591            }
4592        } else {
4593            try {
4594                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4595            } catch (InstallerException ignored) {
4596            }
4597            if (file.getUsableSpace() >= bytes) return;
4598        }
4599
4600        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4601    }
4602
4603    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4604            throws IOException {
4605        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4606        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4607
4608        List<VersionedPackage> packagesToDelete = null;
4609        final long now = System.currentTimeMillis();
4610
4611        synchronized (mPackages) {
4612            final int[] allUsers = sUserManager.getUserIds();
4613            final int libCount = mSharedLibraries.size();
4614            for (int i = 0; i < libCount; i++) {
4615                final LongSparseArray<SharedLibraryEntry> versionedLib
4616                        = mSharedLibraries.valueAt(i);
4617                if (versionedLib == null) {
4618                    continue;
4619                }
4620                final int versionCount = versionedLib.size();
4621                for (int j = 0; j < versionCount; j++) {
4622                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4623                    // Skip packages that are not static shared libs.
4624                    if (!libInfo.isStatic()) {
4625                        break;
4626                    }
4627                    // Important: We skip static shared libs used for some user since
4628                    // in such a case we need to keep the APK on the device. The check for
4629                    // a lib being used for any user is performed by the uninstall call.
4630                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4631                    // Resolve the package name - we use synthetic package names internally
4632                    final String internalPackageName = resolveInternalPackageNameLPr(
4633                            declaringPackage.getPackageName(),
4634                            declaringPackage.getLongVersionCode());
4635                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4636                    // Skip unused static shared libs cached less than the min period
4637                    // to prevent pruning a lib needed by a subsequently installed package.
4638                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4639                        continue;
4640                    }
4641                    if (packagesToDelete == null) {
4642                        packagesToDelete = new ArrayList<>();
4643                    }
4644                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4645                            declaringPackage.getLongVersionCode()));
4646                }
4647            }
4648        }
4649
4650        if (packagesToDelete != null) {
4651            final int packageCount = packagesToDelete.size();
4652            for (int i = 0; i < packageCount; i++) {
4653                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4654                // Delete the package synchronously (will fail of the lib used for any user).
4655                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4656                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4657                                == PackageManager.DELETE_SUCCEEDED) {
4658                    if (volume.getUsableSpace() >= neededSpace) {
4659                        return true;
4660                    }
4661                }
4662            }
4663        }
4664
4665        return false;
4666    }
4667
4668    /**
4669     * Update given flags based on encryption status of current user.
4670     */
4671    private int updateFlags(int flags, int userId) {
4672        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4673                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4674            // Caller expressed an explicit opinion about what encryption
4675            // aware/unaware components they want to see, so fall through and
4676            // give them what they want
4677        } else {
4678            // Caller expressed no opinion, so match based on user state
4679            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4680                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4681            } else {
4682                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4683            }
4684        }
4685        return flags;
4686    }
4687
4688    private UserManagerInternal getUserManagerInternal() {
4689        if (mUserManagerInternal == null) {
4690            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4691        }
4692        return mUserManagerInternal;
4693    }
4694
4695    private ActivityManagerInternal getActivityManagerInternal() {
4696        if (mActivityManagerInternal == null) {
4697            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4698        }
4699        return mActivityManagerInternal;
4700    }
4701
4702
4703    private DeviceIdleController.LocalService getDeviceIdleController() {
4704        if (mDeviceIdleController == null) {
4705            mDeviceIdleController =
4706                    LocalServices.getService(DeviceIdleController.LocalService.class);
4707        }
4708        return mDeviceIdleController;
4709    }
4710
4711    /**
4712     * Update given flags when being used to request {@link PackageInfo}.
4713     */
4714    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4715        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4716        boolean triaged = true;
4717        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4718                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4719            // Caller is asking for component details, so they'd better be
4720            // asking for specific encryption matching behavior, or be triaged
4721            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4722                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4723                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4724                triaged = false;
4725            }
4726        }
4727        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4728                | PackageManager.MATCH_SYSTEM_ONLY
4729                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4730            triaged = false;
4731        }
4732        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4733            mPermissionManager.enforceCrossUserPermission(
4734                    Binder.getCallingUid(), userId, false, false,
4735                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4736                    + Debug.getCallers(5));
4737        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4738                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4739            // If the caller wants all packages and has a restricted profile associated with it,
4740            // then match all users. This is to make sure that launchers that need to access work
4741            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4742            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4743            flags |= PackageManager.MATCH_ANY_USER;
4744        }
4745        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4746            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4747                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4748        }
4749        return updateFlags(flags, userId);
4750    }
4751
4752    /**
4753     * Update given flags when being used to request {@link ApplicationInfo}.
4754     */
4755    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4756        return updateFlagsForPackage(flags, userId, cookie);
4757    }
4758
4759    /**
4760     * Update given flags when being used to request {@link ComponentInfo}.
4761     */
4762    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4763        if (cookie instanceof Intent) {
4764            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4765                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4766            }
4767        }
4768
4769        boolean triaged = true;
4770        // Caller is asking for component details, so they'd better be
4771        // asking for specific encryption matching behavior, or be triaged
4772        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4773                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4774                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4775            triaged = false;
4776        }
4777        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4778            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4779                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4780        }
4781
4782        return updateFlags(flags, userId);
4783    }
4784
4785    /**
4786     * Update given intent when being used to request {@link ResolveInfo}.
4787     */
4788    private Intent updateIntentForResolve(Intent intent) {
4789        if (intent.getSelector() != null) {
4790            intent = intent.getSelector();
4791        }
4792        if (DEBUG_PREFERRED) {
4793            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4794        }
4795        return intent;
4796    }
4797
4798    /**
4799     * Update given flags when being used to request {@link ResolveInfo}.
4800     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4801     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4802     * flag set. However, this flag is only honoured in three circumstances:
4803     * <ul>
4804     * <li>when called from a system process</li>
4805     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4806     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4807     * action and a {@code android.intent.category.BROWSABLE} category</li>
4808     * </ul>
4809     */
4810    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4811        return updateFlagsForResolve(flags, userId, intent, callingUid,
4812                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4813    }
4814    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4815            boolean wantInstantApps) {
4816        return updateFlagsForResolve(flags, userId, intent, callingUid,
4817                wantInstantApps, false /*onlyExposedExplicitly*/);
4818    }
4819    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4820            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4821        // Safe mode means we shouldn't match any third-party components
4822        if (mSafeMode) {
4823            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4824        }
4825        if (getInstantAppPackageName(callingUid) != null) {
4826            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4827            if (onlyExposedExplicitly) {
4828                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4829            }
4830            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4831            flags |= PackageManager.MATCH_INSTANT;
4832        } else {
4833            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4834            final boolean allowMatchInstant = wantInstantApps
4835                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4836            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4837                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4838            if (!allowMatchInstant) {
4839                flags &= ~PackageManager.MATCH_INSTANT;
4840            }
4841        }
4842        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4843    }
4844
4845    @Override
4846    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4847        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4848    }
4849
4850    /**
4851     * Important: The provided filterCallingUid is used exclusively to filter out activities
4852     * that can be seen based on user state. It's typically the original caller uid prior
4853     * to clearing. Because it can only be provided by trusted code, it's value can be
4854     * trusted and will be used as-is; unlike userId which will be validated by this method.
4855     */
4856    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4857            int filterCallingUid, int userId) {
4858        if (!sUserManager.exists(userId)) return null;
4859        flags = updateFlagsForComponent(flags, userId, component);
4860
4861        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4862            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4863                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4864        }
4865
4866        synchronized (mPackages) {
4867            PackageParser.Activity a = mActivities.mActivities.get(component);
4868
4869            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4870            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4871                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4872                if (ps == null) return null;
4873                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4874                    return null;
4875                }
4876                return PackageParser.generateActivityInfo(
4877                        a, flags, ps.readUserState(userId), userId);
4878            }
4879            if (mResolveComponentName.equals(component)) {
4880                return PackageParser.generateActivityInfo(
4881                        mResolveActivity, flags, new PackageUserState(), userId);
4882            }
4883        }
4884        return null;
4885    }
4886
4887    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4888        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4889            return false;
4890        }
4891        final long token = Binder.clearCallingIdentity();
4892        try {
4893            final int callingUserId = UserHandle.getUserId(callingUid);
4894            if (ActivityManager.getCurrentUser() != callingUserId) {
4895                return false;
4896            }
4897            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4898        } finally {
4899            Binder.restoreCallingIdentity(token);
4900        }
4901    }
4902
4903    @Override
4904    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4905            String resolvedType) {
4906        synchronized (mPackages) {
4907            if (component.equals(mResolveComponentName)) {
4908                // The resolver supports EVERYTHING!
4909                return true;
4910            }
4911            final int callingUid = Binder.getCallingUid();
4912            final int callingUserId = UserHandle.getUserId(callingUid);
4913            PackageParser.Activity a = mActivities.mActivities.get(component);
4914            if (a == null) {
4915                return false;
4916            }
4917            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4918            if (ps == null) {
4919                return false;
4920            }
4921            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4922                return false;
4923            }
4924            for (int i=0; i<a.intents.size(); i++) {
4925                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4926                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4927                    return true;
4928                }
4929            }
4930            return false;
4931        }
4932    }
4933
4934    @Override
4935    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4936        if (!sUserManager.exists(userId)) return null;
4937        final int callingUid = Binder.getCallingUid();
4938        flags = updateFlagsForComponent(flags, userId, component);
4939        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4940                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4941        synchronized (mPackages) {
4942            PackageParser.Activity a = mReceivers.mActivities.get(component);
4943            if (DEBUG_PACKAGE_INFO) Log.v(
4944                TAG, "getReceiverInfo " + component + ": " + a);
4945            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4946                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4947                if (ps == null) return null;
4948                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4949                    return null;
4950                }
4951                return PackageParser.generateActivityInfo(
4952                        a, flags, ps.readUserState(userId), userId);
4953            }
4954        }
4955        return null;
4956    }
4957
4958    @Override
4959    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4960            int flags, int userId) {
4961        if (!sUserManager.exists(userId)) return null;
4962        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4963        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4964            return null;
4965        }
4966
4967        flags = updateFlagsForPackage(flags, userId, null);
4968
4969        final boolean canSeeStaticLibraries =
4970                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4971                        == PERMISSION_GRANTED
4972                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4973                        == PERMISSION_GRANTED
4974                || canRequestPackageInstallsInternal(packageName,
4975                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4976                        false  /* throwIfPermNotDeclared*/)
4977                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4978                        == PERMISSION_GRANTED;
4979
4980        synchronized (mPackages) {
4981            List<SharedLibraryInfo> result = null;
4982
4983            final int libCount = mSharedLibraries.size();
4984            for (int i = 0; i < libCount; i++) {
4985                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4986                if (versionedLib == null) {
4987                    continue;
4988                }
4989
4990                final int versionCount = versionedLib.size();
4991                for (int j = 0; j < versionCount; j++) {
4992                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4993                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4994                        break;
4995                    }
4996                    final long identity = Binder.clearCallingIdentity();
4997                    try {
4998                        PackageInfo packageInfo = getPackageInfoVersioned(
4999                                libInfo.getDeclaringPackage(), flags
5000                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5001                        if (packageInfo == null) {
5002                            continue;
5003                        }
5004                    } finally {
5005                        Binder.restoreCallingIdentity(identity);
5006                    }
5007
5008                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5009                            libInfo.getLongVersion(), libInfo.getType(),
5010                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5011                            flags, userId));
5012
5013                    if (result == null) {
5014                        result = new ArrayList<>();
5015                    }
5016                    result.add(resLibInfo);
5017                }
5018            }
5019
5020            return result != null ? new ParceledListSlice<>(result) : null;
5021        }
5022    }
5023
5024    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5025            SharedLibraryInfo libInfo, int flags, int userId) {
5026        List<VersionedPackage> versionedPackages = null;
5027        final int packageCount = mSettings.mPackages.size();
5028        for (int i = 0; i < packageCount; i++) {
5029            PackageSetting ps = mSettings.mPackages.valueAt(i);
5030
5031            if (ps == null) {
5032                continue;
5033            }
5034
5035            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5036                continue;
5037            }
5038
5039            final String libName = libInfo.getName();
5040            if (libInfo.isStatic()) {
5041                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5042                if (libIdx < 0) {
5043                    continue;
5044                }
5045                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5046                    continue;
5047                }
5048                if (versionedPackages == null) {
5049                    versionedPackages = new ArrayList<>();
5050                }
5051                // If the dependent is a static shared lib, use the public package name
5052                String dependentPackageName = ps.name;
5053                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5054                    dependentPackageName = ps.pkg.manifestPackageName;
5055                }
5056                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5057            } else if (ps.pkg != null) {
5058                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5059                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5060                    if (versionedPackages == null) {
5061                        versionedPackages = new ArrayList<>();
5062                    }
5063                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5064                }
5065            }
5066        }
5067
5068        return versionedPackages;
5069    }
5070
5071    @Override
5072    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5073        if (!sUserManager.exists(userId)) return null;
5074        final int callingUid = Binder.getCallingUid();
5075        flags = updateFlagsForComponent(flags, userId, component);
5076        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5077                false /* requireFullPermission */, false /* checkShell */, "get service info");
5078        synchronized (mPackages) {
5079            PackageParser.Service s = mServices.mServices.get(component);
5080            if (DEBUG_PACKAGE_INFO) Log.v(
5081                TAG, "getServiceInfo " + component + ": " + s);
5082            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5083                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5084                if (ps == null) return null;
5085                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5086                    return null;
5087                }
5088                return PackageParser.generateServiceInfo(
5089                        s, flags, ps.readUserState(userId), userId);
5090            }
5091        }
5092        return null;
5093    }
5094
5095    @Override
5096    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5097        if (!sUserManager.exists(userId)) return null;
5098        final int callingUid = Binder.getCallingUid();
5099        flags = updateFlagsForComponent(flags, userId, component);
5100        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5101                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5102        synchronized (mPackages) {
5103            PackageParser.Provider p = mProviders.mProviders.get(component);
5104            if (DEBUG_PACKAGE_INFO) Log.v(
5105                TAG, "getProviderInfo " + component + ": " + p);
5106            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5107                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5108                if (ps == null) return null;
5109                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5110                    return null;
5111                }
5112                return PackageParser.generateProviderInfo(
5113                        p, flags, ps.readUserState(userId), userId);
5114            }
5115        }
5116        return null;
5117    }
5118
5119    @Override
5120    public String[] getSystemSharedLibraryNames() {
5121        // allow instant applications
5122        synchronized (mPackages) {
5123            Set<String> libs = null;
5124            final int libCount = mSharedLibraries.size();
5125            for (int i = 0; i < libCount; i++) {
5126                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5127                if (versionedLib == null) {
5128                    continue;
5129                }
5130                final int versionCount = versionedLib.size();
5131                for (int j = 0; j < versionCount; j++) {
5132                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5133                    if (!libEntry.info.isStatic()) {
5134                        if (libs == null) {
5135                            libs = new ArraySet<>();
5136                        }
5137                        libs.add(libEntry.info.getName());
5138                        break;
5139                    }
5140                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5141                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5142                            UserHandle.getUserId(Binder.getCallingUid()),
5143                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5144                        if (libs == null) {
5145                            libs = new ArraySet<>();
5146                        }
5147                        libs.add(libEntry.info.getName());
5148                        break;
5149                    }
5150                }
5151            }
5152
5153            if (libs != null) {
5154                String[] libsArray = new String[libs.size()];
5155                libs.toArray(libsArray);
5156                return libsArray;
5157            }
5158
5159            return null;
5160        }
5161    }
5162
5163    @Override
5164    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5165        // allow instant applications
5166        synchronized (mPackages) {
5167            return mServicesSystemSharedLibraryPackageName;
5168        }
5169    }
5170
5171    @Override
5172    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5173        // allow instant applications
5174        synchronized (mPackages) {
5175            return mSharedSystemSharedLibraryPackageName;
5176        }
5177    }
5178
5179    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5180        for (int i = userList.length - 1; i >= 0; --i) {
5181            final int userId = userList[i];
5182            // don't add instant app to the list of updates
5183            if (pkgSetting.getInstantApp(userId)) {
5184                continue;
5185            }
5186            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5187            if (changedPackages == null) {
5188                changedPackages = new SparseArray<>();
5189                mChangedPackages.put(userId, changedPackages);
5190            }
5191            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5192            if (sequenceNumbers == null) {
5193                sequenceNumbers = new HashMap<>();
5194                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5195            }
5196            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5197            if (sequenceNumber != null) {
5198                changedPackages.remove(sequenceNumber);
5199            }
5200            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5201            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5202        }
5203        mChangedPackagesSequenceNumber++;
5204    }
5205
5206    @Override
5207    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5208        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5209            return null;
5210        }
5211        synchronized (mPackages) {
5212            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5213                return null;
5214            }
5215            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5216            if (changedPackages == null) {
5217                return null;
5218            }
5219            final List<String> packageNames =
5220                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5221            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5222                final String packageName = changedPackages.get(i);
5223                if (packageName != null) {
5224                    packageNames.add(packageName);
5225                }
5226            }
5227            return packageNames.isEmpty()
5228                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5229        }
5230    }
5231
5232    @Override
5233    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5234        // allow instant applications
5235        ArrayList<FeatureInfo> res;
5236        synchronized (mAvailableFeatures) {
5237            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5238            res.addAll(mAvailableFeatures.values());
5239        }
5240        final FeatureInfo fi = new FeatureInfo();
5241        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5242                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5243        res.add(fi);
5244
5245        return new ParceledListSlice<>(res);
5246    }
5247
5248    @Override
5249    public boolean hasSystemFeature(String name, int version) {
5250        // allow instant applications
5251        synchronized (mAvailableFeatures) {
5252            final FeatureInfo feat = mAvailableFeatures.get(name);
5253            if (feat == null) {
5254                return false;
5255            } else {
5256                return feat.version >= version;
5257            }
5258        }
5259    }
5260
5261    @Override
5262    public int checkPermission(String permName, String pkgName, int userId) {
5263        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5264    }
5265
5266    @Override
5267    public int checkUidPermission(String permName, int uid) {
5268        synchronized (mPackages) {
5269            final String[] packageNames = getPackagesForUid(uid);
5270            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5271                    ? mPackages.get(packageNames[0])
5272                    : null;
5273            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5274        }
5275    }
5276
5277    @Override
5278    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5279        if (UserHandle.getCallingUserId() != userId) {
5280            mContext.enforceCallingPermission(
5281                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5282                    "isPermissionRevokedByPolicy for user " + userId);
5283        }
5284
5285        if (checkPermission(permission, packageName, userId)
5286                == PackageManager.PERMISSION_GRANTED) {
5287            return false;
5288        }
5289
5290        final int callingUid = Binder.getCallingUid();
5291        if (getInstantAppPackageName(callingUid) != null) {
5292            if (!isCallerSameApp(packageName, callingUid)) {
5293                return false;
5294            }
5295        } else {
5296            if (isInstantApp(packageName, userId)) {
5297                return false;
5298            }
5299        }
5300
5301        final long identity = Binder.clearCallingIdentity();
5302        try {
5303            final int flags = getPermissionFlags(permission, packageName, userId);
5304            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5305        } finally {
5306            Binder.restoreCallingIdentity(identity);
5307        }
5308    }
5309
5310    @Override
5311    public String getPermissionControllerPackageName() {
5312        synchronized (mPackages) {
5313            return mRequiredInstallerPackage;
5314        }
5315    }
5316
5317    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5318        return mPermissionManager.addDynamicPermission(
5319                info, async, getCallingUid(), new PermissionCallback() {
5320                    @Override
5321                    public void onPermissionChanged() {
5322                        if (!async) {
5323                            mSettings.writeLPr();
5324                        } else {
5325                            scheduleWriteSettingsLocked();
5326                        }
5327                    }
5328                });
5329    }
5330
5331    @Override
5332    public boolean addPermission(PermissionInfo info) {
5333        synchronized (mPackages) {
5334            return addDynamicPermission(info, false);
5335        }
5336    }
5337
5338    @Override
5339    public boolean addPermissionAsync(PermissionInfo info) {
5340        synchronized (mPackages) {
5341            return addDynamicPermission(info, true);
5342        }
5343    }
5344
5345    @Override
5346    public void removePermission(String permName) {
5347        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5348    }
5349
5350    @Override
5351    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5352        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5353                getCallingUid(), userId, mPermissionCallback);
5354    }
5355
5356    @Override
5357    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5358        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5359                getCallingUid(), userId, mPermissionCallback);
5360    }
5361
5362    @Override
5363    public void resetRuntimePermissions() {
5364        mContext.enforceCallingOrSelfPermission(
5365                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5366                "revokeRuntimePermission");
5367
5368        int callingUid = Binder.getCallingUid();
5369        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5370            mContext.enforceCallingOrSelfPermission(
5371                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5372                    "resetRuntimePermissions");
5373        }
5374
5375        synchronized (mPackages) {
5376            mPermissionManager.updateAllPermissions(
5377                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5378                    mPermissionCallback);
5379            for (int userId : UserManagerService.getInstance().getUserIds()) {
5380                final int packageCount = mPackages.size();
5381                for (int i = 0; i < packageCount; i++) {
5382                    PackageParser.Package pkg = mPackages.valueAt(i);
5383                    if (!(pkg.mExtras instanceof PackageSetting)) {
5384                        continue;
5385                    }
5386                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5387                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5388                }
5389            }
5390        }
5391    }
5392
5393    @Override
5394    public int getPermissionFlags(String permName, String packageName, int userId) {
5395        return mPermissionManager.getPermissionFlags(
5396                permName, packageName, getCallingUid(), userId);
5397    }
5398
5399    @Override
5400    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5401            int flagValues, int userId) {
5402        mPermissionManager.updatePermissionFlags(
5403                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5404                mPermissionCallback);
5405    }
5406
5407    /**
5408     * Update the permission flags for all packages and runtime permissions of a user in order
5409     * to allow device or profile owner to remove POLICY_FIXED.
5410     */
5411    @Override
5412    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5413        synchronized (mPackages) {
5414            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5415                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5416                    mPermissionCallback);
5417            if (changed) {
5418                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5419            }
5420        }
5421    }
5422
5423    @Override
5424    public boolean shouldShowRequestPermissionRationale(String permissionName,
5425            String packageName, int userId) {
5426        if (UserHandle.getCallingUserId() != userId) {
5427            mContext.enforceCallingPermission(
5428                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5429                    "canShowRequestPermissionRationale for user " + userId);
5430        }
5431
5432        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5433        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5434            return false;
5435        }
5436
5437        if (checkPermission(permissionName, packageName, userId)
5438                == PackageManager.PERMISSION_GRANTED) {
5439            return false;
5440        }
5441
5442        final int flags;
5443
5444        final long identity = Binder.clearCallingIdentity();
5445        try {
5446            flags = getPermissionFlags(permissionName,
5447                    packageName, userId);
5448        } finally {
5449            Binder.restoreCallingIdentity(identity);
5450        }
5451
5452        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5453                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5454                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5455
5456        if ((flags & fixedFlags) != 0) {
5457            return false;
5458        }
5459
5460        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5461    }
5462
5463    @Override
5464    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5465        mContext.enforceCallingOrSelfPermission(
5466                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5467                "addOnPermissionsChangeListener");
5468
5469        synchronized (mPackages) {
5470            mOnPermissionChangeListeners.addListenerLocked(listener);
5471        }
5472    }
5473
5474    @Override
5475    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5476        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5477            throw new SecurityException("Instant applications don't have access to this method");
5478        }
5479        synchronized (mPackages) {
5480            mOnPermissionChangeListeners.removeListenerLocked(listener);
5481        }
5482    }
5483
5484    @Override
5485    public boolean isProtectedBroadcast(String actionName) {
5486        // allow instant applications
5487        synchronized (mProtectedBroadcasts) {
5488            if (mProtectedBroadcasts.contains(actionName)) {
5489                return true;
5490            } else if (actionName != null) {
5491                // TODO: remove these terrible hacks
5492                if (actionName.startsWith("android.net.netmon.lingerExpired")
5493                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5494                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5495                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5496                    return true;
5497                }
5498            }
5499        }
5500        return false;
5501    }
5502
5503    @Override
5504    public int checkSignatures(String pkg1, String pkg2) {
5505        synchronized (mPackages) {
5506            final PackageParser.Package p1 = mPackages.get(pkg1);
5507            final PackageParser.Package p2 = mPackages.get(pkg2);
5508            if (p1 == null || p1.mExtras == null
5509                    || p2 == null || p2.mExtras == null) {
5510                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5511            }
5512            final int callingUid = Binder.getCallingUid();
5513            final int callingUserId = UserHandle.getUserId(callingUid);
5514            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5515            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5516            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5517                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5518                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5519            }
5520            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5521        }
5522    }
5523
5524    @Override
5525    public int checkUidSignatures(int uid1, int uid2) {
5526        final int callingUid = Binder.getCallingUid();
5527        final int callingUserId = UserHandle.getUserId(callingUid);
5528        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5529        // Map to base uids.
5530        uid1 = UserHandle.getAppId(uid1);
5531        uid2 = UserHandle.getAppId(uid2);
5532        // reader
5533        synchronized (mPackages) {
5534            Signature[] s1;
5535            Signature[] s2;
5536            Object obj = mSettings.getUserIdLPr(uid1);
5537            if (obj != null) {
5538                if (obj instanceof SharedUserSetting) {
5539                    if (isCallerInstantApp) {
5540                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5541                    }
5542                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5543                } else if (obj instanceof PackageSetting) {
5544                    final PackageSetting ps = (PackageSetting) obj;
5545                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5546                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5547                    }
5548                    s1 = ps.signatures.mSigningDetails.signatures;
5549                } else {
5550                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5551                }
5552            } else {
5553                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5554            }
5555            obj = mSettings.getUserIdLPr(uid2);
5556            if (obj != null) {
5557                if (obj instanceof SharedUserSetting) {
5558                    if (isCallerInstantApp) {
5559                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5560                    }
5561                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5562                } else if (obj instanceof PackageSetting) {
5563                    final PackageSetting ps = (PackageSetting) obj;
5564                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5565                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5566                    }
5567                    s2 = ps.signatures.mSigningDetails.signatures;
5568                } else {
5569                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5570                }
5571            } else {
5572                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5573            }
5574            return compareSignatures(s1, s2);
5575        }
5576    }
5577
5578    @Override
5579    public boolean hasSigningCertificate(
5580            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5581
5582        synchronized (mPackages) {
5583            final PackageParser.Package p = mPackages.get(packageName);
5584            if (p == null || p.mExtras == null) {
5585                return false;
5586            }
5587            final int callingUid = Binder.getCallingUid();
5588            final int callingUserId = UserHandle.getUserId(callingUid);
5589            final PackageSetting ps = (PackageSetting) p.mExtras;
5590            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5591                return false;
5592            }
5593            switch (type) {
5594                case CERT_INPUT_RAW_X509:
5595                    return p.mSigningDetails.hasCertificate(certificate);
5596                case CERT_INPUT_SHA256:
5597                    return p.mSigningDetails.hasSha256Certificate(certificate);
5598                default:
5599                    return false;
5600            }
5601        }
5602    }
5603
5604    @Override
5605    public boolean hasUidSigningCertificate(
5606            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5607        final int callingUid = Binder.getCallingUid();
5608        final int callingUserId = UserHandle.getUserId(callingUid);
5609        // Map to base uids.
5610        uid = UserHandle.getAppId(uid);
5611        // reader
5612        synchronized (mPackages) {
5613            final PackageParser.SigningDetails signingDetails;
5614            final Object obj = mSettings.getUserIdLPr(uid);
5615            if (obj != null) {
5616                if (obj instanceof SharedUserSetting) {
5617                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5618                    if (isCallerInstantApp) {
5619                        return false;
5620                    }
5621                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5622                } else if (obj instanceof PackageSetting) {
5623                    final PackageSetting ps = (PackageSetting) obj;
5624                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5625                        return false;
5626                    }
5627                    signingDetails = ps.signatures.mSigningDetails;
5628                } else {
5629                    return false;
5630                }
5631            } else {
5632                return false;
5633            }
5634            switch (type) {
5635                case CERT_INPUT_RAW_X509:
5636                    return signingDetails.hasCertificate(certificate);
5637                case CERT_INPUT_SHA256:
5638                    return signingDetails.hasSha256Certificate(certificate);
5639                default:
5640                    return false;
5641            }
5642        }
5643    }
5644
5645    /**
5646     * This method should typically only be used when granting or revoking
5647     * permissions, since the app may immediately restart after this call.
5648     * <p>
5649     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5650     * guard your work against the app being relaunched.
5651     */
5652    private void killUid(int appId, int userId, String reason) {
5653        final long identity = Binder.clearCallingIdentity();
5654        try {
5655            IActivityManager am = ActivityManager.getService();
5656            if (am != null) {
5657                try {
5658                    am.killUid(appId, userId, reason);
5659                } catch (RemoteException e) {
5660                    /* ignore - same process */
5661                }
5662            }
5663        } finally {
5664            Binder.restoreCallingIdentity(identity);
5665        }
5666    }
5667
5668    /**
5669     * If the database version for this type of package (internal storage or
5670     * external storage) is less than the version where package signatures
5671     * were updated, return true.
5672     */
5673    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5674        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5675        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5676    }
5677
5678    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5679        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5680        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5681    }
5682
5683    @Override
5684    public List<String> getAllPackages() {
5685        final int callingUid = Binder.getCallingUid();
5686        final int callingUserId = UserHandle.getUserId(callingUid);
5687        synchronized (mPackages) {
5688            if (canViewInstantApps(callingUid, callingUserId)) {
5689                return new ArrayList<String>(mPackages.keySet());
5690            }
5691            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5692            final List<String> result = new ArrayList<>();
5693            if (instantAppPkgName != null) {
5694                // caller is an instant application; filter unexposed applications
5695                for (PackageParser.Package pkg : mPackages.values()) {
5696                    if (!pkg.visibleToInstantApps) {
5697                        continue;
5698                    }
5699                    result.add(pkg.packageName);
5700                }
5701            } else {
5702                // caller is a normal application; filter instant applications
5703                for (PackageParser.Package pkg : mPackages.values()) {
5704                    final PackageSetting ps =
5705                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5706                    if (ps != null
5707                            && ps.getInstantApp(callingUserId)
5708                            && !mInstantAppRegistry.isInstantAccessGranted(
5709                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5710                        continue;
5711                    }
5712                    result.add(pkg.packageName);
5713                }
5714            }
5715            return result;
5716        }
5717    }
5718
5719    @Override
5720    public String[] getPackagesForUid(int uid) {
5721        final int callingUid = Binder.getCallingUid();
5722        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5723        final int userId = UserHandle.getUserId(uid);
5724        uid = UserHandle.getAppId(uid);
5725        // reader
5726        synchronized (mPackages) {
5727            Object obj = mSettings.getUserIdLPr(uid);
5728            if (obj instanceof SharedUserSetting) {
5729                if (isCallerInstantApp) {
5730                    return null;
5731                }
5732                final SharedUserSetting sus = (SharedUserSetting) obj;
5733                final int N = sus.packages.size();
5734                String[] res = new String[N];
5735                final Iterator<PackageSetting> it = sus.packages.iterator();
5736                int i = 0;
5737                while (it.hasNext()) {
5738                    PackageSetting ps = it.next();
5739                    if (ps.getInstalled(userId)) {
5740                        res[i++] = ps.name;
5741                    } else {
5742                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5743                    }
5744                }
5745                return res;
5746            } else if (obj instanceof PackageSetting) {
5747                final PackageSetting ps = (PackageSetting) obj;
5748                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5749                    return new String[]{ps.name};
5750                }
5751            }
5752        }
5753        return null;
5754    }
5755
5756    @Override
5757    public String getNameForUid(int uid) {
5758        final int callingUid = Binder.getCallingUid();
5759        if (getInstantAppPackageName(callingUid) != null) {
5760            return null;
5761        }
5762        synchronized (mPackages) {
5763            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5764            if (obj instanceof SharedUserSetting) {
5765                final SharedUserSetting sus = (SharedUserSetting) obj;
5766                return sus.name + ":" + sus.userId;
5767            } else if (obj instanceof PackageSetting) {
5768                final PackageSetting ps = (PackageSetting) obj;
5769                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5770                    return null;
5771                }
5772                return ps.name;
5773            }
5774            return null;
5775        }
5776    }
5777
5778    @Override
5779    public String[] getNamesForUids(int[] uids) {
5780        if (uids == null || uids.length == 0) {
5781            return null;
5782        }
5783        final int callingUid = Binder.getCallingUid();
5784        if (getInstantAppPackageName(callingUid) != null) {
5785            return null;
5786        }
5787        final String[] names = new String[uids.length];
5788        synchronized (mPackages) {
5789            for (int i = uids.length - 1; i >= 0; i--) {
5790                final int uid = uids[i];
5791                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5792                if (obj instanceof SharedUserSetting) {
5793                    final SharedUserSetting sus = (SharedUserSetting) obj;
5794                    names[i] = "shared:" + sus.name;
5795                } else if (obj instanceof PackageSetting) {
5796                    final PackageSetting ps = (PackageSetting) obj;
5797                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5798                        names[i] = null;
5799                    } else {
5800                        names[i] = ps.name;
5801                    }
5802                } else {
5803                    names[i] = null;
5804                }
5805            }
5806        }
5807        return names;
5808    }
5809
5810    @Override
5811    public int getUidForSharedUser(String sharedUserName) {
5812        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5813            return -1;
5814        }
5815        if (sharedUserName == null) {
5816            return -1;
5817        }
5818        // reader
5819        synchronized (mPackages) {
5820            SharedUserSetting suid;
5821            try {
5822                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5823                if (suid != null) {
5824                    return suid.userId;
5825                }
5826            } catch (PackageManagerException ignore) {
5827                // can't happen, but, still need to catch it
5828            }
5829            return -1;
5830        }
5831    }
5832
5833    @Override
5834    public int getFlagsForUid(int uid) {
5835        final int callingUid = Binder.getCallingUid();
5836        if (getInstantAppPackageName(callingUid) != null) {
5837            return 0;
5838        }
5839        synchronized (mPackages) {
5840            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5841            if (obj instanceof SharedUserSetting) {
5842                final SharedUserSetting sus = (SharedUserSetting) obj;
5843                return sus.pkgFlags;
5844            } else if (obj instanceof PackageSetting) {
5845                final PackageSetting ps = (PackageSetting) obj;
5846                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5847                    return 0;
5848                }
5849                return ps.pkgFlags;
5850            }
5851        }
5852        return 0;
5853    }
5854
5855    @Override
5856    public int getPrivateFlagsForUid(int uid) {
5857        final int callingUid = Binder.getCallingUid();
5858        if (getInstantAppPackageName(callingUid) != null) {
5859            return 0;
5860        }
5861        synchronized (mPackages) {
5862            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5863            if (obj instanceof SharedUserSetting) {
5864                final SharedUserSetting sus = (SharedUserSetting) obj;
5865                return sus.pkgPrivateFlags;
5866            } else if (obj instanceof PackageSetting) {
5867                final PackageSetting ps = (PackageSetting) obj;
5868                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5869                    return 0;
5870                }
5871                return ps.pkgPrivateFlags;
5872            }
5873        }
5874        return 0;
5875    }
5876
5877    @Override
5878    public boolean isUidPrivileged(int uid) {
5879        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5880            return false;
5881        }
5882        uid = UserHandle.getAppId(uid);
5883        // reader
5884        synchronized (mPackages) {
5885            Object obj = mSettings.getUserIdLPr(uid);
5886            if (obj instanceof SharedUserSetting) {
5887                final SharedUserSetting sus = (SharedUserSetting) obj;
5888                final Iterator<PackageSetting> it = sus.packages.iterator();
5889                while (it.hasNext()) {
5890                    if (it.next().isPrivileged()) {
5891                        return true;
5892                    }
5893                }
5894            } else if (obj instanceof PackageSetting) {
5895                final PackageSetting ps = (PackageSetting) obj;
5896                return ps.isPrivileged();
5897            }
5898        }
5899        return false;
5900    }
5901
5902    @Override
5903    public String[] getAppOpPermissionPackages(String permName) {
5904        return mPermissionManager.getAppOpPermissionPackages(permName);
5905    }
5906
5907    @Override
5908    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5909            int flags, int userId) {
5910        return resolveIntentInternal(
5911                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5912    }
5913
5914    /**
5915     * Normally instant apps can only be resolved when they're visible to the caller.
5916     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5917     * since we need to allow the system to start any installed application.
5918     */
5919    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5920            int flags, int userId, boolean resolveForStart) {
5921        try {
5922            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5923
5924            if (!sUserManager.exists(userId)) return null;
5925            final int callingUid = Binder.getCallingUid();
5926            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5927            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5928                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5929
5930            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5931            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5932                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5933            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5934
5935            final ResolveInfo bestChoice =
5936                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5937            return bestChoice;
5938        } finally {
5939            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5940        }
5941    }
5942
5943    @Override
5944    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5945        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5946            throw new SecurityException(
5947                    "findPersistentPreferredActivity can only be run by the system");
5948        }
5949        if (!sUserManager.exists(userId)) {
5950            return null;
5951        }
5952        final int callingUid = Binder.getCallingUid();
5953        intent = updateIntentForResolve(intent);
5954        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5955        final int flags = updateFlagsForResolve(
5956                0, userId, intent, callingUid, false /*includeInstantApps*/);
5957        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5958                userId);
5959        synchronized (mPackages) {
5960            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5961                    userId);
5962        }
5963    }
5964
5965    @Override
5966    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5967            IntentFilter filter, int match, ComponentName activity) {
5968        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5969            return;
5970        }
5971        final int userId = UserHandle.getCallingUserId();
5972        if (DEBUG_PREFERRED) {
5973            Log.v(TAG, "setLastChosenActivity intent=" + intent
5974                + " resolvedType=" + resolvedType
5975                + " flags=" + flags
5976                + " filter=" + filter
5977                + " match=" + match
5978                + " activity=" + activity);
5979            filter.dump(new PrintStreamPrinter(System.out), "    ");
5980        }
5981        intent.setComponent(null);
5982        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5983                userId);
5984        // Find any earlier preferred or last chosen entries and nuke them
5985        findPreferredActivity(intent, resolvedType,
5986                flags, query, 0, false, true, false, userId);
5987        // Add the new activity as the last chosen for this filter
5988        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5989                "Setting last chosen");
5990    }
5991
5992    @Override
5993    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5994        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5995            return null;
5996        }
5997        final int userId = UserHandle.getCallingUserId();
5998        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5999        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6000                userId);
6001        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6002                false, false, false, userId);
6003    }
6004
6005    /**
6006     * Returns whether or not instant apps have been disabled remotely.
6007     */
6008    private boolean areWebInstantAppsDisabled() {
6009        return mWebInstantAppsDisabled;
6010    }
6011
6012    private boolean isInstantAppResolutionAllowed(
6013            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6014            boolean skipPackageCheck) {
6015        if (mInstantAppResolverConnection == null) {
6016            return false;
6017        }
6018        if (mInstantAppInstallerActivity == null) {
6019            return false;
6020        }
6021        if (intent.getComponent() != null) {
6022            return false;
6023        }
6024        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6025            return false;
6026        }
6027        if (!skipPackageCheck && intent.getPackage() != null) {
6028            return false;
6029        }
6030        if (!intent.isWebIntent()) {
6031            // for non web intents, we should not resolve externally if an app already exists to
6032            // handle it or if the caller didn't explicitly request it.
6033            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6034                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6035                return false;
6036            }
6037        } else {
6038            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6039                return false;
6040            } else if (areWebInstantAppsDisabled()) {
6041                return false;
6042            }
6043        }
6044        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6045        // Or if there's already an ephemeral app installed that handles the action
6046        synchronized (mPackages) {
6047            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6048            for (int n = 0; n < count; n++) {
6049                final ResolveInfo info = resolvedActivities.get(n);
6050                final String packageName = info.activityInfo.packageName;
6051                final PackageSetting ps = mSettings.mPackages.get(packageName);
6052                if (ps != null) {
6053                    // only check domain verification status if the app is not a browser
6054                    if (!info.handleAllWebDataURI) {
6055                        // Try to get the status from User settings first
6056                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6057                        final int status = (int) (packedStatus >> 32);
6058                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6059                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6060                            if (DEBUG_INSTANT) {
6061                                Slog.v(TAG, "DENY instant app;"
6062                                    + " pkg: " + packageName + ", status: " + status);
6063                            }
6064                            return false;
6065                        }
6066                    }
6067                    if (ps.getInstantApp(userId)) {
6068                        if (DEBUG_INSTANT) {
6069                            Slog.v(TAG, "DENY instant app installed;"
6070                                    + " pkg: " + packageName);
6071                        }
6072                        return false;
6073                    }
6074                }
6075            }
6076        }
6077        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6078        return true;
6079    }
6080
6081    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6082            Intent origIntent, String resolvedType, String callingPackage,
6083            Bundle verificationBundle, int userId) {
6084        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6085                new InstantAppRequest(responseObj, origIntent, resolvedType,
6086                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6087        mHandler.sendMessage(msg);
6088    }
6089
6090    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6091            int flags, List<ResolveInfo> query, int userId) {
6092        if (query != null) {
6093            final int N = query.size();
6094            if (N == 1) {
6095                return query.get(0);
6096            } else if (N > 1) {
6097                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6098                // If there is more than one activity with the same priority,
6099                // then let the user decide between them.
6100                ResolveInfo r0 = query.get(0);
6101                ResolveInfo r1 = query.get(1);
6102                if (DEBUG_INTENT_MATCHING || debug) {
6103                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6104                            + r1.activityInfo.name + "=" + r1.priority);
6105                }
6106                // If the first activity has a higher priority, or a different
6107                // default, then it is always desirable to pick it.
6108                if (r0.priority != r1.priority
6109                        || r0.preferredOrder != r1.preferredOrder
6110                        || r0.isDefault != r1.isDefault) {
6111                    return query.get(0);
6112                }
6113                // If we have saved a preference for a preferred activity for
6114                // this Intent, use that.
6115                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6116                        flags, query, r0.priority, true, false, debug, userId);
6117                if (ri != null) {
6118                    return ri;
6119                }
6120                // If we have an ephemeral app, use it
6121                for (int i = 0; i < N; i++) {
6122                    ri = query.get(i);
6123                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6124                        final String packageName = ri.activityInfo.packageName;
6125                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6126                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6127                        final int status = (int)(packedStatus >> 32);
6128                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6129                            return ri;
6130                        }
6131                    }
6132                }
6133                ri = new ResolveInfo(mResolveInfo);
6134                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6135                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6136                // If all of the options come from the same package, show the application's
6137                // label and icon instead of the generic resolver's.
6138                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6139                // and then throw away the ResolveInfo itself, meaning that the caller loses
6140                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6141                // a fallback for this case; we only set the target package's resources on
6142                // the ResolveInfo, not the ActivityInfo.
6143                final String intentPackage = intent.getPackage();
6144                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6145                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6146                    ri.resolvePackageName = intentPackage;
6147                    if (userNeedsBadging(userId)) {
6148                        ri.noResourceId = true;
6149                    } else {
6150                        ri.icon = appi.icon;
6151                    }
6152                    ri.iconResourceId = appi.icon;
6153                    ri.labelRes = appi.labelRes;
6154                }
6155                ri.activityInfo.applicationInfo = new ApplicationInfo(
6156                        ri.activityInfo.applicationInfo);
6157                if (userId != 0) {
6158                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6159                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6160                }
6161                // Make sure that the resolver is displayable in car mode
6162                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6163                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6164                return ri;
6165            }
6166        }
6167        return null;
6168    }
6169
6170    /**
6171     * Return true if the given list is not empty and all of its contents have
6172     * an activityInfo with the given package name.
6173     */
6174    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6175        if (ArrayUtils.isEmpty(list)) {
6176            return false;
6177        }
6178        for (int i = 0, N = list.size(); i < N; i++) {
6179            final ResolveInfo ri = list.get(i);
6180            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6181            if (ai == null || !packageName.equals(ai.packageName)) {
6182                return false;
6183            }
6184        }
6185        return true;
6186    }
6187
6188    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6189            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6190        final int N = query.size();
6191        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6192                .get(userId);
6193        // Get the list of persistent preferred activities that handle the intent
6194        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6195        List<PersistentPreferredActivity> pprefs = ppir != null
6196                ? ppir.queryIntent(intent, resolvedType,
6197                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6198                        userId)
6199                : null;
6200        if (pprefs != null && pprefs.size() > 0) {
6201            final int M = pprefs.size();
6202            for (int i=0; i<M; i++) {
6203                final PersistentPreferredActivity ppa = pprefs.get(i);
6204                if (DEBUG_PREFERRED || debug) {
6205                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6206                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6207                            + "\n  component=" + ppa.mComponent);
6208                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6209                }
6210                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6211                        flags | MATCH_DISABLED_COMPONENTS, userId);
6212                if (DEBUG_PREFERRED || debug) {
6213                    Slog.v(TAG, "Found persistent preferred activity:");
6214                    if (ai != null) {
6215                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6216                    } else {
6217                        Slog.v(TAG, "  null");
6218                    }
6219                }
6220                if (ai == null) {
6221                    // This previously registered persistent preferred activity
6222                    // component is no longer known. Ignore it and do NOT remove it.
6223                    continue;
6224                }
6225                for (int j=0; j<N; j++) {
6226                    final ResolveInfo ri = query.get(j);
6227                    if (!ri.activityInfo.applicationInfo.packageName
6228                            .equals(ai.applicationInfo.packageName)) {
6229                        continue;
6230                    }
6231                    if (!ri.activityInfo.name.equals(ai.name)) {
6232                        continue;
6233                    }
6234                    //  Found a persistent preference that can handle the intent.
6235                    if (DEBUG_PREFERRED || debug) {
6236                        Slog.v(TAG, "Returning persistent preferred activity: " +
6237                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6238                    }
6239                    return ri;
6240                }
6241            }
6242        }
6243        return null;
6244    }
6245
6246    // TODO: handle preferred activities missing while user has amnesia
6247    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6248            List<ResolveInfo> query, int priority, boolean always,
6249            boolean removeMatches, boolean debug, int userId) {
6250        if (!sUserManager.exists(userId)) return null;
6251        final int callingUid = Binder.getCallingUid();
6252        flags = updateFlagsForResolve(
6253                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6254        intent = updateIntentForResolve(intent);
6255        // writer
6256        synchronized (mPackages) {
6257            // Try to find a matching persistent preferred activity.
6258            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6259                    debug, userId);
6260
6261            // If a persistent preferred activity matched, use it.
6262            if (pri != null) {
6263                return pri;
6264            }
6265
6266            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6267            // Get the list of preferred activities that handle the intent
6268            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6269            List<PreferredActivity> prefs = pir != null
6270                    ? pir.queryIntent(intent, resolvedType,
6271                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6272                            userId)
6273                    : null;
6274            if (prefs != null && prefs.size() > 0) {
6275                boolean changed = false;
6276                try {
6277                    // First figure out how good the original match set is.
6278                    // We will only allow preferred activities that came
6279                    // from the same match quality.
6280                    int match = 0;
6281
6282                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6283
6284                    final int N = query.size();
6285                    for (int j=0; j<N; j++) {
6286                        final ResolveInfo ri = query.get(j);
6287                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6288                                + ": 0x" + Integer.toHexString(match));
6289                        if (ri.match > match) {
6290                            match = ri.match;
6291                        }
6292                    }
6293
6294                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6295                            + Integer.toHexString(match));
6296
6297                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6298                    final int M = prefs.size();
6299                    for (int i=0; i<M; i++) {
6300                        final PreferredActivity pa = prefs.get(i);
6301                        if (DEBUG_PREFERRED || debug) {
6302                            Slog.v(TAG, "Checking PreferredActivity ds="
6303                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6304                                    + "\n  component=" + pa.mPref.mComponent);
6305                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6306                        }
6307                        if (pa.mPref.mMatch != match) {
6308                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6309                                    + Integer.toHexString(pa.mPref.mMatch));
6310                            continue;
6311                        }
6312                        // If it's not an "always" type preferred activity and that's what we're
6313                        // looking for, skip it.
6314                        if (always && !pa.mPref.mAlways) {
6315                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6316                            continue;
6317                        }
6318                        final ActivityInfo ai = getActivityInfo(
6319                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6320                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6321                                userId);
6322                        if (DEBUG_PREFERRED || debug) {
6323                            Slog.v(TAG, "Found preferred activity:");
6324                            if (ai != null) {
6325                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6326                            } else {
6327                                Slog.v(TAG, "  null");
6328                            }
6329                        }
6330                        if (ai == null) {
6331                            // This previously registered preferred activity
6332                            // component is no longer known.  Most likely an update
6333                            // to the app was installed and in the new version this
6334                            // component no longer exists.  Clean it up by removing
6335                            // it from the preferred activities list, and skip it.
6336                            Slog.w(TAG, "Removing dangling preferred activity: "
6337                                    + pa.mPref.mComponent);
6338                            pir.removeFilter(pa);
6339                            changed = true;
6340                            continue;
6341                        }
6342                        for (int j=0; j<N; j++) {
6343                            final ResolveInfo ri = query.get(j);
6344                            if (!ri.activityInfo.applicationInfo.packageName
6345                                    .equals(ai.applicationInfo.packageName)) {
6346                                continue;
6347                            }
6348                            if (!ri.activityInfo.name.equals(ai.name)) {
6349                                continue;
6350                            }
6351
6352                            if (removeMatches) {
6353                                pir.removeFilter(pa);
6354                                changed = true;
6355                                if (DEBUG_PREFERRED) {
6356                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6357                                }
6358                                break;
6359                            }
6360
6361                            // Okay we found a previously set preferred or last chosen app.
6362                            // If the result set is different from when this
6363                            // was created, and is not a subset of the preferred set, we need to
6364                            // clear it and re-ask the user their preference, if we're looking for
6365                            // an "always" type entry.
6366                            if (always && !pa.mPref.sameSet(query)) {
6367                                if (pa.mPref.isSuperset(query)) {
6368                                    // some components of the set are no longer present in
6369                                    // the query, but the preferred activity can still be reused
6370                                    if (DEBUG_PREFERRED) {
6371                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6372                                                + " still valid as only non-preferred components"
6373                                                + " were removed for " + intent + " type "
6374                                                + resolvedType);
6375                                    }
6376                                    // remove obsolete components and re-add the up-to-date filter
6377                                    PreferredActivity freshPa = new PreferredActivity(pa,
6378                                            pa.mPref.mMatch,
6379                                            pa.mPref.discardObsoleteComponents(query),
6380                                            pa.mPref.mComponent,
6381                                            pa.mPref.mAlways);
6382                                    pir.removeFilter(pa);
6383                                    pir.addFilter(freshPa);
6384                                    changed = true;
6385                                } else {
6386                                    Slog.i(TAG,
6387                                            "Result set changed, dropping preferred activity for "
6388                                                    + intent + " type " + resolvedType);
6389                                    if (DEBUG_PREFERRED) {
6390                                        Slog.v(TAG, "Removing preferred activity since set changed "
6391                                                + pa.mPref.mComponent);
6392                                    }
6393                                    pir.removeFilter(pa);
6394                                    // Re-add the filter as a "last chosen" entry (!always)
6395                                    PreferredActivity lastChosen = new PreferredActivity(
6396                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6397                                    pir.addFilter(lastChosen);
6398                                    changed = true;
6399                                    return null;
6400                                }
6401                            }
6402
6403                            // Yay! Either the set matched or we're looking for the last chosen
6404                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6405                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6406                            return ri;
6407                        }
6408                    }
6409                } finally {
6410                    if (changed) {
6411                        if (DEBUG_PREFERRED) {
6412                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6413                        }
6414                        scheduleWritePackageRestrictionsLocked(userId);
6415                    }
6416                }
6417            }
6418        }
6419        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6420        return null;
6421    }
6422
6423    /*
6424     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6425     */
6426    @Override
6427    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6428            int targetUserId) {
6429        mContext.enforceCallingOrSelfPermission(
6430                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6431        List<CrossProfileIntentFilter> matches =
6432                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6433        if (matches != null) {
6434            int size = matches.size();
6435            for (int i = 0; i < size; i++) {
6436                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6437            }
6438        }
6439        if (intent.hasWebURI()) {
6440            // cross-profile app linking works only towards the parent.
6441            final int callingUid = Binder.getCallingUid();
6442            final UserInfo parent = getProfileParent(sourceUserId);
6443            synchronized(mPackages) {
6444                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6445                        false /*includeInstantApps*/);
6446                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6447                        intent, resolvedType, flags, sourceUserId, parent.id);
6448                return xpDomainInfo != null;
6449            }
6450        }
6451        return false;
6452    }
6453
6454    private UserInfo getProfileParent(int userId) {
6455        final long identity = Binder.clearCallingIdentity();
6456        try {
6457            return sUserManager.getProfileParent(userId);
6458        } finally {
6459            Binder.restoreCallingIdentity(identity);
6460        }
6461    }
6462
6463    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6464            String resolvedType, int userId) {
6465        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6466        if (resolver != null) {
6467            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6468        }
6469        return null;
6470    }
6471
6472    @Override
6473    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6474            String resolvedType, int flags, int userId) {
6475        try {
6476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6477
6478            return new ParceledListSlice<>(
6479                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6480        } finally {
6481            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6482        }
6483    }
6484
6485    /**
6486     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6487     * instant, returns {@code null}.
6488     */
6489    private String getInstantAppPackageName(int callingUid) {
6490        synchronized (mPackages) {
6491            // If the caller is an isolated app use the owner's uid for the lookup.
6492            if (Process.isIsolated(callingUid)) {
6493                callingUid = mIsolatedOwners.get(callingUid);
6494            }
6495            final int appId = UserHandle.getAppId(callingUid);
6496            final Object obj = mSettings.getUserIdLPr(appId);
6497            if (obj instanceof PackageSetting) {
6498                final PackageSetting ps = (PackageSetting) obj;
6499                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6500                return isInstantApp ? ps.pkg.packageName : null;
6501            }
6502        }
6503        return null;
6504    }
6505
6506    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6507            String resolvedType, int flags, int userId) {
6508        return queryIntentActivitiesInternal(
6509                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6510                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6511    }
6512
6513    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6514            String resolvedType, int flags, int filterCallingUid, int userId,
6515            boolean resolveForStart, boolean allowDynamicSplits) {
6516        if (!sUserManager.exists(userId)) return Collections.emptyList();
6517        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6518        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6519                false /* requireFullPermission */, false /* checkShell */,
6520                "query intent activities");
6521        final String pkgName = intent.getPackage();
6522        ComponentName comp = intent.getComponent();
6523        if (comp == null) {
6524            if (intent.getSelector() != null) {
6525                intent = intent.getSelector();
6526                comp = intent.getComponent();
6527            }
6528        }
6529
6530        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6531                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6532        if (comp != null) {
6533            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6534            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6535            if (ai != null) {
6536                // When specifying an explicit component, we prevent the activity from being
6537                // used when either 1) the calling package is normal and the activity is within
6538                // an ephemeral application or 2) the calling package is ephemeral and the
6539                // activity is not visible to ephemeral applications.
6540                final boolean matchInstantApp =
6541                        (flags & PackageManager.MATCH_INSTANT) != 0;
6542                final boolean matchVisibleToInstantAppOnly =
6543                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6544                final boolean matchExplicitlyVisibleOnly =
6545                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6546                final boolean isCallerInstantApp =
6547                        instantAppPkgName != null;
6548                final boolean isTargetSameInstantApp =
6549                        comp.getPackageName().equals(instantAppPkgName);
6550                final boolean isTargetInstantApp =
6551                        (ai.applicationInfo.privateFlags
6552                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6553                final boolean isTargetVisibleToInstantApp =
6554                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6555                final boolean isTargetExplicitlyVisibleToInstantApp =
6556                        isTargetVisibleToInstantApp
6557                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6558                final boolean isTargetHiddenFromInstantApp =
6559                        !isTargetVisibleToInstantApp
6560                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6561                final boolean blockResolution =
6562                        !isTargetSameInstantApp
6563                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6564                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6565                                        && isTargetHiddenFromInstantApp));
6566                if (!blockResolution) {
6567                    final ResolveInfo ri = new ResolveInfo();
6568                    ri.activityInfo = ai;
6569                    list.add(ri);
6570                }
6571            }
6572            return applyPostResolutionFilter(
6573                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6574        }
6575
6576        // reader
6577        boolean sortResult = false;
6578        boolean addInstant = false;
6579        List<ResolveInfo> result;
6580        synchronized (mPackages) {
6581            if (pkgName == null) {
6582                List<CrossProfileIntentFilter> matchingFilters =
6583                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6584                // Check for results that need to skip the current profile.
6585                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6586                        resolvedType, flags, userId);
6587                if (xpResolveInfo != null) {
6588                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6589                    xpResult.add(xpResolveInfo);
6590                    return applyPostResolutionFilter(
6591                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6592                            allowDynamicSplits, filterCallingUid, userId, intent);
6593                }
6594
6595                // Check for results in the current profile.
6596                result = filterIfNotSystemUser(mActivities.queryIntent(
6597                        intent, resolvedType, flags, userId), userId);
6598                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6599                        false /*skipPackageCheck*/);
6600                // Check for cross profile results.
6601                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6602                xpResolveInfo = queryCrossProfileIntents(
6603                        matchingFilters, intent, resolvedType, flags, userId,
6604                        hasNonNegativePriorityResult);
6605                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6606                    boolean isVisibleToUser = filterIfNotSystemUser(
6607                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6608                    if (isVisibleToUser) {
6609                        result.add(xpResolveInfo);
6610                        sortResult = true;
6611                    }
6612                }
6613                if (intent.hasWebURI()) {
6614                    CrossProfileDomainInfo xpDomainInfo = null;
6615                    final UserInfo parent = getProfileParent(userId);
6616                    if (parent != null) {
6617                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6618                                flags, userId, parent.id);
6619                    }
6620                    if (xpDomainInfo != null) {
6621                        if (xpResolveInfo != null) {
6622                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6623                            // in the result.
6624                            result.remove(xpResolveInfo);
6625                        }
6626                        if (result.size() == 0 && !addInstant) {
6627                            // No result in current profile, but found candidate in parent user.
6628                            // And we are not going to add emphemeral app, so we can return the
6629                            // result straight away.
6630                            result.add(xpDomainInfo.resolveInfo);
6631                            return applyPostResolutionFilter(result, instantAppPkgName,
6632                                    allowDynamicSplits, filterCallingUid, userId, intent);
6633                        }
6634                    } else if (result.size() <= 1 && !addInstant) {
6635                        // No result in parent user and <= 1 result in current profile, and we
6636                        // are not going to add emphemeral app, so we can return the result without
6637                        // further processing.
6638                        return applyPostResolutionFilter(result, instantAppPkgName,
6639                                allowDynamicSplits, filterCallingUid, userId, intent);
6640                    }
6641                    // We have more than one candidate (combining results from current and parent
6642                    // profile), so we need filtering and sorting.
6643                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6644                            intent, flags, result, xpDomainInfo, userId);
6645                    sortResult = true;
6646                }
6647            } else {
6648                final PackageParser.Package pkg = mPackages.get(pkgName);
6649                result = null;
6650                if (pkg != null) {
6651                    result = filterIfNotSystemUser(
6652                            mActivities.queryIntentForPackage(
6653                                    intent, resolvedType, flags, pkg.activities, userId),
6654                            userId);
6655                }
6656                if (result == null || result.size() == 0) {
6657                    // the caller wants to resolve for a particular package; however, there
6658                    // were no installed results, so, try to find an ephemeral result
6659                    addInstant = isInstantAppResolutionAllowed(
6660                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6661                    if (result == null) {
6662                        result = new ArrayList<>();
6663                    }
6664                }
6665            }
6666        }
6667        if (addInstant) {
6668            result = maybeAddInstantAppInstaller(
6669                    result, intent, resolvedType, flags, userId, resolveForStart);
6670        }
6671        if (sortResult) {
6672            Collections.sort(result, mResolvePrioritySorter);
6673        }
6674        return applyPostResolutionFilter(
6675                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6676    }
6677
6678    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6679            String resolvedType, int flags, int userId, boolean resolveForStart) {
6680        // first, check to see if we've got an instant app already installed
6681        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6682        ResolveInfo localInstantApp = null;
6683        boolean blockResolution = false;
6684        if (!alreadyResolvedLocally) {
6685            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6686                    flags
6687                        | PackageManager.GET_RESOLVED_FILTER
6688                        | PackageManager.MATCH_INSTANT
6689                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6690                    userId);
6691            for (int i = instantApps.size() - 1; i >= 0; --i) {
6692                final ResolveInfo info = instantApps.get(i);
6693                final String packageName = info.activityInfo.packageName;
6694                final PackageSetting ps = mSettings.mPackages.get(packageName);
6695                if (ps.getInstantApp(userId)) {
6696                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6697                    final int status = (int)(packedStatus >> 32);
6698                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6699                        // there's a local instant application installed, but, the user has
6700                        // chosen to never use it; skip resolution and don't acknowledge
6701                        // an instant application is even available
6702                        if (DEBUG_INSTANT) {
6703                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6704                        }
6705                        blockResolution = true;
6706                        break;
6707                    } else {
6708                        // we have a locally installed instant application; skip resolution
6709                        // but acknowledge there's an instant application available
6710                        if (DEBUG_INSTANT) {
6711                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6712                        }
6713                        localInstantApp = info;
6714                        break;
6715                    }
6716                }
6717            }
6718        }
6719        // no app installed, let's see if one's available
6720        AuxiliaryResolveInfo auxiliaryResponse = null;
6721        if (!blockResolution) {
6722            if (localInstantApp == null) {
6723                // we don't have an instant app locally, resolve externally
6724                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6725                final InstantAppRequest requestObject = new InstantAppRequest(
6726                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6727                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6728                        resolveForStart);
6729                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6730                        mInstantAppResolverConnection, requestObject);
6731                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6732            } else {
6733                // we have an instant application locally, but, we can't admit that since
6734                // callers shouldn't be able to determine prior browsing. create a dummy
6735                // auxiliary response so the downstream code behaves as if there's an
6736                // instant application available externally. when it comes time to start
6737                // the instant application, we'll do the right thing.
6738                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6739                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6740                                        ai.packageName, ai.versionCode, null /* splitName */);
6741            }
6742        }
6743        if (intent.isWebIntent() && auxiliaryResponse == null) {
6744            return result;
6745        }
6746        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6747        if (ps == null
6748                || ps.getUserState().get(userId) == null
6749                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6750            return result;
6751        }
6752        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6753        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6754                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6755        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6756                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6757        // add a non-generic filter
6758        ephemeralInstaller.filter = new IntentFilter();
6759        if (intent.getAction() != null) {
6760            ephemeralInstaller.filter.addAction(intent.getAction());
6761        }
6762        if (intent.getData() != null && intent.getData().getPath() != null) {
6763            ephemeralInstaller.filter.addDataPath(
6764                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6765        }
6766        ephemeralInstaller.isInstantAppAvailable = true;
6767        // make sure this resolver is the default
6768        ephemeralInstaller.isDefault = true;
6769        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6770        if (DEBUG_INSTANT) {
6771            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6772        }
6773
6774        result.add(ephemeralInstaller);
6775        return result;
6776    }
6777
6778    private static class CrossProfileDomainInfo {
6779        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6780        ResolveInfo resolveInfo;
6781        /* Best domain verification status of the activities found in the other profile */
6782        int bestDomainVerificationStatus;
6783    }
6784
6785    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6786            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6787        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6788                sourceUserId)) {
6789            return null;
6790        }
6791        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6792                resolvedType, flags, parentUserId);
6793
6794        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6795            return null;
6796        }
6797        CrossProfileDomainInfo result = null;
6798        int size = resultTargetUser.size();
6799        for (int i = 0; i < size; i++) {
6800            ResolveInfo riTargetUser = resultTargetUser.get(i);
6801            // Intent filter verification is only for filters that specify a host. So don't return
6802            // those that handle all web uris.
6803            if (riTargetUser.handleAllWebDataURI) {
6804                continue;
6805            }
6806            String packageName = riTargetUser.activityInfo.packageName;
6807            PackageSetting ps = mSettings.mPackages.get(packageName);
6808            if (ps == null) {
6809                continue;
6810            }
6811            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6812            int status = (int)(verificationState >> 32);
6813            if (result == null) {
6814                result = new CrossProfileDomainInfo();
6815                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6816                        sourceUserId, parentUserId);
6817                result.bestDomainVerificationStatus = status;
6818            } else {
6819                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6820                        result.bestDomainVerificationStatus);
6821            }
6822        }
6823        // Don't consider matches with status NEVER across profiles.
6824        if (result != null && result.bestDomainVerificationStatus
6825                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6826            return null;
6827        }
6828        return result;
6829    }
6830
6831    /**
6832     * Verification statuses are ordered from the worse to the best, except for
6833     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6834     */
6835    private int bestDomainVerificationStatus(int status1, int status2) {
6836        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6837            return status2;
6838        }
6839        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6840            return status1;
6841        }
6842        return (int) MathUtils.max(status1, status2);
6843    }
6844
6845    private boolean isUserEnabled(int userId) {
6846        long callingId = Binder.clearCallingIdentity();
6847        try {
6848            UserInfo userInfo = sUserManager.getUserInfo(userId);
6849            return userInfo != null && userInfo.isEnabled();
6850        } finally {
6851            Binder.restoreCallingIdentity(callingId);
6852        }
6853    }
6854
6855    /**
6856     * Filter out activities with systemUserOnly flag set, when current user is not System.
6857     *
6858     * @return filtered list
6859     */
6860    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6861        if (userId == UserHandle.USER_SYSTEM) {
6862            return resolveInfos;
6863        }
6864        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6865            ResolveInfo info = resolveInfos.get(i);
6866            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6867                resolveInfos.remove(i);
6868            }
6869        }
6870        return resolveInfos;
6871    }
6872
6873    /**
6874     * Filters out ephemeral activities.
6875     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6876     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6877     *
6878     * @param resolveInfos The pre-filtered list of resolved activities
6879     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6880     *          is performed.
6881     * @param intent
6882     * @return A filtered list of resolved activities.
6883     */
6884    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6885            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6886            Intent intent) {
6887        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6888        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6889            final ResolveInfo info = resolveInfos.get(i);
6890            // remove locally resolved instant app web results when disabled
6891            if (info.isInstantAppAvailable && blockInstant) {
6892                resolveInfos.remove(i);
6893                continue;
6894            }
6895            // allow activities that are defined in the provided package
6896            if (allowDynamicSplits
6897                    && info.activityInfo != null
6898                    && info.activityInfo.splitName != null
6899                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6900                            info.activityInfo.splitName)) {
6901                if (mInstantAppInstallerActivity == null) {
6902                    if (DEBUG_INSTALL) {
6903                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6904                    }
6905                    resolveInfos.remove(i);
6906                    continue;
6907                }
6908                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6909                    resolveInfos.remove(i);
6910                    continue;
6911                }
6912                // requested activity is defined in a split that hasn't been installed yet.
6913                // add the installer to the resolve list
6914                if (DEBUG_INSTALL) {
6915                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6916                }
6917                final ResolveInfo installerInfo = new ResolveInfo(
6918                        mInstantAppInstallerInfo);
6919                final ComponentName installFailureActivity = findInstallFailureActivity(
6920                        info.activityInfo.packageName,  filterCallingUid, userId);
6921                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6922                        installFailureActivity,
6923                        info.activityInfo.packageName,
6924                        info.activityInfo.applicationInfo.versionCode,
6925                        info.activityInfo.splitName);
6926                // add a non-generic filter
6927                installerInfo.filter = new IntentFilter();
6928
6929                // This resolve info may appear in the chooser UI, so let us make it
6930                // look as the one it replaces as far as the user is concerned which
6931                // requires loading the correct label and icon for the resolve info.
6932                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6933                installerInfo.labelRes = info.resolveLabelResId();
6934                installerInfo.icon = info.resolveIconResId();
6935                installerInfo.isInstantAppAvailable = true;
6936                resolveInfos.set(i, installerInfo);
6937                continue;
6938            }
6939            // caller is a full app, don't need to apply any other filtering
6940            if (ephemeralPkgName == null) {
6941                continue;
6942            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6943                // caller is same app; don't need to apply any other filtering
6944                continue;
6945            }
6946            // allow activities that have been explicitly exposed to ephemeral apps
6947            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6948            if (!isEphemeralApp
6949                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6950                continue;
6951            }
6952            resolveInfos.remove(i);
6953        }
6954        return resolveInfos;
6955    }
6956
6957    /**
6958     * Returns the activity component that can handle install failures.
6959     * <p>By default, the instant application installer handles failures. However, an
6960     * application may want to handle failures on its own. Applications do this by
6961     * creating an activity with an intent filter that handles the action
6962     * {@link Intent#ACTION_INSTALL_FAILURE}.
6963     */
6964    private @Nullable ComponentName findInstallFailureActivity(
6965            String packageName, int filterCallingUid, int userId) {
6966        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6967        failureActivityIntent.setPackage(packageName);
6968        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6969        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6970                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6971                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6972        final int NR = result.size();
6973        if (NR > 0) {
6974            for (int i = 0; i < NR; i++) {
6975                final ResolveInfo info = result.get(i);
6976                if (info.activityInfo.splitName != null) {
6977                    continue;
6978                }
6979                return new ComponentName(packageName, info.activityInfo.name);
6980            }
6981        }
6982        return null;
6983    }
6984
6985    /**
6986     * @param resolveInfos list of resolve infos in descending priority order
6987     * @return if the list contains a resolve info with non-negative priority
6988     */
6989    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6990        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6991    }
6992
6993    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6994            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6995            int userId) {
6996        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6997
6998        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6999            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7000                    candidates.size());
7001        }
7002
7003        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7004        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7005        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7006        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7007        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7008        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7009
7010        synchronized (mPackages) {
7011            final int count = candidates.size();
7012            // First, try to use linked apps. Partition the candidates into four lists:
7013            // one for the final results, one for the "do not use ever", one for "undefined status"
7014            // and finally one for "browser app type".
7015            for (int n=0; n<count; n++) {
7016                ResolveInfo info = candidates.get(n);
7017                String packageName = info.activityInfo.packageName;
7018                PackageSetting ps = mSettings.mPackages.get(packageName);
7019                if (ps != null) {
7020                    // Add to the special match all list (Browser use case)
7021                    if (info.handleAllWebDataURI) {
7022                        matchAllList.add(info);
7023                        continue;
7024                    }
7025                    // Try to get the status from User settings first
7026                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7027                    int status = (int)(packedStatus >> 32);
7028                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7029                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7030                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7031                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7032                                    + " : linkgen=" + linkGeneration);
7033                        }
7034                        // Use link-enabled generation as preferredOrder, i.e.
7035                        // prefer newly-enabled over earlier-enabled.
7036                        info.preferredOrder = linkGeneration;
7037                        alwaysList.add(info);
7038                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7039                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7040                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7041                        }
7042                        neverList.add(info);
7043                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7044                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7045                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7046                        }
7047                        alwaysAskList.add(info);
7048                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7049                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7050                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7051                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7052                        }
7053                        undefinedList.add(info);
7054                    }
7055                }
7056            }
7057
7058            // We'll want to include browser possibilities in a few cases
7059            boolean includeBrowser = false;
7060
7061            // First try to add the "always" resolution(s) for the current user, if any
7062            if (alwaysList.size() > 0) {
7063                result.addAll(alwaysList);
7064            } else {
7065                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7066                result.addAll(undefinedList);
7067                // Maybe add one for the other profile.
7068                if (xpDomainInfo != null && (
7069                        xpDomainInfo.bestDomainVerificationStatus
7070                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7071                    result.add(xpDomainInfo.resolveInfo);
7072                }
7073                includeBrowser = true;
7074            }
7075
7076            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7077            // If there were 'always' entries their preferred order has been set, so we also
7078            // back that off to make the alternatives equivalent
7079            if (alwaysAskList.size() > 0) {
7080                for (ResolveInfo i : result) {
7081                    i.preferredOrder = 0;
7082                }
7083                result.addAll(alwaysAskList);
7084                includeBrowser = true;
7085            }
7086
7087            if (includeBrowser) {
7088                // Also add browsers (all of them or only the default one)
7089                if (DEBUG_DOMAIN_VERIFICATION) {
7090                    Slog.v(TAG, "   ...including browsers in candidate set");
7091                }
7092                if ((matchFlags & MATCH_ALL) != 0) {
7093                    result.addAll(matchAllList);
7094                } else {
7095                    // Browser/generic handling case.  If there's a default browser, go straight
7096                    // to that (but only if there is no other higher-priority match).
7097                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7098                    int maxMatchPrio = 0;
7099                    ResolveInfo defaultBrowserMatch = null;
7100                    final int numCandidates = matchAllList.size();
7101                    for (int n = 0; n < numCandidates; n++) {
7102                        ResolveInfo info = matchAllList.get(n);
7103                        // track the highest overall match priority...
7104                        if (info.priority > maxMatchPrio) {
7105                            maxMatchPrio = info.priority;
7106                        }
7107                        // ...and the highest-priority default browser match
7108                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7109                            if (defaultBrowserMatch == null
7110                                    || (defaultBrowserMatch.priority < info.priority)) {
7111                                if (debug) {
7112                                    Slog.v(TAG, "Considering default browser match " + info);
7113                                }
7114                                defaultBrowserMatch = info;
7115                            }
7116                        }
7117                    }
7118                    if (defaultBrowserMatch != null
7119                            && defaultBrowserMatch.priority >= maxMatchPrio
7120                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7121                    {
7122                        if (debug) {
7123                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7124                        }
7125                        result.add(defaultBrowserMatch);
7126                    } else {
7127                        result.addAll(matchAllList);
7128                    }
7129                }
7130
7131                // If there is nothing selected, add all candidates and remove the ones that the user
7132                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7133                if (result.size() == 0) {
7134                    result.addAll(candidates);
7135                    result.removeAll(neverList);
7136                }
7137            }
7138        }
7139        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7140            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7141                    result.size());
7142            for (ResolveInfo info : result) {
7143                Slog.v(TAG, "  + " + info.activityInfo);
7144            }
7145        }
7146        return result;
7147    }
7148
7149    // Returns a packed value as a long:
7150    //
7151    // high 'int'-sized word: link status: undefined/ask/never/always.
7152    // low 'int'-sized word: relative priority among 'always' results.
7153    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7154        long result = ps.getDomainVerificationStatusForUser(userId);
7155        // if none available, get the master status
7156        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7157            if (ps.getIntentFilterVerificationInfo() != null) {
7158                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7159            }
7160        }
7161        return result;
7162    }
7163
7164    private ResolveInfo querySkipCurrentProfileIntents(
7165            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7166            int flags, int sourceUserId) {
7167        if (matchingFilters != null) {
7168            int size = matchingFilters.size();
7169            for (int i = 0; i < size; i ++) {
7170                CrossProfileIntentFilter filter = matchingFilters.get(i);
7171                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7172                    // Checking if there are activities in the target user that can handle the
7173                    // intent.
7174                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7175                            resolvedType, flags, sourceUserId);
7176                    if (resolveInfo != null) {
7177                        return resolveInfo;
7178                    }
7179                }
7180            }
7181        }
7182        return null;
7183    }
7184
7185    // Return matching ResolveInfo in target user if any.
7186    private ResolveInfo queryCrossProfileIntents(
7187            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7188            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7189        if (matchingFilters != null) {
7190            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7191            // match the same intent. For performance reasons, it is better not to
7192            // run queryIntent twice for the same userId
7193            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7194            int size = matchingFilters.size();
7195            for (int i = 0; i < size; i++) {
7196                CrossProfileIntentFilter filter = matchingFilters.get(i);
7197                int targetUserId = filter.getTargetUserId();
7198                boolean skipCurrentProfile =
7199                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7200                boolean skipCurrentProfileIfNoMatchFound =
7201                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7202                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7203                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7204                    // Checking if there are activities in the target user that can handle the
7205                    // intent.
7206                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7207                            resolvedType, flags, sourceUserId);
7208                    if (resolveInfo != null) return resolveInfo;
7209                    alreadyTriedUserIds.put(targetUserId, true);
7210                }
7211            }
7212        }
7213        return null;
7214    }
7215
7216    /**
7217     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7218     * will forward the intent to the filter's target user.
7219     * Otherwise, returns null.
7220     */
7221    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7222            String resolvedType, int flags, int sourceUserId) {
7223        int targetUserId = filter.getTargetUserId();
7224        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7225                resolvedType, flags, targetUserId);
7226        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7227            // If all the matches in the target profile are suspended, return null.
7228            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7229                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7230                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7231                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7232                            targetUserId);
7233                }
7234            }
7235        }
7236        return null;
7237    }
7238
7239    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7240            int sourceUserId, int targetUserId) {
7241        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7242        long ident = Binder.clearCallingIdentity();
7243        boolean targetIsProfile;
7244        try {
7245            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7246        } finally {
7247            Binder.restoreCallingIdentity(ident);
7248        }
7249        String className;
7250        if (targetIsProfile) {
7251            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7252        } else {
7253            className = FORWARD_INTENT_TO_PARENT;
7254        }
7255        ComponentName forwardingActivityComponentName = new ComponentName(
7256                mAndroidApplication.packageName, className);
7257        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7258                sourceUserId);
7259        if (!targetIsProfile) {
7260            forwardingActivityInfo.showUserIcon = targetUserId;
7261            forwardingResolveInfo.noResourceId = true;
7262        }
7263        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7264        forwardingResolveInfo.priority = 0;
7265        forwardingResolveInfo.preferredOrder = 0;
7266        forwardingResolveInfo.match = 0;
7267        forwardingResolveInfo.isDefault = true;
7268        forwardingResolveInfo.filter = filter;
7269        forwardingResolveInfo.targetUserId = targetUserId;
7270        return forwardingResolveInfo;
7271    }
7272
7273    @Override
7274    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7275            Intent[] specifics, String[] specificTypes, Intent intent,
7276            String resolvedType, int flags, int userId) {
7277        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7278                specificTypes, intent, resolvedType, flags, userId));
7279    }
7280
7281    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7282            Intent[] specifics, String[] specificTypes, Intent intent,
7283            String resolvedType, int flags, int userId) {
7284        if (!sUserManager.exists(userId)) return Collections.emptyList();
7285        final int callingUid = Binder.getCallingUid();
7286        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7287                false /*includeInstantApps*/);
7288        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7289                false /*requireFullPermission*/, false /*checkShell*/,
7290                "query intent activity options");
7291        final String resultsAction = intent.getAction();
7292
7293        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7294                | PackageManager.GET_RESOLVED_FILTER, userId);
7295
7296        if (DEBUG_INTENT_MATCHING) {
7297            Log.v(TAG, "Query " + intent + ": " + results);
7298        }
7299
7300        int specificsPos = 0;
7301        int N;
7302
7303        // todo: note that the algorithm used here is O(N^2).  This
7304        // isn't a problem in our current environment, but if we start running
7305        // into situations where we have more than 5 or 10 matches then this
7306        // should probably be changed to something smarter...
7307
7308        // First we go through and resolve each of the specific items
7309        // that were supplied, taking care of removing any corresponding
7310        // duplicate items in the generic resolve list.
7311        if (specifics != null) {
7312            for (int i=0; i<specifics.length; i++) {
7313                final Intent sintent = specifics[i];
7314                if (sintent == null) {
7315                    continue;
7316                }
7317
7318                if (DEBUG_INTENT_MATCHING) {
7319                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7320                }
7321
7322                String action = sintent.getAction();
7323                if (resultsAction != null && resultsAction.equals(action)) {
7324                    // If this action was explicitly requested, then don't
7325                    // remove things that have it.
7326                    action = null;
7327                }
7328
7329                ResolveInfo ri = null;
7330                ActivityInfo ai = null;
7331
7332                ComponentName comp = sintent.getComponent();
7333                if (comp == null) {
7334                    ri = resolveIntent(
7335                        sintent,
7336                        specificTypes != null ? specificTypes[i] : null,
7337                            flags, userId);
7338                    if (ri == null) {
7339                        continue;
7340                    }
7341                    if (ri == mResolveInfo) {
7342                        // ACK!  Must do something better with this.
7343                    }
7344                    ai = ri.activityInfo;
7345                    comp = new ComponentName(ai.applicationInfo.packageName,
7346                            ai.name);
7347                } else {
7348                    ai = getActivityInfo(comp, flags, userId);
7349                    if (ai == null) {
7350                        continue;
7351                    }
7352                }
7353
7354                // Look for any generic query activities that are duplicates
7355                // of this specific one, and remove them from the results.
7356                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7357                N = results.size();
7358                int j;
7359                for (j=specificsPos; j<N; j++) {
7360                    ResolveInfo sri = results.get(j);
7361                    if ((sri.activityInfo.name.equals(comp.getClassName())
7362                            && sri.activityInfo.applicationInfo.packageName.equals(
7363                                    comp.getPackageName()))
7364                        || (action != null && sri.filter.matchAction(action))) {
7365                        results.remove(j);
7366                        if (DEBUG_INTENT_MATCHING) Log.v(
7367                            TAG, "Removing duplicate item from " + j
7368                            + " due to specific " + specificsPos);
7369                        if (ri == null) {
7370                            ri = sri;
7371                        }
7372                        j--;
7373                        N--;
7374                    }
7375                }
7376
7377                // Add this specific item to its proper place.
7378                if (ri == null) {
7379                    ri = new ResolveInfo();
7380                    ri.activityInfo = ai;
7381                }
7382                results.add(specificsPos, ri);
7383                ri.specificIndex = i;
7384                specificsPos++;
7385            }
7386        }
7387
7388        // Now we go through the remaining generic results and remove any
7389        // duplicate actions that are found here.
7390        N = results.size();
7391        for (int i=specificsPos; i<N-1; i++) {
7392            final ResolveInfo rii = results.get(i);
7393            if (rii.filter == null) {
7394                continue;
7395            }
7396
7397            // Iterate over all of the actions of this result's intent
7398            // filter...  typically this should be just one.
7399            final Iterator<String> it = rii.filter.actionsIterator();
7400            if (it == null) {
7401                continue;
7402            }
7403            while (it.hasNext()) {
7404                final String action = it.next();
7405                if (resultsAction != null && resultsAction.equals(action)) {
7406                    // If this action was explicitly requested, then don't
7407                    // remove things that have it.
7408                    continue;
7409                }
7410                for (int j=i+1; j<N; j++) {
7411                    final ResolveInfo rij = results.get(j);
7412                    if (rij.filter != null && rij.filter.hasAction(action)) {
7413                        results.remove(j);
7414                        if (DEBUG_INTENT_MATCHING) Log.v(
7415                            TAG, "Removing duplicate item from " + j
7416                            + " due to action " + action + " at " + i);
7417                        j--;
7418                        N--;
7419                    }
7420                }
7421            }
7422
7423            // If the caller didn't request filter information, drop it now
7424            // so we don't have to marshall/unmarshall it.
7425            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7426                rii.filter = null;
7427            }
7428        }
7429
7430        // Filter out the caller activity if so requested.
7431        if (caller != null) {
7432            N = results.size();
7433            for (int i=0; i<N; i++) {
7434                ActivityInfo ainfo = results.get(i).activityInfo;
7435                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7436                        && caller.getClassName().equals(ainfo.name)) {
7437                    results.remove(i);
7438                    break;
7439                }
7440            }
7441        }
7442
7443        // If the caller didn't request filter information,
7444        // drop them now so we don't have to
7445        // marshall/unmarshall it.
7446        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7447            N = results.size();
7448            for (int i=0; i<N; i++) {
7449                results.get(i).filter = null;
7450            }
7451        }
7452
7453        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7454        return results;
7455    }
7456
7457    @Override
7458    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7459            String resolvedType, int flags, int userId) {
7460        return new ParceledListSlice<>(
7461                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7462                        false /*allowDynamicSplits*/));
7463    }
7464
7465    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7466            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7467        if (!sUserManager.exists(userId)) return Collections.emptyList();
7468        final int callingUid = Binder.getCallingUid();
7469        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7470                false /*requireFullPermission*/, false /*checkShell*/,
7471                "query intent receivers");
7472        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7473        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7474                false /*includeInstantApps*/);
7475        ComponentName comp = intent.getComponent();
7476        if (comp == null) {
7477            if (intent.getSelector() != null) {
7478                intent = intent.getSelector();
7479                comp = intent.getComponent();
7480            }
7481        }
7482        if (comp != null) {
7483            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7484            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7485            if (ai != null) {
7486                // When specifying an explicit component, we prevent the activity from being
7487                // used when either 1) the calling package is normal and the activity is within
7488                // an instant application or 2) the calling package is ephemeral and the
7489                // activity is not visible to instant applications.
7490                final boolean matchInstantApp =
7491                        (flags & PackageManager.MATCH_INSTANT) != 0;
7492                final boolean matchVisibleToInstantAppOnly =
7493                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7494                final boolean matchExplicitlyVisibleOnly =
7495                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7496                final boolean isCallerInstantApp =
7497                        instantAppPkgName != null;
7498                final boolean isTargetSameInstantApp =
7499                        comp.getPackageName().equals(instantAppPkgName);
7500                final boolean isTargetInstantApp =
7501                        (ai.applicationInfo.privateFlags
7502                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7503                final boolean isTargetVisibleToInstantApp =
7504                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7505                final boolean isTargetExplicitlyVisibleToInstantApp =
7506                        isTargetVisibleToInstantApp
7507                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7508                final boolean isTargetHiddenFromInstantApp =
7509                        !isTargetVisibleToInstantApp
7510                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7511                final boolean blockResolution =
7512                        !isTargetSameInstantApp
7513                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7514                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7515                                        && isTargetHiddenFromInstantApp));
7516                if (!blockResolution) {
7517                    ResolveInfo ri = new ResolveInfo();
7518                    ri.activityInfo = ai;
7519                    list.add(ri);
7520                }
7521            }
7522            return applyPostResolutionFilter(
7523                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7524        }
7525
7526        // reader
7527        synchronized (mPackages) {
7528            String pkgName = intent.getPackage();
7529            if (pkgName == null) {
7530                final List<ResolveInfo> result =
7531                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7532                return applyPostResolutionFilter(
7533                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7534            }
7535            final PackageParser.Package pkg = mPackages.get(pkgName);
7536            if (pkg != null) {
7537                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7538                        intent, resolvedType, flags, pkg.receivers, userId);
7539                return applyPostResolutionFilter(
7540                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7541            }
7542            return Collections.emptyList();
7543        }
7544    }
7545
7546    @Override
7547    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7548        final int callingUid = Binder.getCallingUid();
7549        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7550    }
7551
7552    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7553            int userId, int callingUid) {
7554        if (!sUserManager.exists(userId)) return null;
7555        flags = updateFlagsForResolve(
7556                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7557        List<ResolveInfo> query = queryIntentServicesInternal(
7558                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7559        if (query != null) {
7560            if (query.size() >= 1) {
7561                // If there is more than one service with the same priority,
7562                // just arbitrarily pick the first one.
7563                return query.get(0);
7564            }
7565        }
7566        return null;
7567    }
7568
7569    @Override
7570    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7571            String resolvedType, int flags, int userId) {
7572        final int callingUid = Binder.getCallingUid();
7573        return new ParceledListSlice<>(queryIntentServicesInternal(
7574                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7575    }
7576
7577    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7578            String resolvedType, int flags, int userId, int callingUid,
7579            boolean includeInstantApps) {
7580        if (!sUserManager.exists(userId)) return Collections.emptyList();
7581        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7582                false /*requireFullPermission*/, false /*checkShell*/,
7583                "query intent receivers");
7584        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7585        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7586        ComponentName comp = intent.getComponent();
7587        if (comp == null) {
7588            if (intent.getSelector() != null) {
7589                intent = intent.getSelector();
7590                comp = intent.getComponent();
7591            }
7592        }
7593        if (comp != null) {
7594            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7595            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7596            if (si != null) {
7597                // When specifying an explicit component, we prevent the service from being
7598                // used when either 1) the service is in an instant application and the
7599                // caller is not the same instant application or 2) the calling package is
7600                // ephemeral and the activity is not visible to ephemeral applications.
7601                final boolean matchInstantApp =
7602                        (flags & PackageManager.MATCH_INSTANT) != 0;
7603                final boolean matchVisibleToInstantAppOnly =
7604                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7605                final boolean isCallerInstantApp =
7606                        instantAppPkgName != null;
7607                final boolean isTargetSameInstantApp =
7608                        comp.getPackageName().equals(instantAppPkgName);
7609                final boolean isTargetInstantApp =
7610                        (si.applicationInfo.privateFlags
7611                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7612                final boolean isTargetHiddenFromInstantApp =
7613                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7614                final boolean blockResolution =
7615                        !isTargetSameInstantApp
7616                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7617                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7618                                        && isTargetHiddenFromInstantApp));
7619                if (!blockResolution) {
7620                    final ResolveInfo ri = new ResolveInfo();
7621                    ri.serviceInfo = si;
7622                    list.add(ri);
7623                }
7624            }
7625            return list;
7626        }
7627
7628        // reader
7629        synchronized (mPackages) {
7630            String pkgName = intent.getPackage();
7631            if (pkgName == null) {
7632                return applyPostServiceResolutionFilter(
7633                        mServices.queryIntent(intent, resolvedType, flags, userId),
7634                        instantAppPkgName);
7635            }
7636            final PackageParser.Package pkg = mPackages.get(pkgName);
7637            if (pkg != null) {
7638                return applyPostServiceResolutionFilter(
7639                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7640                                userId),
7641                        instantAppPkgName);
7642            }
7643            return Collections.emptyList();
7644        }
7645    }
7646
7647    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7648            String instantAppPkgName) {
7649        if (instantAppPkgName == null) {
7650            return resolveInfos;
7651        }
7652        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7653            final ResolveInfo info = resolveInfos.get(i);
7654            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7655            // allow services that are defined in the provided package
7656            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7657                if (info.serviceInfo.splitName != null
7658                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7659                                info.serviceInfo.splitName)) {
7660                    // requested service is defined in a split that hasn't been installed yet.
7661                    // add the installer to the resolve list
7662                    if (DEBUG_INSTANT) {
7663                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7664                    }
7665                    final ResolveInfo installerInfo = new ResolveInfo(
7666                            mInstantAppInstallerInfo);
7667                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7668                            null /* installFailureActivity */,
7669                            info.serviceInfo.packageName,
7670                            info.serviceInfo.applicationInfo.versionCode,
7671                            info.serviceInfo.splitName);
7672                    // add a non-generic filter
7673                    installerInfo.filter = new IntentFilter();
7674                    // load resources from the correct package
7675                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7676                    resolveInfos.set(i, installerInfo);
7677                }
7678                continue;
7679            }
7680            // allow services that have been explicitly exposed to ephemeral apps
7681            if (!isEphemeralApp
7682                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7683                continue;
7684            }
7685            resolveInfos.remove(i);
7686        }
7687        return resolveInfos;
7688    }
7689
7690    @Override
7691    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7692            String resolvedType, int flags, int userId) {
7693        return new ParceledListSlice<>(
7694                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7695    }
7696
7697    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7698            Intent intent, String resolvedType, int flags, int userId) {
7699        if (!sUserManager.exists(userId)) return Collections.emptyList();
7700        final int callingUid = Binder.getCallingUid();
7701        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7702        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7703                false /*includeInstantApps*/);
7704        ComponentName comp = intent.getComponent();
7705        if (comp == null) {
7706            if (intent.getSelector() != null) {
7707                intent = intent.getSelector();
7708                comp = intent.getComponent();
7709            }
7710        }
7711        if (comp != null) {
7712            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7713            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7714            if (pi != null) {
7715                // When specifying an explicit component, we prevent the provider from being
7716                // used when either 1) the provider is in an instant application and the
7717                // caller is not the same instant application or 2) the calling package is an
7718                // instant application and the provider is not visible to instant applications.
7719                final boolean matchInstantApp =
7720                        (flags & PackageManager.MATCH_INSTANT) != 0;
7721                final boolean matchVisibleToInstantAppOnly =
7722                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7723                final boolean isCallerInstantApp =
7724                        instantAppPkgName != null;
7725                final boolean isTargetSameInstantApp =
7726                        comp.getPackageName().equals(instantAppPkgName);
7727                final boolean isTargetInstantApp =
7728                        (pi.applicationInfo.privateFlags
7729                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7730                final boolean isTargetHiddenFromInstantApp =
7731                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7732                final boolean blockResolution =
7733                        !isTargetSameInstantApp
7734                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7735                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7736                                        && isTargetHiddenFromInstantApp));
7737                if (!blockResolution) {
7738                    final ResolveInfo ri = new ResolveInfo();
7739                    ri.providerInfo = pi;
7740                    list.add(ri);
7741                }
7742            }
7743            return list;
7744        }
7745
7746        // reader
7747        synchronized (mPackages) {
7748            String pkgName = intent.getPackage();
7749            if (pkgName == null) {
7750                return applyPostContentProviderResolutionFilter(
7751                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7752                        instantAppPkgName);
7753            }
7754            final PackageParser.Package pkg = mPackages.get(pkgName);
7755            if (pkg != null) {
7756                return applyPostContentProviderResolutionFilter(
7757                        mProviders.queryIntentForPackage(
7758                        intent, resolvedType, flags, pkg.providers, userId),
7759                        instantAppPkgName);
7760            }
7761            return Collections.emptyList();
7762        }
7763    }
7764
7765    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7766            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7767        if (instantAppPkgName == null) {
7768            return resolveInfos;
7769        }
7770        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7771            final ResolveInfo info = resolveInfos.get(i);
7772            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7773            // allow providers that are defined in the provided package
7774            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7775                if (info.providerInfo.splitName != null
7776                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7777                                info.providerInfo.splitName)) {
7778                    // requested provider is defined in a split that hasn't been installed yet.
7779                    // add the installer to the resolve list
7780                    if (DEBUG_INSTANT) {
7781                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7782                    }
7783                    final ResolveInfo installerInfo = new ResolveInfo(
7784                            mInstantAppInstallerInfo);
7785                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7786                            null /*failureActivity*/,
7787                            info.providerInfo.packageName,
7788                            info.providerInfo.applicationInfo.versionCode,
7789                            info.providerInfo.splitName);
7790                    // add a non-generic filter
7791                    installerInfo.filter = new IntentFilter();
7792                    // load resources from the correct package
7793                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7794                    resolveInfos.set(i, installerInfo);
7795                }
7796                continue;
7797            }
7798            // allow providers that have been explicitly exposed to instant applications
7799            if (!isEphemeralApp
7800                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7801                continue;
7802            }
7803            resolveInfos.remove(i);
7804        }
7805        return resolveInfos;
7806    }
7807
7808    @Override
7809    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7810        final int callingUid = Binder.getCallingUid();
7811        if (getInstantAppPackageName(callingUid) != null) {
7812            return ParceledListSlice.emptyList();
7813        }
7814        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7815        flags = updateFlagsForPackage(flags, userId, null);
7816        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7817        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7818                true /* requireFullPermission */, false /* checkShell */,
7819                "get installed packages");
7820
7821        // writer
7822        synchronized (mPackages) {
7823            ArrayList<PackageInfo> list;
7824            if (listUninstalled) {
7825                list = new ArrayList<>(mSettings.mPackages.size());
7826                for (PackageSetting ps : mSettings.mPackages.values()) {
7827                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7828                        continue;
7829                    }
7830                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7831                        continue;
7832                    }
7833                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7834                    if (pi != null) {
7835                        list.add(pi);
7836                    }
7837                }
7838            } else {
7839                list = new ArrayList<>(mPackages.size());
7840                for (PackageParser.Package p : mPackages.values()) {
7841                    final PackageSetting ps = (PackageSetting) p.mExtras;
7842                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7843                        continue;
7844                    }
7845                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7846                        continue;
7847                    }
7848                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7849                            p.mExtras, flags, userId);
7850                    if (pi != null) {
7851                        list.add(pi);
7852                    }
7853                }
7854            }
7855
7856            return new ParceledListSlice<>(list);
7857        }
7858    }
7859
7860    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7861            String[] permissions, boolean[] tmp, int flags, int userId) {
7862        int numMatch = 0;
7863        final PermissionsState permissionsState = ps.getPermissionsState();
7864        for (int i=0; i<permissions.length; i++) {
7865            final String permission = permissions[i];
7866            if (permissionsState.hasPermission(permission, userId)) {
7867                tmp[i] = true;
7868                numMatch++;
7869            } else {
7870                tmp[i] = false;
7871            }
7872        }
7873        if (numMatch == 0) {
7874            return;
7875        }
7876        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7877
7878        // The above might return null in cases of uninstalled apps or install-state
7879        // skew across users/profiles.
7880        if (pi != null) {
7881            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7882                if (numMatch == permissions.length) {
7883                    pi.requestedPermissions = permissions;
7884                } else {
7885                    pi.requestedPermissions = new String[numMatch];
7886                    numMatch = 0;
7887                    for (int i=0; i<permissions.length; i++) {
7888                        if (tmp[i]) {
7889                            pi.requestedPermissions[numMatch] = permissions[i];
7890                            numMatch++;
7891                        }
7892                    }
7893                }
7894            }
7895            list.add(pi);
7896        }
7897    }
7898
7899    @Override
7900    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7901            String[] permissions, int flags, int userId) {
7902        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7903        flags = updateFlagsForPackage(flags, userId, permissions);
7904        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7905                true /* requireFullPermission */, false /* checkShell */,
7906                "get packages holding permissions");
7907        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7908
7909        // writer
7910        synchronized (mPackages) {
7911            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7912            boolean[] tmpBools = new boolean[permissions.length];
7913            if (listUninstalled) {
7914                for (PackageSetting ps : mSettings.mPackages.values()) {
7915                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7916                            userId);
7917                }
7918            } else {
7919                for (PackageParser.Package pkg : mPackages.values()) {
7920                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7921                    if (ps != null) {
7922                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7923                                userId);
7924                    }
7925                }
7926            }
7927
7928            return new ParceledListSlice<PackageInfo>(list);
7929        }
7930    }
7931
7932    @Override
7933    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7934        final int callingUid = Binder.getCallingUid();
7935        if (getInstantAppPackageName(callingUid) != null) {
7936            return ParceledListSlice.emptyList();
7937        }
7938        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7939        flags = updateFlagsForApplication(flags, userId, null);
7940        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7941
7942        // writer
7943        synchronized (mPackages) {
7944            ArrayList<ApplicationInfo> list;
7945            if (listUninstalled) {
7946                list = new ArrayList<>(mSettings.mPackages.size());
7947                for (PackageSetting ps : mSettings.mPackages.values()) {
7948                    ApplicationInfo ai;
7949                    int effectiveFlags = flags;
7950                    if (ps.isSystem()) {
7951                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7952                    }
7953                    if (ps.pkg != null) {
7954                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7955                            continue;
7956                        }
7957                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7958                            continue;
7959                        }
7960                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7961                                ps.readUserState(userId), userId);
7962                        if (ai != null) {
7963                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7964                        }
7965                    } else {
7966                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7967                        // and already converts to externally visible package name
7968                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7969                                callingUid, effectiveFlags, userId);
7970                    }
7971                    if (ai != null) {
7972                        list.add(ai);
7973                    }
7974                }
7975            } else {
7976                list = new ArrayList<>(mPackages.size());
7977                for (PackageParser.Package p : mPackages.values()) {
7978                    if (p.mExtras != null) {
7979                        PackageSetting ps = (PackageSetting) p.mExtras;
7980                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7981                            continue;
7982                        }
7983                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7984                            continue;
7985                        }
7986                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7987                                ps.readUserState(userId), userId);
7988                        if (ai != null) {
7989                            ai.packageName = resolveExternalPackageNameLPr(p);
7990                            list.add(ai);
7991                        }
7992                    }
7993                }
7994            }
7995
7996            return new ParceledListSlice<>(list);
7997        }
7998    }
7999
8000    @Override
8001    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8002        if (HIDE_EPHEMERAL_APIS) {
8003            return null;
8004        }
8005        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8006            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8007                    "getEphemeralApplications");
8008        }
8009        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8010                true /* requireFullPermission */, false /* checkShell */,
8011                "getEphemeralApplications");
8012        synchronized (mPackages) {
8013            List<InstantAppInfo> instantApps = mInstantAppRegistry
8014                    .getInstantAppsLPr(userId);
8015            if (instantApps != null) {
8016                return new ParceledListSlice<>(instantApps);
8017            }
8018        }
8019        return null;
8020    }
8021
8022    @Override
8023    public boolean isInstantApp(String packageName, int userId) {
8024        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8025                true /* requireFullPermission */, false /* checkShell */,
8026                "isInstantApp");
8027        if (HIDE_EPHEMERAL_APIS) {
8028            return false;
8029        }
8030
8031        synchronized (mPackages) {
8032            int callingUid = Binder.getCallingUid();
8033            if (Process.isIsolated(callingUid)) {
8034                callingUid = mIsolatedOwners.get(callingUid);
8035            }
8036            final PackageSetting ps = mSettings.mPackages.get(packageName);
8037            PackageParser.Package pkg = mPackages.get(packageName);
8038            final boolean returnAllowed =
8039                    ps != null
8040                    && (isCallerSameApp(packageName, callingUid)
8041                            || canViewInstantApps(callingUid, userId)
8042                            || mInstantAppRegistry.isInstantAccessGranted(
8043                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8044            if (returnAllowed) {
8045                return ps.getInstantApp(userId);
8046            }
8047        }
8048        return false;
8049    }
8050
8051    @Override
8052    public byte[] getInstantAppCookie(String packageName, int userId) {
8053        if (HIDE_EPHEMERAL_APIS) {
8054            return null;
8055        }
8056
8057        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8058                true /* requireFullPermission */, false /* checkShell */,
8059                "getInstantAppCookie");
8060        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8061            return null;
8062        }
8063        synchronized (mPackages) {
8064            return mInstantAppRegistry.getInstantAppCookieLPw(
8065                    packageName, userId);
8066        }
8067    }
8068
8069    @Override
8070    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8071        if (HIDE_EPHEMERAL_APIS) {
8072            return true;
8073        }
8074
8075        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8076                true /* requireFullPermission */, true /* checkShell */,
8077                "setInstantAppCookie");
8078        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8079            return false;
8080        }
8081        synchronized (mPackages) {
8082            return mInstantAppRegistry.setInstantAppCookieLPw(
8083                    packageName, cookie, userId);
8084        }
8085    }
8086
8087    @Override
8088    public Bitmap getInstantAppIcon(String packageName, int userId) {
8089        if (HIDE_EPHEMERAL_APIS) {
8090            return null;
8091        }
8092
8093        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8094            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8095                    "getInstantAppIcon");
8096        }
8097        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8098                true /* requireFullPermission */, false /* checkShell */,
8099                "getInstantAppIcon");
8100
8101        synchronized (mPackages) {
8102            return mInstantAppRegistry.getInstantAppIconLPw(
8103                    packageName, userId);
8104        }
8105    }
8106
8107    private boolean isCallerSameApp(String packageName, int uid) {
8108        PackageParser.Package pkg = mPackages.get(packageName);
8109        return pkg != null
8110                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8111    }
8112
8113    @Override
8114    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8115        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8116            return ParceledListSlice.emptyList();
8117        }
8118        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8119    }
8120
8121    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8122        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8123
8124        // reader
8125        synchronized (mPackages) {
8126            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8127            final int userId = UserHandle.getCallingUserId();
8128            while (i.hasNext()) {
8129                final PackageParser.Package p = i.next();
8130                if (p.applicationInfo == null) continue;
8131
8132                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8133                        && !p.applicationInfo.isDirectBootAware();
8134                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8135                        && p.applicationInfo.isDirectBootAware();
8136
8137                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8138                        && (!mSafeMode || isSystemApp(p))
8139                        && (matchesUnaware || matchesAware)) {
8140                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8141                    if (ps != null) {
8142                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8143                                ps.readUserState(userId), userId);
8144                        if (ai != null) {
8145                            finalList.add(ai);
8146                        }
8147                    }
8148                }
8149            }
8150        }
8151
8152        return finalList;
8153    }
8154
8155    @Override
8156    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8157        return resolveContentProviderInternal(name, flags, userId);
8158    }
8159
8160    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8161        if (!sUserManager.exists(userId)) return null;
8162        flags = updateFlagsForComponent(flags, userId, name);
8163        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8164        // reader
8165        synchronized (mPackages) {
8166            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8167            PackageSetting ps = provider != null
8168                    ? mSettings.mPackages.get(provider.owner.packageName)
8169                    : null;
8170            if (ps != null) {
8171                final boolean isInstantApp = ps.getInstantApp(userId);
8172                // normal application; filter out instant application provider
8173                if (instantAppPkgName == null && isInstantApp) {
8174                    return null;
8175                }
8176                // instant application; filter out other instant applications
8177                if (instantAppPkgName != null
8178                        && isInstantApp
8179                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8180                    return null;
8181                }
8182                // instant application; filter out non-exposed provider
8183                if (instantAppPkgName != null
8184                        && !isInstantApp
8185                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8186                    return null;
8187                }
8188                // provider not enabled
8189                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8190                    return null;
8191                }
8192                return PackageParser.generateProviderInfo(
8193                        provider, flags, ps.readUserState(userId), userId);
8194            }
8195            return null;
8196        }
8197    }
8198
8199    /**
8200     * @deprecated
8201     */
8202    @Deprecated
8203    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8204        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8205            return;
8206        }
8207        // reader
8208        synchronized (mPackages) {
8209            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8210                    .entrySet().iterator();
8211            final int userId = UserHandle.getCallingUserId();
8212            while (i.hasNext()) {
8213                Map.Entry<String, PackageParser.Provider> entry = i.next();
8214                PackageParser.Provider p = entry.getValue();
8215                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8216
8217                if (ps != null && p.syncable
8218                        && (!mSafeMode || (p.info.applicationInfo.flags
8219                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8220                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8221                            ps.readUserState(userId), userId);
8222                    if (info != null) {
8223                        outNames.add(entry.getKey());
8224                        outInfo.add(info);
8225                    }
8226                }
8227            }
8228        }
8229    }
8230
8231    @Override
8232    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8233            int uid, int flags, String metaDataKey) {
8234        final int callingUid = Binder.getCallingUid();
8235        final int userId = processName != null ? UserHandle.getUserId(uid)
8236                : UserHandle.getCallingUserId();
8237        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8238        flags = updateFlagsForComponent(flags, userId, processName);
8239        ArrayList<ProviderInfo> finalList = null;
8240        // reader
8241        synchronized (mPackages) {
8242            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8243            while (i.hasNext()) {
8244                final PackageParser.Provider p = i.next();
8245                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8246                if (ps != null && p.info.authority != null
8247                        && (processName == null
8248                                || (p.info.processName.equals(processName)
8249                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8250                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8251
8252                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8253                    // parameter.
8254                    if (metaDataKey != null
8255                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8256                        continue;
8257                    }
8258                    final ComponentName component =
8259                            new ComponentName(p.info.packageName, p.info.name);
8260                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8261                        continue;
8262                    }
8263                    if (finalList == null) {
8264                        finalList = new ArrayList<ProviderInfo>(3);
8265                    }
8266                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8267                            ps.readUserState(userId), userId);
8268                    if (info != null) {
8269                        finalList.add(info);
8270                    }
8271                }
8272            }
8273        }
8274
8275        if (finalList != null) {
8276            Collections.sort(finalList, mProviderInitOrderSorter);
8277            return new ParceledListSlice<ProviderInfo>(finalList);
8278        }
8279
8280        return ParceledListSlice.emptyList();
8281    }
8282
8283    @Override
8284    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8285        // reader
8286        synchronized (mPackages) {
8287            final int callingUid = Binder.getCallingUid();
8288            final int callingUserId = UserHandle.getUserId(callingUid);
8289            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8290            if (ps == null) return null;
8291            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8292                return null;
8293            }
8294            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8295            return PackageParser.generateInstrumentationInfo(i, flags);
8296        }
8297    }
8298
8299    @Override
8300    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8301            String targetPackage, int flags) {
8302        final int callingUid = Binder.getCallingUid();
8303        final int callingUserId = UserHandle.getUserId(callingUid);
8304        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8305        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8306            return ParceledListSlice.emptyList();
8307        }
8308        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8309    }
8310
8311    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8312            int flags) {
8313        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8314
8315        // reader
8316        synchronized (mPackages) {
8317            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8318            while (i.hasNext()) {
8319                final PackageParser.Instrumentation p = i.next();
8320                if (targetPackage == null
8321                        || targetPackage.equals(p.info.targetPackage)) {
8322                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8323                            flags);
8324                    if (ii != null) {
8325                        finalList.add(ii);
8326                    }
8327                }
8328            }
8329        }
8330
8331        return finalList;
8332    }
8333
8334    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8335        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8336        try {
8337            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8338        } finally {
8339            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8340        }
8341    }
8342
8343    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8344        final File[] files = scanDir.listFiles();
8345        if (ArrayUtils.isEmpty(files)) {
8346            Log.d(TAG, "No files in app dir " + scanDir);
8347            return;
8348        }
8349
8350        if (DEBUG_PACKAGE_SCANNING) {
8351            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8352                    + " flags=0x" + Integer.toHexString(parseFlags));
8353        }
8354        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8355                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8356                mParallelPackageParserCallback)) {
8357            // Submit files for parsing in parallel
8358            int fileCount = 0;
8359            for (File file : files) {
8360                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8361                        && !PackageInstallerService.isStageName(file.getName());
8362                if (!isPackage) {
8363                    // Ignore entries which are not packages
8364                    continue;
8365                }
8366                parallelPackageParser.submit(file, parseFlags);
8367                fileCount++;
8368            }
8369
8370            // Process results one by one
8371            for (; fileCount > 0; fileCount--) {
8372                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8373                Throwable throwable = parseResult.throwable;
8374                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8375
8376                if (throwable == null) {
8377                    // TODO(toddke): move lower in the scan chain
8378                    // Static shared libraries have synthetic package names
8379                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8380                        renameStaticSharedLibraryPackage(parseResult.pkg);
8381                    }
8382                    try {
8383                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8384                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8385                                    currentTime, null);
8386                        }
8387                    } catch (PackageManagerException e) {
8388                        errorCode = e.error;
8389                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8390                    }
8391                } else if (throwable instanceof PackageParser.PackageParserException) {
8392                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8393                            throwable;
8394                    errorCode = e.error;
8395                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8396                } else {
8397                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8398                            + parseResult.scanFile, throwable);
8399                }
8400
8401                // Delete invalid userdata apps
8402                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8403                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8404                    logCriticalInfo(Log.WARN,
8405                            "Deleting invalid package at " + parseResult.scanFile);
8406                    removeCodePathLI(parseResult.scanFile);
8407                }
8408            }
8409        }
8410    }
8411
8412    public static void reportSettingsProblem(int priority, String msg) {
8413        logCriticalInfo(priority, msg);
8414    }
8415
8416    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8417            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8418        // When upgrading from pre-N MR1, verify the package time stamp using the package
8419        // directory and not the APK file.
8420        final long lastModifiedTime = mIsPreNMR1Upgrade
8421                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8422        if (ps != null && !forceCollect
8423                && ps.codePathString.equals(pkg.codePath)
8424                && ps.timeStamp == lastModifiedTime
8425                && !isCompatSignatureUpdateNeeded(pkg)
8426                && !isRecoverSignatureUpdateNeeded(pkg)) {
8427            if (ps.signatures.mSigningDetails.signatures != null
8428                    && ps.signatures.mSigningDetails.signatures.length != 0
8429                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8430                            != SignatureSchemeVersion.UNKNOWN) {
8431                // Optimization: reuse the existing cached signing data
8432                // if the package appears to be unchanged.
8433                pkg.mSigningDetails =
8434                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8435                return;
8436            }
8437
8438            Slog.w(TAG, "PackageSetting for " + ps.name
8439                    + " is missing signatures.  Collecting certs again to recover them.");
8440        } else {
8441            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8442                    (forceCollect ? " (forced)" : ""));
8443        }
8444
8445        try {
8446            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8447            PackageParser.collectCertificates(pkg, skipVerify);
8448        } catch (PackageParserException e) {
8449            throw PackageManagerException.from(e);
8450        } finally {
8451            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8452        }
8453    }
8454
8455    /**
8456     *  Traces a package scan.
8457     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8458     */
8459    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8460            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8461        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8462        try {
8463            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8464        } finally {
8465            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8466        }
8467    }
8468
8469    /**
8470     *  Scans a package and returns the newly parsed package.
8471     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8472     */
8473    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8474            long currentTime, UserHandle user) throws PackageManagerException {
8475        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8476        PackageParser pp = new PackageParser();
8477        pp.setSeparateProcesses(mSeparateProcesses);
8478        pp.setOnlyCoreApps(mOnlyCore);
8479        pp.setDisplayMetrics(mMetrics);
8480        pp.setCallback(mPackageParserCallback);
8481
8482        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8483        final PackageParser.Package pkg;
8484        try {
8485            pkg = pp.parsePackage(scanFile, parseFlags);
8486        } catch (PackageParserException e) {
8487            throw PackageManagerException.from(e);
8488        } finally {
8489            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8490        }
8491
8492        // Static shared libraries have synthetic package names
8493        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8494            renameStaticSharedLibraryPackage(pkg);
8495        }
8496
8497        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8498    }
8499
8500    /**
8501     *  Scans a package and returns the newly parsed package.
8502     *  @throws PackageManagerException on a parse error.
8503     */
8504    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8505            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8506            @Nullable UserHandle user)
8507                    throws PackageManagerException {
8508        // If the package has children and this is the first dive in the function
8509        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8510        // packages (parent and children) would be successfully scanned before the
8511        // actual scan since scanning mutates internal state and we want to atomically
8512        // install the package and its children.
8513        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8514            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8515                scanFlags |= SCAN_CHECK_ONLY;
8516            }
8517        } else {
8518            scanFlags &= ~SCAN_CHECK_ONLY;
8519        }
8520
8521        // Scan the parent
8522        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8523                scanFlags, currentTime, user);
8524
8525        // Scan the children
8526        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8527        for (int i = 0; i < childCount; i++) {
8528            PackageParser.Package childPackage = pkg.childPackages.get(i);
8529            addForInitLI(childPackage, parseFlags, scanFlags,
8530                    currentTime, user);
8531        }
8532
8533
8534        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8535            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8536        }
8537
8538        return scannedPkg;
8539    }
8540
8541    /**
8542     * Returns if full apk verification can be skipped for the whole package, including the splits.
8543     */
8544    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8545        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8546            return false;
8547        }
8548        // TODO: Allow base and splits to be verified individually.
8549        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8550            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8551                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8552                    return false;
8553                }
8554            }
8555        }
8556        return true;
8557    }
8558
8559    /**
8560     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8561     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8562     * match one in a trusted source, and should be done separately.
8563     */
8564    private boolean canSkipFullApkVerification(String apkPath) {
8565        byte[] rootHashObserved = null;
8566        try {
8567            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8568            if (rootHashObserved == null) {
8569                return false;  // APK does not contain Merkle tree root hash.
8570            }
8571            synchronized (mInstallLock) {
8572                // Returns whether the observed root hash matches what kernel has.
8573                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8574                return true;
8575            }
8576        } catch (InstallerException | IOException | DigestException |
8577                NoSuchAlgorithmException e) {
8578            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8579        }
8580        return false;
8581    }
8582
8583    /**
8584     * Adds a new package to the internal data structures during platform initialization.
8585     * <p>After adding, the package is known to the system and available for querying.
8586     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8587     * etc...], additional checks are performed. Basic verification [such as ensuring
8588     * matching signatures, checking version codes, etc...] occurs if the package is
8589     * identical to a previously known package. If the package fails a signature check,
8590     * the version installed on /data will be removed. If the version of the new package
8591     * is less than or equal than the version on /data, it will be ignored.
8592     * <p>Regardless of the package location, the results are applied to the internal
8593     * structures and the package is made available to the rest of the system.
8594     * <p>NOTE: The return value should be removed. It's the passed in package object.
8595     */
8596    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8597            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8598            @Nullable UserHandle user)
8599                    throws PackageManagerException {
8600        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8601        final String renamedPkgName;
8602        final PackageSetting disabledPkgSetting;
8603        final boolean isSystemPkgUpdated;
8604        final boolean pkgAlreadyExists;
8605        PackageSetting pkgSetting;
8606
8607        // NOTE: installPackageLI() has the same code to setup the package's
8608        // application info. This probably should be done lower in the call
8609        // stack [such as scanPackageOnly()]. However, we verify the application
8610        // info prior to that [in scanPackageNew()] and thus have to setup
8611        // the application info early.
8612        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8613        pkg.setApplicationInfoCodePath(pkg.codePath);
8614        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8615        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8616        pkg.setApplicationInfoResourcePath(pkg.codePath);
8617        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8618        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8619
8620        synchronized (mPackages) {
8621            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8622            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8623            if (realPkgName != null) {
8624                ensurePackageRenamed(pkg, renamedPkgName);
8625            }
8626            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8627            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8628            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8629            pkgAlreadyExists = pkgSetting != null;
8630            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8631            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8632            isSystemPkgUpdated = disabledPkgSetting != null;
8633
8634            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8635                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8636            }
8637
8638            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8639                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8640                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8641                    : null;
8642            if (DEBUG_PACKAGE_SCANNING
8643                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8644                    && sharedUserSetting != null) {
8645                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8646                        + " (uid=" + sharedUserSetting.userId + "):"
8647                        + " packages=" + sharedUserSetting.packages);
8648            }
8649
8650            if (scanSystemPartition) {
8651                // Potentially prune child packages. If the application on the /system
8652                // partition has been updated via OTA, but, is still disabled by a
8653                // version on /data, cycle through all of its children packages and
8654                // remove children that are no longer defined.
8655                if (isSystemPkgUpdated) {
8656                    final int scannedChildCount = (pkg.childPackages != null)
8657                            ? pkg.childPackages.size() : 0;
8658                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8659                            ? disabledPkgSetting.childPackageNames.size() : 0;
8660                    for (int i = 0; i < disabledChildCount; i++) {
8661                        String disabledChildPackageName =
8662                                disabledPkgSetting.childPackageNames.get(i);
8663                        boolean disabledPackageAvailable = false;
8664                        for (int j = 0; j < scannedChildCount; j++) {
8665                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8666                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8667                                disabledPackageAvailable = true;
8668                                break;
8669                            }
8670                        }
8671                        if (!disabledPackageAvailable) {
8672                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8673                        }
8674                    }
8675                    // we're updating the disabled package, so, scan it as the package setting
8676                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8677                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8678                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8679                            (pkg == mPlatformPackage), user);
8680                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8681                }
8682            }
8683        }
8684
8685        final boolean newPkgChangedPaths =
8686                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8687        final boolean newPkgVersionGreater =
8688                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8689        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8690                && newPkgChangedPaths && newPkgVersionGreater;
8691        if (isSystemPkgBetter) {
8692            // The version of the application on /system is greater than the version on
8693            // /data. Switch back to the application on /system.
8694            // It's safe to assume the application on /system will correctly scan. If not,
8695            // there won't be a working copy of the application.
8696            synchronized (mPackages) {
8697                // just remove the loaded entries from package lists
8698                mPackages.remove(pkgSetting.name);
8699            }
8700
8701            logCriticalInfo(Log.WARN,
8702                    "System package updated;"
8703                    + " name: " + pkgSetting.name
8704                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8705                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8706
8707            final InstallArgs args = createInstallArgsForExisting(
8708                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8709                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8710            args.cleanUpResourcesLI();
8711            synchronized (mPackages) {
8712                mSettings.enableSystemPackageLPw(pkgSetting.name);
8713            }
8714        }
8715
8716        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8717            // The version of the application on the /system partition is less than or
8718            // equal to the version on the /data partition. Throw an exception and use
8719            // the application already installed on the /data partition.
8720            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8721                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8722                    + " better than this " + pkg.getLongVersionCode());
8723        }
8724
8725        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8726        // force re-collecting certificate.
8727        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8728                disabledPkgSetting);
8729        // Full APK verification can be skipped during certificate collection, only if the file is
8730        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8731        // cases, only data in Signing Block is verified instead of the whole file.
8732        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8733                (forceCollect && canSkipFullPackageVerification(pkg));
8734        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8735
8736        boolean shouldHideSystemApp = false;
8737        // A new application appeared on /system, but, we already have a copy of
8738        // the application installed on /data.
8739        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8740                && !pkgSetting.isSystem()) {
8741
8742            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8743                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8744                logCriticalInfo(Log.WARN,
8745                        "System package signature mismatch;"
8746                        + " name: " + pkgSetting.name);
8747                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8748                        "scanPackageInternalLI")) {
8749                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8750                }
8751                pkgSetting = null;
8752            } else if (newPkgVersionGreater) {
8753                // The application on /system is newer than the application on /data.
8754                // Simply remove the application on /data [keeping application data]
8755                // and replace it with the version on /system.
8756                logCriticalInfo(Log.WARN,
8757                        "System package enabled;"
8758                        + " name: " + pkgSetting.name
8759                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8760                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8761                InstallArgs args = createInstallArgsForExisting(
8762                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8763                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8764                synchronized (mInstallLock) {
8765                    args.cleanUpResourcesLI();
8766                }
8767            } else {
8768                // The application on /system is older than the application on /data. Hide
8769                // the application on /system and the version on /data will be scanned later
8770                // and re-added like an update.
8771                shouldHideSystemApp = true;
8772                logCriticalInfo(Log.INFO,
8773                        "System package disabled;"
8774                        + " name: " + pkgSetting.name
8775                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8776                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8777            }
8778        }
8779
8780        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8781                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8782
8783        if (shouldHideSystemApp) {
8784            synchronized (mPackages) {
8785                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8786            }
8787        }
8788        return scannedPkg;
8789    }
8790
8791    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8792        // Derive the new package synthetic package name
8793        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8794                + pkg.staticSharedLibVersion);
8795    }
8796
8797    private static String fixProcessName(String defProcessName,
8798            String processName) {
8799        if (processName == null) {
8800            return defProcessName;
8801        }
8802        return processName;
8803    }
8804
8805    /**
8806     * Enforces that only the system UID or root's UID can call a method exposed
8807     * via Binder.
8808     *
8809     * @param message used as message if SecurityException is thrown
8810     * @throws SecurityException if the caller is not system or root
8811     */
8812    private static final void enforceSystemOrRoot(String message) {
8813        final int uid = Binder.getCallingUid();
8814        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8815            throw new SecurityException(message);
8816        }
8817    }
8818
8819    @Override
8820    public void performFstrimIfNeeded() {
8821        enforceSystemOrRoot("Only the system can request fstrim");
8822
8823        // Before everything else, see whether we need to fstrim.
8824        try {
8825            IStorageManager sm = PackageHelper.getStorageManager();
8826            if (sm != null) {
8827                boolean doTrim = false;
8828                final long interval = android.provider.Settings.Global.getLong(
8829                        mContext.getContentResolver(),
8830                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8831                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8832                if (interval > 0) {
8833                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8834                    if (timeSinceLast > interval) {
8835                        doTrim = true;
8836                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8837                                + "; running immediately");
8838                    }
8839                }
8840                if (doTrim) {
8841                    final boolean dexOptDialogShown;
8842                    synchronized (mPackages) {
8843                        dexOptDialogShown = mDexOptDialogShown;
8844                    }
8845                    if (!isFirstBoot() && dexOptDialogShown) {
8846                        try {
8847                            ActivityManager.getService().showBootMessage(
8848                                    mContext.getResources().getString(
8849                                            R.string.android_upgrading_fstrim), true);
8850                        } catch (RemoteException e) {
8851                        }
8852                    }
8853                    sm.runMaintenance();
8854                }
8855            } else {
8856                Slog.e(TAG, "storageManager service unavailable!");
8857            }
8858        } catch (RemoteException e) {
8859            // Can't happen; StorageManagerService is local
8860        }
8861    }
8862
8863    @Override
8864    public void updatePackagesIfNeeded() {
8865        enforceSystemOrRoot("Only the system can request package update");
8866
8867        // We need to re-extract after an OTA.
8868        boolean causeUpgrade = isUpgrade();
8869
8870        // First boot or factory reset.
8871        // Note: we also handle devices that are upgrading to N right now as if it is their
8872        //       first boot, as they do not have profile data.
8873        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8874
8875        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8876        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8877
8878        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8879            return;
8880        }
8881
8882        List<PackageParser.Package> pkgs;
8883        synchronized (mPackages) {
8884            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8885        }
8886
8887        final long startTime = System.nanoTime();
8888        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8889                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8890                    false /* bootComplete */);
8891
8892        final int elapsedTimeSeconds =
8893                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8894
8895        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8896        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8897        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8898        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8899        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8900    }
8901
8902    /*
8903     * Return the prebuilt profile path given a package base code path.
8904     */
8905    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8906        return pkg.baseCodePath + ".prof";
8907    }
8908
8909    /**
8910     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8911     * containing statistics about the invocation. The array consists of three elements,
8912     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8913     * and {@code numberOfPackagesFailed}.
8914     */
8915    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8916            final int compilationReason, boolean bootComplete) {
8917
8918        int numberOfPackagesVisited = 0;
8919        int numberOfPackagesOptimized = 0;
8920        int numberOfPackagesSkipped = 0;
8921        int numberOfPackagesFailed = 0;
8922        final int numberOfPackagesToDexopt = pkgs.size();
8923
8924        for (PackageParser.Package pkg : pkgs) {
8925            numberOfPackagesVisited++;
8926
8927            boolean useProfileForDexopt = false;
8928
8929            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8930                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8931                // that are already compiled.
8932                File profileFile = new File(getPrebuildProfilePath(pkg));
8933                // Copy profile if it exists.
8934                if (profileFile.exists()) {
8935                    try {
8936                        // We could also do this lazily before calling dexopt in
8937                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8938                        // is that we don't have a good way to say "do this only once".
8939                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8940                                pkg.applicationInfo.uid, pkg.packageName,
8941                                ArtManager.getProfileName(null))) {
8942                            Log.e(TAG, "Installer failed to copy system profile!");
8943                        } else {
8944                            // Disabled as this causes speed-profile compilation during first boot
8945                            // even if things are already compiled.
8946                            // useProfileForDexopt = true;
8947                        }
8948                    } catch (Exception e) {
8949                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8950                                e);
8951                    }
8952                } else {
8953                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8954                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8955                    // minimize the number off apps being speed-profile compiled during first boot.
8956                    // The other paths will not change the filter.
8957                    if (disabledPs != null && disabledPs.pkg.isStub) {
8958                        // The package is the stub one, remove the stub suffix to get the normal
8959                        // package and APK names.
8960                        String systemProfilePath =
8961                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8962                        profileFile = new File(systemProfilePath);
8963                        // If we have a profile for a compressed APK, copy it to the reference
8964                        // location.
8965                        // Note that copying the profile here will cause it to override the
8966                        // reference profile every OTA even though the existing reference profile
8967                        // may have more data. We can't copy during decompression since the
8968                        // directories are not set up at that point.
8969                        if (profileFile.exists()) {
8970                            try {
8971                                // We could also do this lazily before calling dexopt in
8972                                // PackageDexOptimizer to prevent this happening on first boot. The
8973                                // issue is that we don't have a good way to say "do this only
8974                                // once".
8975                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8976                                        pkg.applicationInfo.uid, pkg.packageName,
8977                                        ArtManager.getProfileName(null))) {
8978                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8979                                } else {
8980                                    useProfileForDexopt = true;
8981                                }
8982                            } catch (Exception e) {
8983                                Log.e(TAG, "Failed to copy profile " +
8984                                        profileFile.getAbsolutePath() + " ", e);
8985                            }
8986                        }
8987                    }
8988                }
8989            }
8990
8991            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8992                if (DEBUG_DEXOPT) {
8993                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8994                }
8995                numberOfPackagesSkipped++;
8996                continue;
8997            }
8998
8999            if (DEBUG_DEXOPT) {
9000                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9001                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9002            }
9003
9004            if (showDialog) {
9005                try {
9006                    ActivityManager.getService().showBootMessage(
9007                            mContext.getResources().getString(R.string.android_upgrading_apk,
9008                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9009                } catch (RemoteException e) {
9010                }
9011                synchronized (mPackages) {
9012                    mDexOptDialogShown = true;
9013                }
9014            }
9015
9016            int pkgCompilationReason = compilationReason;
9017            if (useProfileForDexopt) {
9018                // Use background dexopt mode to try and use the profile. Note that this does not
9019                // guarantee usage of the profile.
9020                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9021            }
9022
9023            // checkProfiles is false to avoid merging profiles during boot which
9024            // might interfere with background compilation (b/28612421).
9025            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9026            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9027            // trade-off worth doing to save boot time work.
9028            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9029            if (compilationReason == REASON_FIRST_BOOT) {
9030                // TODO: This doesn't cover the upgrade case, we should check for this too.
9031                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9032            }
9033            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9034                    pkg.packageName,
9035                    pkgCompilationReason,
9036                    dexoptFlags));
9037
9038            switch (primaryDexOptStaus) {
9039                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9040                    numberOfPackagesOptimized++;
9041                    break;
9042                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9043                    numberOfPackagesSkipped++;
9044                    break;
9045                case PackageDexOptimizer.DEX_OPT_FAILED:
9046                    numberOfPackagesFailed++;
9047                    break;
9048                default:
9049                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9050                    break;
9051            }
9052        }
9053
9054        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9055                numberOfPackagesFailed };
9056    }
9057
9058    @Override
9059    public void notifyPackageUse(String packageName, int reason) {
9060        synchronized (mPackages) {
9061            final int callingUid = Binder.getCallingUid();
9062            final int callingUserId = UserHandle.getUserId(callingUid);
9063            if (getInstantAppPackageName(callingUid) != null) {
9064                if (!isCallerSameApp(packageName, callingUid)) {
9065                    return;
9066                }
9067            } else {
9068                if (isInstantApp(packageName, callingUserId)) {
9069                    return;
9070                }
9071            }
9072            notifyPackageUseLocked(packageName, reason);
9073        }
9074    }
9075
9076    @GuardedBy("mPackages")
9077    private void notifyPackageUseLocked(String packageName, int reason) {
9078        final PackageParser.Package p = mPackages.get(packageName);
9079        if (p == null) {
9080            return;
9081        }
9082        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9083    }
9084
9085    @Override
9086    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9087            List<String> classPaths, String loaderIsa) {
9088        int userId = UserHandle.getCallingUserId();
9089        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9090        if (ai == null) {
9091            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9092                + loadingPackageName + ", user=" + userId);
9093            return;
9094        }
9095        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9096    }
9097
9098    @Override
9099    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9100            IDexModuleRegisterCallback callback) {
9101        int userId = UserHandle.getCallingUserId();
9102        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9103        DexManager.RegisterDexModuleResult result;
9104        if (ai == null) {
9105            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9106                     " calling user. package=" + packageName + ", user=" + userId);
9107            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9108        } else {
9109            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9110        }
9111
9112        if (callback != null) {
9113            mHandler.post(() -> {
9114                try {
9115                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9116                } catch (RemoteException e) {
9117                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9118                }
9119            });
9120        }
9121    }
9122
9123    /**
9124     * Ask the package manager to perform a dex-opt with the given compiler filter.
9125     *
9126     * Note: exposed only for the shell command to allow moving packages explicitly to a
9127     *       definite state.
9128     */
9129    @Override
9130    public boolean performDexOptMode(String packageName,
9131            boolean checkProfiles, String targetCompilerFilter, boolean force,
9132            boolean bootComplete, String splitName) {
9133        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9134                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9135                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9136        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9137                targetCompilerFilter, splitName, flags));
9138    }
9139
9140    /**
9141     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9142     * secondary dex files belonging to the given package.
9143     *
9144     * Note: exposed only for the shell command to allow moving packages explicitly to a
9145     *       definite state.
9146     */
9147    @Override
9148    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9149            boolean force) {
9150        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9151                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9152                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9153                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9154        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9155    }
9156
9157    /*package*/ boolean performDexOpt(DexoptOptions options) {
9158        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9159            return false;
9160        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9161            return false;
9162        }
9163
9164        if (options.isDexoptOnlySecondaryDex()) {
9165            return mDexManager.dexoptSecondaryDex(options);
9166        } else {
9167            int dexoptStatus = performDexOptWithStatus(options);
9168            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9169        }
9170    }
9171
9172    /**
9173     * Perform dexopt on the given package and return one of following result:
9174     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9175     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9176     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9177     */
9178    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9179        return performDexOptTraced(options);
9180    }
9181
9182    private int performDexOptTraced(DexoptOptions options) {
9183        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9184        try {
9185            return performDexOptInternal(options);
9186        } finally {
9187            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9188        }
9189    }
9190
9191    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9192    // if the package can now be considered up to date for the given filter.
9193    private int performDexOptInternal(DexoptOptions options) {
9194        PackageParser.Package p;
9195        synchronized (mPackages) {
9196            p = mPackages.get(options.getPackageName());
9197            if (p == null) {
9198                // Package could not be found. Report failure.
9199                return PackageDexOptimizer.DEX_OPT_FAILED;
9200            }
9201            mPackageUsage.maybeWriteAsync(mPackages);
9202            mCompilerStats.maybeWriteAsync();
9203        }
9204        long callingId = Binder.clearCallingIdentity();
9205        try {
9206            synchronized (mInstallLock) {
9207                return performDexOptInternalWithDependenciesLI(p, options);
9208            }
9209        } finally {
9210            Binder.restoreCallingIdentity(callingId);
9211        }
9212    }
9213
9214    public ArraySet<String> getOptimizablePackages() {
9215        ArraySet<String> pkgs = new ArraySet<String>();
9216        synchronized (mPackages) {
9217            for (PackageParser.Package p : mPackages.values()) {
9218                if (PackageDexOptimizer.canOptimizePackage(p)) {
9219                    pkgs.add(p.packageName);
9220                }
9221            }
9222        }
9223        return pkgs;
9224    }
9225
9226    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9227            DexoptOptions options) {
9228        // Select the dex optimizer based on the force parameter.
9229        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9230        //       allocate an object here.
9231        PackageDexOptimizer pdo = options.isForce()
9232                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9233                : mPackageDexOptimizer;
9234
9235        // Dexopt all dependencies first. Note: we ignore the return value and march on
9236        // on errors.
9237        // Note that we are going to call performDexOpt on those libraries as many times as
9238        // they are referenced in packages. When we do a batch of performDexOpt (for example
9239        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9240        // and the first package that uses the library will dexopt it. The
9241        // others will see that the compiled code for the library is up to date.
9242        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9243        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9244        if (!deps.isEmpty()) {
9245            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9246                    options.getCompilationReason(), options.getCompilerFilter(),
9247                    options.getSplitName(),
9248                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9249            for (PackageParser.Package depPackage : deps) {
9250                // TODO: Analyze and investigate if we (should) profile libraries.
9251                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9252                        getOrCreateCompilerPackageStats(depPackage),
9253                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9254            }
9255        }
9256        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9257                getOrCreateCompilerPackageStats(p),
9258                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9259    }
9260
9261    /**
9262     * Reconcile the information we have about the secondary dex files belonging to
9263     * {@code packagName} and the actual dex files. For all dex files that were
9264     * deleted, update the internal records and delete the generated oat files.
9265     */
9266    @Override
9267    public void reconcileSecondaryDexFiles(String packageName) {
9268        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9269            return;
9270        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9271            return;
9272        }
9273        mDexManager.reconcileSecondaryDexFiles(packageName);
9274    }
9275
9276    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9277    // a reference there.
9278    /*package*/ DexManager getDexManager() {
9279        return mDexManager;
9280    }
9281
9282    /**
9283     * Execute the background dexopt job immediately.
9284     */
9285    @Override
9286    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9287        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9288            return false;
9289        }
9290        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9291    }
9292
9293    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9294        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9295                || p.usesStaticLibraries != null) {
9296            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9297            Set<String> collectedNames = new HashSet<>();
9298            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9299
9300            retValue.remove(p);
9301
9302            return retValue;
9303        } else {
9304            return Collections.emptyList();
9305        }
9306    }
9307
9308    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9309            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9310        if (!collectedNames.contains(p.packageName)) {
9311            collectedNames.add(p.packageName);
9312            collected.add(p);
9313
9314            if (p.usesLibraries != null) {
9315                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9316                        null, collected, collectedNames);
9317            }
9318            if (p.usesOptionalLibraries != null) {
9319                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9320                        null, collected, collectedNames);
9321            }
9322            if (p.usesStaticLibraries != null) {
9323                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9324                        p.usesStaticLibrariesVersions, collected, collectedNames);
9325            }
9326        }
9327    }
9328
9329    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9330            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9331        final int libNameCount = libs.size();
9332        for (int i = 0; i < libNameCount; i++) {
9333            String libName = libs.get(i);
9334            long version = (versions != null && versions.length == libNameCount)
9335                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9336            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9337            if (libPkg != null) {
9338                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9339            }
9340        }
9341    }
9342
9343    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9344        synchronized (mPackages) {
9345            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9346            if (libEntry != null) {
9347                return mPackages.get(libEntry.apk);
9348            }
9349            return null;
9350        }
9351    }
9352
9353    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9354        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9355        if (versionedLib == null) {
9356            return null;
9357        }
9358        return versionedLib.get(version);
9359    }
9360
9361    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9362        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9363                pkg.staticSharedLibName);
9364        if (versionedLib == null) {
9365            return null;
9366        }
9367        long previousLibVersion = -1;
9368        final int versionCount = versionedLib.size();
9369        for (int i = 0; i < versionCount; i++) {
9370            final long libVersion = versionedLib.keyAt(i);
9371            if (libVersion < pkg.staticSharedLibVersion) {
9372                previousLibVersion = Math.max(previousLibVersion, libVersion);
9373            }
9374        }
9375        if (previousLibVersion >= 0) {
9376            return versionedLib.get(previousLibVersion);
9377        }
9378        return null;
9379    }
9380
9381    public void shutdown() {
9382        mPackageUsage.writeNow(mPackages);
9383        mCompilerStats.writeNow();
9384        mDexManager.writePackageDexUsageNow();
9385    }
9386
9387    @Override
9388    public void dumpProfiles(String packageName) {
9389        PackageParser.Package pkg;
9390        synchronized (mPackages) {
9391            pkg = mPackages.get(packageName);
9392            if (pkg == null) {
9393                throw new IllegalArgumentException("Unknown package: " + packageName);
9394            }
9395        }
9396        /* Only the shell, root, or the app user should be able to dump profiles. */
9397        int callingUid = Binder.getCallingUid();
9398        if (callingUid != Process.SHELL_UID &&
9399            callingUid != Process.ROOT_UID &&
9400            callingUid != pkg.applicationInfo.uid) {
9401            throw new SecurityException("dumpProfiles");
9402        }
9403
9404        synchronized (mInstallLock) {
9405            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9406            mArtManagerService.dumpProfiles(pkg);
9407            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9408        }
9409    }
9410
9411    @Override
9412    public void forceDexOpt(String packageName) {
9413        enforceSystemOrRoot("forceDexOpt");
9414
9415        PackageParser.Package pkg;
9416        synchronized (mPackages) {
9417            pkg = mPackages.get(packageName);
9418            if (pkg == null) {
9419                throw new IllegalArgumentException("Unknown package: " + packageName);
9420            }
9421        }
9422
9423        synchronized (mInstallLock) {
9424            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9425
9426            // Whoever is calling forceDexOpt wants a compiled package.
9427            // Don't use profiles since that may cause compilation to be skipped.
9428            final int res = performDexOptInternalWithDependenciesLI(
9429                    pkg,
9430                    new DexoptOptions(packageName,
9431                            getDefaultCompilerFilter(),
9432                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9433
9434            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9435            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9436                throw new IllegalStateException("Failed to dexopt: " + res);
9437            }
9438        }
9439    }
9440
9441    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9442        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9443            Slog.w(TAG, "Unable to update from " + oldPkg.name
9444                    + " to " + newPkg.packageName
9445                    + ": old package not in system partition");
9446            return false;
9447        } else if (mPackages.get(oldPkg.name) != null) {
9448            Slog.w(TAG, "Unable to update from " + oldPkg.name
9449                    + " to " + newPkg.packageName
9450                    + ": old package still exists");
9451            return false;
9452        }
9453        return true;
9454    }
9455
9456    void removeCodePathLI(File codePath) {
9457        if (codePath.isDirectory()) {
9458            try {
9459                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9460            } catch (InstallerException e) {
9461                Slog.w(TAG, "Failed to remove code path", e);
9462            }
9463        } else {
9464            codePath.delete();
9465        }
9466    }
9467
9468    private int[] resolveUserIds(int userId) {
9469        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9470    }
9471
9472    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9473        if (pkg == null) {
9474            Slog.wtf(TAG, "Package was null!", new Throwable());
9475            return;
9476        }
9477        clearAppDataLeafLIF(pkg, userId, flags);
9478        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9479        for (int i = 0; i < childCount; i++) {
9480            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9481        }
9482
9483        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9484    }
9485
9486    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9487        final PackageSetting ps;
9488        synchronized (mPackages) {
9489            ps = mSettings.mPackages.get(pkg.packageName);
9490        }
9491        for (int realUserId : resolveUserIds(userId)) {
9492            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9493            try {
9494                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9495                        ceDataInode);
9496            } catch (InstallerException e) {
9497                Slog.w(TAG, String.valueOf(e));
9498            }
9499        }
9500    }
9501
9502    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9503        if (pkg == null) {
9504            Slog.wtf(TAG, "Package was null!", new Throwable());
9505            return;
9506        }
9507        destroyAppDataLeafLIF(pkg, userId, flags);
9508        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9509        for (int i = 0; i < childCount; i++) {
9510            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9511        }
9512    }
9513
9514    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9515        final PackageSetting ps;
9516        synchronized (mPackages) {
9517            ps = mSettings.mPackages.get(pkg.packageName);
9518        }
9519        for (int realUserId : resolveUserIds(userId)) {
9520            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9521            try {
9522                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9523                        ceDataInode);
9524            } catch (InstallerException e) {
9525                Slog.w(TAG, String.valueOf(e));
9526            }
9527            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9528        }
9529    }
9530
9531    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9532        if (pkg == null) {
9533            Slog.wtf(TAG, "Package was null!", new Throwable());
9534            return;
9535        }
9536        destroyAppProfilesLeafLIF(pkg);
9537        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9538        for (int i = 0; i < childCount; i++) {
9539            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9540        }
9541    }
9542
9543    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9544        try {
9545            mInstaller.destroyAppProfiles(pkg.packageName);
9546        } catch (InstallerException e) {
9547            Slog.w(TAG, String.valueOf(e));
9548        }
9549    }
9550
9551    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9552        if (pkg == null) {
9553            Slog.wtf(TAG, "Package was null!", new Throwable());
9554            return;
9555        }
9556        mArtManagerService.clearAppProfiles(pkg);
9557        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9558        for (int i = 0; i < childCount; i++) {
9559            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9560        }
9561    }
9562
9563    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9564            long lastUpdateTime) {
9565        // Set parent install/update time
9566        PackageSetting ps = (PackageSetting) pkg.mExtras;
9567        if (ps != null) {
9568            ps.firstInstallTime = firstInstallTime;
9569            ps.lastUpdateTime = lastUpdateTime;
9570        }
9571        // Set children install/update time
9572        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9573        for (int i = 0; i < childCount; i++) {
9574            PackageParser.Package childPkg = pkg.childPackages.get(i);
9575            ps = (PackageSetting) childPkg.mExtras;
9576            if (ps != null) {
9577                ps.firstInstallTime = firstInstallTime;
9578                ps.lastUpdateTime = lastUpdateTime;
9579            }
9580        }
9581    }
9582
9583    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9584            SharedLibraryEntry file,
9585            PackageParser.Package changingLib) {
9586        if (file.path != null) {
9587            usesLibraryFiles.add(file.path);
9588            return;
9589        }
9590        PackageParser.Package p = mPackages.get(file.apk);
9591        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9592            // If we are doing this while in the middle of updating a library apk,
9593            // then we need to make sure to use that new apk for determining the
9594            // dependencies here.  (We haven't yet finished committing the new apk
9595            // to the package manager state.)
9596            if (p == null || p.packageName.equals(changingLib.packageName)) {
9597                p = changingLib;
9598            }
9599        }
9600        if (p != null) {
9601            usesLibraryFiles.addAll(p.getAllCodePaths());
9602            if (p.usesLibraryFiles != null) {
9603                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9604            }
9605        }
9606    }
9607
9608    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9609            PackageParser.Package changingLib) throws PackageManagerException {
9610        if (pkg == null) {
9611            return;
9612        }
9613        // The collection used here must maintain the order of addition (so
9614        // that libraries are searched in the correct order) and must have no
9615        // duplicates.
9616        Set<String> usesLibraryFiles = null;
9617        if (pkg.usesLibraries != null) {
9618            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9619                    null, null, pkg.packageName, changingLib, true,
9620                    pkg.applicationInfo.targetSdkVersion, null);
9621        }
9622        if (pkg.usesStaticLibraries != null) {
9623            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9624                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9625                    pkg.packageName, changingLib, true,
9626                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9627        }
9628        if (pkg.usesOptionalLibraries != null) {
9629            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9630                    null, null, pkg.packageName, changingLib, false,
9631                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9632        }
9633        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9634            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9635        } else {
9636            pkg.usesLibraryFiles = null;
9637        }
9638    }
9639
9640    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9641            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9642            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9643            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9644            throws PackageManagerException {
9645        final int libCount = requestedLibraries.size();
9646        for (int i = 0; i < libCount; i++) {
9647            final String libName = requestedLibraries.get(i);
9648            final long libVersion = requiredVersions != null ? requiredVersions[i]
9649                    : SharedLibraryInfo.VERSION_UNDEFINED;
9650            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9651            if (libEntry == null) {
9652                if (required) {
9653                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9654                            "Package " + packageName + " requires unavailable shared library "
9655                                    + libName + "; failing!");
9656                } else if (DEBUG_SHARED_LIBRARIES) {
9657                    Slog.i(TAG, "Package " + packageName
9658                            + " desires unavailable shared library "
9659                            + libName + "; ignoring!");
9660                }
9661            } else {
9662                if (requiredVersions != null && requiredCertDigests != null) {
9663                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9664                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9665                            "Package " + packageName + " requires unavailable static shared"
9666                                    + " library " + libName + " version "
9667                                    + libEntry.info.getLongVersion() + "; failing!");
9668                    }
9669
9670                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9671                    if (libPkg == null) {
9672                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9673                                "Package " + packageName + " requires unavailable static shared"
9674                                        + " library; failing!");
9675                    }
9676
9677                    final String[] expectedCertDigests = requiredCertDigests[i];
9678
9679
9680                    if (expectedCertDigests.length > 1) {
9681
9682                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9683                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9684                                ? PackageUtils.computeSignaturesSha256Digests(
9685                                libPkg.mSigningDetails.signatures)
9686                                : PackageUtils.computeSignaturesSha256Digests(
9687                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9688
9689                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9690                        // target O we don't parse the "additional-certificate" tags similarly
9691                        // how we only consider all certs only for apps targeting O (see above).
9692                        // Therefore, the size check is safe to make.
9693                        if (expectedCertDigests.length != libCertDigests.length) {
9694                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9695                                    "Package " + packageName + " requires differently signed" +
9696                                            " static shared library; failing!");
9697                        }
9698
9699                        // Use a predictable order as signature order may vary
9700                        Arrays.sort(libCertDigests);
9701                        Arrays.sort(expectedCertDigests);
9702
9703                        final int certCount = libCertDigests.length;
9704                        for (int j = 0; j < certCount; j++) {
9705                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9706                                throw new PackageManagerException(
9707                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9708                                        "Package " + packageName + " requires differently signed" +
9709                                                " static shared library; failing!");
9710                            }
9711                        }
9712                    } else {
9713
9714                        // lib signing cert could have rotated beyond the one expected, check to see
9715                        // if the new one has been blessed by the old
9716                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9717                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9718                            throw new PackageManagerException(
9719                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9720                                    "Package " + packageName + " requires differently signed" +
9721                                            " static shared library; failing!");
9722                        }
9723                    }
9724                }
9725
9726                if (outUsedLibraries == null) {
9727                    // Use LinkedHashSet to preserve the order of files added to
9728                    // usesLibraryFiles while eliminating duplicates.
9729                    outUsedLibraries = new LinkedHashSet<>();
9730                }
9731                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9732            }
9733        }
9734        return outUsedLibraries;
9735    }
9736
9737    private static boolean hasString(List<String> list, List<String> which) {
9738        if (list == null) {
9739            return false;
9740        }
9741        for (int i=list.size()-1; i>=0; i--) {
9742            for (int j=which.size()-1; j>=0; j--) {
9743                if (which.get(j).equals(list.get(i))) {
9744                    return true;
9745                }
9746            }
9747        }
9748        return false;
9749    }
9750
9751    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9752            PackageParser.Package changingPkg) {
9753        ArrayList<PackageParser.Package> res = null;
9754        for (PackageParser.Package pkg : mPackages.values()) {
9755            if (changingPkg != null
9756                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9757                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9758                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9759                            changingPkg.staticSharedLibName)) {
9760                return null;
9761            }
9762            if (res == null) {
9763                res = new ArrayList<>();
9764            }
9765            res.add(pkg);
9766            try {
9767                updateSharedLibrariesLPr(pkg, changingPkg);
9768            } catch (PackageManagerException e) {
9769                // If a system app update or an app and a required lib missing we
9770                // delete the package and for updated system apps keep the data as
9771                // it is better for the user to reinstall than to be in an limbo
9772                // state. Also libs disappearing under an app should never happen
9773                // - just in case.
9774                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9775                    final int flags = pkg.isUpdatedSystemApp()
9776                            ? PackageManager.DELETE_KEEP_DATA : 0;
9777                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9778                            flags , null, true, null);
9779                }
9780                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9781            }
9782        }
9783        return res;
9784    }
9785
9786    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9787            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9788            @Nullable UserHandle user) throws PackageManagerException {
9789        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9790        // If the package has children and this is the first dive in the function
9791        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9792        // whether all packages (parent and children) would be successfully scanned
9793        // before the actual scan since scanning mutates internal state and we want
9794        // to atomically install the package and its children.
9795        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9796            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9797                scanFlags |= SCAN_CHECK_ONLY;
9798            }
9799        } else {
9800            scanFlags &= ~SCAN_CHECK_ONLY;
9801        }
9802
9803        final PackageParser.Package scannedPkg;
9804        try {
9805            // Scan the parent
9806            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9807            // Scan the children
9808            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9809            for (int i = 0; i < childCount; i++) {
9810                PackageParser.Package childPkg = pkg.childPackages.get(i);
9811                scanPackageNewLI(childPkg, parseFlags,
9812                        scanFlags, currentTime, user);
9813            }
9814        } finally {
9815            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9816        }
9817
9818        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9819            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9820        }
9821
9822        return scannedPkg;
9823    }
9824
9825    /** The result of a package scan. */
9826    private static class ScanResult {
9827        /** Whether or not the package scan was successful */
9828        public final boolean success;
9829        /**
9830         * The final package settings. This may be the same object passed in
9831         * the {@link ScanRequest}, but, with modified values.
9832         */
9833        @Nullable public final PackageSetting pkgSetting;
9834        /** ABI code paths that have changed in the package scan */
9835        @Nullable public final List<String> changedAbiCodePath;
9836        public ScanResult(
9837                boolean success,
9838                @Nullable PackageSetting pkgSetting,
9839                @Nullable List<String> changedAbiCodePath) {
9840            this.success = success;
9841            this.pkgSetting = pkgSetting;
9842            this.changedAbiCodePath = changedAbiCodePath;
9843        }
9844    }
9845
9846    /** A package to be scanned */
9847    private static class ScanRequest {
9848        /** The parsed package */
9849        @NonNull public final PackageParser.Package pkg;
9850        /** Shared user settings, if the package has a shared user */
9851        @Nullable public final SharedUserSetting sharedUserSetting;
9852        /**
9853         * Package settings of the currently installed version.
9854         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9855         * during scan.
9856         */
9857        @Nullable public final PackageSetting pkgSetting;
9858        /** A copy of the settings for the currently installed version */
9859        @Nullable public final PackageSetting oldPkgSetting;
9860        /** Package settings for the disabled version on the /system partition */
9861        @Nullable public final PackageSetting disabledPkgSetting;
9862        /** Package settings for the installed version under its original package name */
9863        @Nullable public final PackageSetting originalPkgSetting;
9864        /** The real package name of a renamed application */
9865        @Nullable public final String realPkgName;
9866        public final @ParseFlags int parseFlags;
9867        public final @ScanFlags int scanFlags;
9868        /** The user for which the package is being scanned */
9869        @Nullable public final UserHandle user;
9870        /** Whether or not the platform package is being scanned */
9871        public final boolean isPlatformPackage;
9872        public ScanRequest(
9873                @NonNull PackageParser.Package pkg,
9874                @Nullable SharedUserSetting sharedUserSetting,
9875                @Nullable PackageSetting pkgSetting,
9876                @Nullable PackageSetting disabledPkgSetting,
9877                @Nullable PackageSetting originalPkgSetting,
9878                @Nullable String realPkgName,
9879                @ParseFlags int parseFlags,
9880                @ScanFlags int scanFlags,
9881                boolean isPlatformPackage,
9882                @Nullable UserHandle user) {
9883            this.pkg = pkg;
9884            this.pkgSetting = pkgSetting;
9885            this.sharedUserSetting = sharedUserSetting;
9886            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9887            this.disabledPkgSetting = disabledPkgSetting;
9888            this.originalPkgSetting = originalPkgSetting;
9889            this.realPkgName = realPkgName;
9890            this.parseFlags = parseFlags;
9891            this.scanFlags = scanFlags;
9892            this.isPlatformPackage = isPlatformPackage;
9893            this.user = user;
9894        }
9895    }
9896
9897    /**
9898     * Returns the actual scan flags depending upon the state of the other settings.
9899     * <p>Updated system applications will not have the following flags set
9900     * by default and need to be adjusted after the fact:
9901     * <ul>
9902     * <li>{@link #SCAN_AS_SYSTEM}</li>
9903     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9904     * <li>{@link #SCAN_AS_OEM}</li>
9905     * <li>{@link #SCAN_AS_VENDOR}</li>
9906     * <li>{@link #SCAN_AS_PRODUCT}</li>
9907     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9908     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9909     * </ul>
9910     */
9911    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9912            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9913            PackageParser.Package pkg) {
9914        if (disabledPkgSetting != null) {
9915            // updated system application, must at least have SCAN_AS_SYSTEM
9916            scanFlags |= SCAN_AS_SYSTEM;
9917            if ((disabledPkgSetting.pkgPrivateFlags
9918                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9919                scanFlags |= SCAN_AS_PRIVILEGED;
9920            }
9921            if ((disabledPkgSetting.pkgPrivateFlags
9922                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9923                scanFlags |= SCAN_AS_OEM;
9924            }
9925            if ((disabledPkgSetting.pkgPrivateFlags
9926                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9927                scanFlags |= SCAN_AS_VENDOR;
9928            }
9929            if ((disabledPkgSetting.pkgPrivateFlags
9930                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9931                scanFlags |= SCAN_AS_PRODUCT;
9932            }
9933        }
9934        if (pkgSetting != null) {
9935            final int userId = ((user == null) ? 0 : user.getIdentifier());
9936            if (pkgSetting.getInstantApp(userId)) {
9937                scanFlags |= SCAN_AS_INSTANT_APP;
9938            }
9939            if (pkgSetting.getVirtulalPreload(userId)) {
9940                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9941            }
9942        }
9943
9944        // Scan as privileged apps that share a user with a priv-app.
9945        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9946                && (pkg.mSharedUserId != null)) {
9947            SharedUserSetting sharedUserSetting = null;
9948            try {
9949                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9950            } catch (PackageManagerException ignore) {}
9951            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9952                // Exempt SharedUsers signed with the platform key.
9953                // TODO(b/72378145) Fix this exemption. Force signature apps
9954                // to whitelist their privileged permissions just like other
9955                // priv-apps.
9956                synchronized (mPackages) {
9957                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9958                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9959                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9960                        scanFlags |= SCAN_AS_PRIVILEGED;
9961                    }
9962                }
9963            }
9964        }
9965
9966        return scanFlags;
9967    }
9968
9969    @GuardedBy("mInstallLock")
9970    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9971            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9972            @Nullable UserHandle user) throws PackageManagerException {
9973
9974        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9975        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9976        if (realPkgName != null) {
9977            ensurePackageRenamed(pkg, renamedPkgName);
9978        }
9979        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9980        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9981        final PackageSetting disabledPkgSetting =
9982                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9983
9984        if (mTransferedPackages.contains(pkg.packageName)) {
9985            Slog.w(TAG, "Package " + pkg.packageName
9986                    + " was transferred to another, but its .apk remains");
9987        }
9988
9989        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9990        synchronized (mPackages) {
9991            applyPolicy(pkg, parseFlags, scanFlags);
9992            assertPackageIsValid(pkg, parseFlags, scanFlags);
9993
9994            SharedUserSetting sharedUserSetting = null;
9995            if (pkg.mSharedUserId != null) {
9996                // SIDE EFFECTS; may potentially allocate a new shared user
9997                sharedUserSetting = mSettings.getSharedUserLPw(
9998                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9999                if (DEBUG_PACKAGE_SCANNING) {
10000                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10001                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10002                                + " (uid=" + sharedUserSetting.userId + "):"
10003                                + " packages=" + sharedUserSetting.packages);
10004                }
10005            }
10006
10007            boolean scanSucceeded = false;
10008            try {
10009                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10010                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10011                        (pkg == mPlatformPackage), user);
10012                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10013                if (result.success) {
10014                    commitScanResultsLocked(request, result);
10015                }
10016                scanSucceeded = true;
10017            } finally {
10018                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10019                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10020                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10021                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10022                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10023                  }
10024            }
10025        }
10026        return pkg;
10027    }
10028
10029    /**
10030     * Commits the package scan and modifies system state.
10031     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10032     * of committing the package, leaving the system in an inconsistent state.
10033     * This needs to be fixed so, once we get to this point, no errors are
10034     * possible and the system is not left in an inconsistent state.
10035     */
10036    @GuardedBy("mPackages")
10037    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10038            throws PackageManagerException {
10039        final PackageParser.Package pkg = request.pkg;
10040        final @ParseFlags int parseFlags = request.parseFlags;
10041        final @ScanFlags int scanFlags = request.scanFlags;
10042        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10043        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10044        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10045        final UserHandle user = request.user;
10046        final String realPkgName = request.realPkgName;
10047        final PackageSetting pkgSetting = result.pkgSetting;
10048        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10049        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10050
10051        if (newPkgSettingCreated) {
10052            if (originalPkgSetting != null) {
10053                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10054            }
10055            // THROWS: when we can't allocate a user id. add call to check if there's
10056            // enough space to ensure we won't throw; otherwise, don't modify state
10057            mSettings.addUserToSettingLPw(pkgSetting);
10058
10059            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10060                mTransferedPackages.add(originalPkgSetting.name);
10061            }
10062        }
10063        // TODO(toddke): Consider a method specifically for modifying the Package object
10064        // post scan; or, moving this stuff out of the Package object since it has nothing
10065        // to do with the package on disk.
10066        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10067        // for creating the application ID. If we did this earlier, we would be saving the
10068        // correct ID.
10069        pkg.applicationInfo.uid = pkgSetting.appId;
10070
10071        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10072
10073        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10074            mTransferedPackages.add(pkg.packageName);
10075        }
10076
10077        // THROWS: when requested libraries that can't be found. it only changes
10078        // the state of the passed in pkg object, so, move to the top of the method
10079        // and allow it to abort
10080        if ((scanFlags & SCAN_BOOTING) == 0
10081                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10082            // Check all shared libraries and map to their actual file path.
10083            // We only do this here for apps not on a system dir, because those
10084            // are the only ones that can fail an install due to this.  We
10085            // will take care of the system apps by updating all of their
10086            // library paths after the scan is done. Also during the initial
10087            // scan don't update any libs as we do this wholesale after all
10088            // apps are scanned to avoid dependency based scanning.
10089            updateSharedLibrariesLPr(pkg, null);
10090        }
10091
10092        // All versions of a static shared library are referenced with the same
10093        // package name. Internally, we use a synthetic package name to allow
10094        // multiple versions of the same shared library to be installed. So,
10095        // we need to generate the synthetic package name of the latest shared
10096        // library in order to compare signatures.
10097        PackageSetting signatureCheckPs = pkgSetting;
10098        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10099            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10100            if (libraryEntry != null) {
10101                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10102            }
10103        }
10104
10105        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10106        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10107            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10108                // We just determined the app is signed correctly, so bring
10109                // over the latest parsed certs.
10110                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10111            } else {
10112                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10113                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10114                            "Package " + pkg.packageName + " upgrade keys do not match the "
10115                                    + "previously installed version");
10116                } else {
10117                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10118                    String msg = "System package " + pkg.packageName
10119                            + " signature changed; retaining data.";
10120                    reportSettingsProblem(Log.WARN, msg);
10121                }
10122            }
10123        } else {
10124            try {
10125                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10126                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10127                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10128                        pkg.mSigningDetails, compareCompat, compareRecover);
10129                // The new KeySets will be re-added later in the scanning process.
10130                if (compatMatch) {
10131                    synchronized (mPackages) {
10132                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10133                    }
10134                }
10135                // We just determined the app is signed correctly, so bring
10136                // over the latest parsed certs.
10137                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10138
10139
10140                // if this is is a sharedUser, check to see if the new package is signed by a newer
10141                // signing certificate than the existing one, and if so, copy over the new details
10142                if (signatureCheckPs.sharedUser != null
10143                        && pkg.mSigningDetails.hasAncestor(
10144                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10145                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10146                }
10147            } catch (PackageManagerException e) {
10148                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10149                    throw e;
10150                }
10151                // The signature has changed, but this package is in the system
10152                // image...  let's recover!
10153                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10154                // However...  if this package is part of a shared user, but it
10155                // doesn't match the signature of the shared user, let's fail.
10156                // What this means is that you can't change the signatures
10157                // associated with an overall shared user, which doesn't seem all
10158                // that unreasonable.
10159                if (signatureCheckPs.sharedUser != null) {
10160                    if (compareSignatures(
10161                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10162                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10163                        throw new PackageManagerException(
10164                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10165                                "Signature mismatch for shared user: "
10166                                        + pkgSetting.sharedUser);
10167                    }
10168                }
10169                // File a report about this.
10170                String msg = "System package " + pkg.packageName
10171                        + " signature changed; retaining data.";
10172                reportSettingsProblem(Log.WARN, msg);
10173            } catch (IllegalArgumentException e) {
10174
10175                // should never happen: certs matched when checking, but not when comparing
10176                // old to new for sharedUser
10177                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10178                        "Signing certificates comparison made on incomparable signing details"
10179                        + " but somehow passed verifySignatures!");
10180            }
10181        }
10182
10183        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10184            // This package wants to adopt ownership of permissions from
10185            // another package.
10186            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10187                final String origName = pkg.mAdoptPermissions.get(i);
10188                final PackageSetting orig = mSettings.getPackageLPr(origName);
10189                if (orig != null) {
10190                    if (verifyPackageUpdateLPr(orig, pkg)) {
10191                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10192                                + pkg.packageName);
10193                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10194                    }
10195                }
10196            }
10197        }
10198
10199        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10200            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10201                final String codePathString = changedAbiCodePath.get(i);
10202                try {
10203                    mInstaller.rmdex(codePathString,
10204                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10205                } catch (InstallerException ignored) {
10206                }
10207            }
10208        }
10209
10210        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10211            if (oldPkgSetting != null) {
10212                synchronized (mPackages) {
10213                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10214                }
10215            }
10216        } else {
10217            final int userId = user == null ? 0 : user.getIdentifier();
10218            // Modify state for the given package setting
10219            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10220                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10221            if (pkgSetting.getInstantApp(userId)) {
10222                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10223            }
10224        }
10225    }
10226
10227    /**
10228     * Returns the "real" name of the package.
10229     * <p>This may differ from the package's actual name if the application has already
10230     * been installed under one of this package's original names.
10231     */
10232    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10233            @Nullable String renamedPkgName) {
10234        if (isPackageRenamed(pkg, renamedPkgName)) {
10235            return pkg.mRealPackage;
10236        }
10237        return null;
10238    }
10239
10240    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10241    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10242            @Nullable String renamedPkgName) {
10243        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10244    }
10245
10246    /**
10247     * Returns the original package setting.
10248     * <p>A package can migrate its name during an update. In this scenario, a package
10249     * designates a set of names that it considers as one of its original names.
10250     * <p>An original package must be signed identically and it must have the same
10251     * shared user [if any].
10252     */
10253    @GuardedBy("mPackages")
10254    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10255            @Nullable String renamedPkgName) {
10256        if (!isPackageRenamed(pkg, renamedPkgName)) {
10257            return null;
10258        }
10259        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10260            final PackageSetting originalPs =
10261                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10262            if (originalPs != null) {
10263                // the package is already installed under its original name...
10264                // but, should we use it?
10265                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10266                    // the new package is incompatible with the original
10267                    continue;
10268                } else if (originalPs.sharedUser != null) {
10269                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10270                        // the shared user id is incompatible with the original
10271                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10272                                + " to " + pkg.packageName + ": old uid "
10273                                + originalPs.sharedUser.name
10274                                + " differs from " + pkg.mSharedUserId);
10275                        continue;
10276                    }
10277                    // TODO: Add case when shared user id is added [b/28144775]
10278                } else {
10279                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10280                            + pkg.packageName + " to old name " + originalPs.name);
10281                }
10282                return originalPs;
10283            }
10284        }
10285        return null;
10286    }
10287
10288    /**
10289     * Renames the package if it was installed under a different name.
10290     * <p>When we've already installed the package under an original name, update
10291     * the new package so we can continue to have the old name.
10292     */
10293    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10294            @NonNull String renamedPackageName) {
10295        if (pkg.mOriginalPackages == null
10296                || !pkg.mOriginalPackages.contains(renamedPackageName)
10297                || pkg.packageName.equals(renamedPackageName)) {
10298            return;
10299        }
10300        pkg.setPackageName(renamedPackageName);
10301    }
10302
10303    /**
10304     * Just scans the package without any side effects.
10305     * <p>Not entirely true at the moment. There is still one side effect -- this
10306     * method potentially modifies a live {@link PackageSetting} object representing
10307     * the package being scanned. This will be resolved in the future.
10308     *
10309     * @param request Information about the package to be scanned
10310     * @param isUnderFactoryTest Whether or not the device is under factory test
10311     * @param currentTime The current time, in millis
10312     * @return The results of the scan
10313     */
10314    @GuardedBy("mInstallLock")
10315    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10316            boolean isUnderFactoryTest, long currentTime)
10317                    throws PackageManagerException {
10318        final PackageParser.Package pkg = request.pkg;
10319        PackageSetting pkgSetting = request.pkgSetting;
10320        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10321        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10322        final @ParseFlags int parseFlags = request.parseFlags;
10323        final @ScanFlags int scanFlags = request.scanFlags;
10324        final String realPkgName = request.realPkgName;
10325        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10326        final UserHandle user = request.user;
10327        final boolean isPlatformPackage = request.isPlatformPackage;
10328
10329        List<String> changedAbiCodePath = null;
10330
10331        if (DEBUG_PACKAGE_SCANNING) {
10332            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10333                Log.d(TAG, "Scanning package " + pkg.packageName);
10334        }
10335
10336        if (Build.IS_DEBUGGABLE &&
10337                pkg.isPrivileged() &&
10338                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10339            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10340        }
10341
10342        // Initialize package source and resource directories
10343        final File scanFile = new File(pkg.codePath);
10344        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10345        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10346
10347        // We keep references to the derived CPU Abis from settings in oder to reuse
10348        // them in the case where we're not upgrading or booting for the first time.
10349        String primaryCpuAbiFromSettings = null;
10350        String secondaryCpuAbiFromSettings = null;
10351        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10352
10353        if (!needToDeriveAbi) {
10354            if (pkgSetting != null) {
10355                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10356                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10357            } else {
10358                // Re-scanning a system package after uninstalling updates; need to derive ABI
10359                needToDeriveAbi = true;
10360            }
10361        }
10362
10363        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10364            PackageManagerService.reportSettingsProblem(Log.WARN,
10365                    "Package " + pkg.packageName + " shared user changed from "
10366                            + (pkgSetting.sharedUser != null
10367                            ? pkgSetting.sharedUser.name : "<nothing>")
10368                            + " to "
10369                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10370                            + "; replacing with new");
10371            pkgSetting = null;
10372        }
10373
10374        String[] usesStaticLibraries = null;
10375        if (pkg.usesStaticLibraries != null) {
10376            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10377            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10378        }
10379        final boolean createNewPackage = (pkgSetting == null);
10380        if (createNewPackage) {
10381            final String parentPackageName = (pkg.parentPackage != null)
10382                    ? pkg.parentPackage.packageName : null;
10383            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10384            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10385            // REMOVE SharedUserSetting from method; update in a separate call
10386            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10387                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10388                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10389                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10390                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10391                    user, true /*allowInstall*/, instantApp, virtualPreload,
10392                    parentPackageName, pkg.getChildPackageNames(),
10393                    UserManagerService.getInstance(), usesStaticLibraries,
10394                    pkg.usesStaticLibrariesVersions);
10395        } else {
10396            // REMOVE SharedUserSetting from method; update in a separate call.
10397            //
10398            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10399            // secondaryCpuAbi are not known at this point so we always update them
10400            // to null here, only to reset them at a later point.
10401            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10402                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10403                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10404                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10405                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10406                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10407        }
10408        if (createNewPackage && originalPkgSetting != null) {
10409            // This is the initial transition from the original package, so,
10410            // fix up the new package's name now. We must do this after looking
10411            // up the package under its new name, so getPackageLP takes care of
10412            // fiddling things correctly.
10413            pkg.setPackageName(originalPkgSetting.name);
10414
10415            // File a report about this.
10416            String msg = "New package " + pkgSetting.realName
10417                    + " renamed to replace old package " + pkgSetting.name;
10418            reportSettingsProblem(Log.WARN, msg);
10419        }
10420
10421        if (disabledPkgSetting != null) {
10422            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10423        }
10424
10425        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10426        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10427        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10428        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10429        // least restrictive selinux domain.
10430        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10431        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10432        // ensures that all packages continue to run in the same selinux domain.
10433        final int targetSdkVersion =
10434            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10435            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10436        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10437        // They currently can be if the sharedUser apps are signed with the platform key.
10438        final boolean isPrivileged = (sharedUserSetting != null) ?
10439            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10440
10441        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10442                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10443
10444        pkg.mExtras = pkgSetting;
10445        pkg.applicationInfo.processName = fixProcessName(
10446                pkg.applicationInfo.packageName,
10447                pkg.applicationInfo.processName);
10448
10449        if (!isPlatformPackage) {
10450            // Get all of our default paths setup
10451            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10452        }
10453
10454        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10455
10456        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10457            if (needToDeriveAbi) {
10458                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10459                final boolean extractNativeLibs = !pkg.isLibrary();
10460                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10461                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10462
10463                // Some system apps still use directory structure for native libraries
10464                // in which case we might end up not detecting abi solely based on apk
10465                // structure. Try to detect abi based on directory structure.
10466                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10467                        pkg.applicationInfo.primaryCpuAbi == null) {
10468                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10469                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10470                }
10471            } else {
10472                // This is not a first boot or an upgrade, don't bother deriving the
10473                // ABI during the scan. Instead, trust the value that was stored in the
10474                // package setting.
10475                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10476                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10477
10478                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10479
10480                if (DEBUG_ABI_SELECTION) {
10481                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10482                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10483                            pkg.applicationInfo.secondaryCpuAbi);
10484                }
10485            }
10486        } else {
10487            if ((scanFlags & SCAN_MOVE) != 0) {
10488                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10489                // but we already have this packages package info in the PackageSetting. We just
10490                // use that and derive the native library path based on the new codepath.
10491                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10492                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10493            }
10494
10495            // Set native library paths again. For moves, the path will be updated based on the
10496            // ABIs we've determined above. For non-moves, the path will be updated based on the
10497            // ABIs we determined during compilation, but the path will depend on the final
10498            // package path (after the rename away from the stage path).
10499            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10500        }
10501
10502        // This is a special case for the "system" package, where the ABI is
10503        // dictated by the zygote configuration (and init.rc). We should keep track
10504        // of this ABI so that we can deal with "normal" applications that run under
10505        // the same UID correctly.
10506        if (isPlatformPackage) {
10507            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10508                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10509        }
10510
10511        // If there's a mismatch between the abi-override in the package setting
10512        // and the abiOverride specified for the install. Warn about this because we
10513        // would've already compiled the app without taking the package setting into
10514        // account.
10515        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10516            if (cpuAbiOverride == null && pkg.packageName != null) {
10517                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10518                        " for package " + pkg.packageName);
10519            }
10520        }
10521
10522        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10523        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10524        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10525
10526        // Copy the derived override back to the parsed package, so that we can
10527        // update the package settings accordingly.
10528        pkg.cpuAbiOverride = cpuAbiOverride;
10529
10530        if (DEBUG_ABI_SELECTION) {
10531            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10532                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10533                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10534        }
10535
10536        // Push the derived path down into PackageSettings so we know what to
10537        // clean up at uninstall time.
10538        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10539
10540        if (DEBUG_ABI_SELECTION) {
10541            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10542                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10543                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10544        }
10545
10546        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10547            // We don't do this here during boot because we can do it all
10548            // at once after scanning all existing packages.
10549            //
10550            // We also do this *before* we perform dexopt on this package, so that
10551            // we can avoid redundant dexopts, and also to make sure we've got the
10552            // code and package path correct.
10553            changedAbiCodePath =
10554                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10555        }
10556
10557        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10558                android.Manifest.permission.FACTORY_TEST)) {
10559            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10560        }
10561
10562        if (isSystemApp(pkg)) {
10563            pkgSetting.isOrphaned = true;
10564        }
10565
10566        // Take care of first install / last update times.
10567        final long scanFileTime = getLastModifiedTime(pkg);
10568        if (currentTime != 0) {
10569            if (pkgSetting.firstInstallTime == 0) {
10570                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10571            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10572                pkgSetting.lastUpdateTime = currentTime;
10573            }
10574        } else if (pkgSetting.firstInstallTime == 0) {
10575            // We need *something*.  Take time time stamp of the file.
10576            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10577        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10578            if (scanFileTime != pkgSetting.timeStamp) {
10579                // A package on the system image has changed; consider this
10580                // to be an update.
10581                pkgSetting.lastUpdateTime = scanFileTime;
10582            }
10583        }
10584        pkgSetting.setTimeStamp(scanFileTime);
10585
10586        pkgSetting.pkg = pkg;
10587        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10588        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10589            pkgSetting.versionCode = pkg.getLongVersionCode();
10590        }
10591        // Update volume if needed
10592        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10593        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10594            Slog.i(PackageManagerService.TAG,
10595                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10596                    + " package " + pkg.packageName
10597                    + " volume from " + pkgSetting.volumeUuid
10598                    + " to " + volumeUuid);
10599            pkgSetting.volumeUuid = volumeUuid;
10600        }
10601
10602        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10603    }
10604
10605    /**
10606     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10607     */
10608    private static boolean apkHasCode(String fileName) {
10609        StrictJarFile jarFile = null;
10610        try {
10611            jarFile = new StrictJarFile(fileName,
10612                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10613            return jarFile.findEntry("classes.dex") != null;
10614        } catch (IOException ignore) {
10615        } finally {
10616            try {
10617                if (jarFile != null) {
10618                    jarFile.close();
10619                }
10620            } catch (IOException ignore) {}
10621        }
10622        return false;
10623    }
10624
10625    /**
10626     * Enforces code policy for the package. This ensures that if an APK has
10627     * declared hasCode="true" in its manifest that the APK actually contains
10628     * code.
10629     *
10630     * @throws PackageManagerException If bytecode could not be found when it should exist
10631     */
10632    private static void assertCodePolicy(PackageParser.Package pkg)
10633            throws PackageManagerException {
10634        final boolean shouldHaveCode =
10635                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10636        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10637            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10638                    "Package " + pkg.baseCodePath + " code is missing");
10639        }
10640
10641        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10642            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10643                final boolean splitShouldHaveCode =
10644                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10645                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10646                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10647                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10648                }
10649            }
10650        }
10651    }
10652
10653    /**
10654     * Applies policy to the parsed package based upon the given policy flags.
10655     * Ensures the package is in a good state.
10656     * <p>
10657     * Implementation detail: This method must NOT have any side effect. It would
10658     * ideally be static, but, it requires locks to read system state.
10659     */
10660    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10661            final @ScanFlags int scanFlags) {
10662        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10663            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10664            if (pkg.applicationInfo.isDirectBootAware()) {
10665                // we're direct boot aware; set for all components
10666                for (PackageParser.Service s : pkg.services) {
10667                    s.info.encryptionAware = s.info.directBootAware = true;
10668                }
10669                for (PackageParser.Provider p : pkg.providers) {
10670                    p.info.encryptionAware = p.info.directBootAware = true;
10671                }
10672                for (PackageParser.Activity a : pkg.activities) {
10673                    a.info.encryptionAware = a.info.directBootAware = true;
10674                }
10675                for (PackageParser.Activity r : pkg.receivers) {
10676                    r.info.encryptionAware = r.info.directBootAware = true;
10677                }
10678            }
10679            if (compressedFileExists(pkg.codePath)) {
10680                pkg.isStub = true;
10681            }
10682        } else {
10683            // non system apps can't be flagged as core
10684            pkg.coreApp = false;
10685            // clear flags not applicable to regular apps
10686            pkg.applicationInfo.flags &=
10687                    ~ApplicationInfo.FLAG_PERSISTENT;
10688            pkg.applicationInfo.privateFlags &=
10689                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10690            pkg.applicationInfo.privateFlags &=
10691                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10692            // cap permission priorities
10693            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10694                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10695                    pkg.permissionGroups.get(i).info.priority = 0;
10696                }
10697            }
10698        }
10699        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10700            // clear protected broadcasts
10701            pkg.protectedBroadcasts = null;
10702            // ignore export request for single user receivers
10703            if (pkg.receivers != null) {
10704                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10705                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10706                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10707                        receiver.info.exported = false;
10708                    }
10709                }
10710            }
10711            // ignore export request for single user services
10712            if (pkg.services != null) {
10713                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10714                    final PackageParser.Service service = pkg.services.get(i);
10715                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10716                        service.info.exported = false;
10717                    }
10718                }
10719            }
10720            // ignore export request for single user providers
10721            if (pkg.providers != null) {
10722                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10723                    final PackageParser.Provider provider = pkg.providers.get(i);
10724                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10725                        provider.info.exported = false;
10726                    }
10727                }
10728            }
10729        }
10730
10731        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10732            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10733        }
10734
10735        if ((scanFlags & SCAN_AS_OEM) != 0) {
10736            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10737        }
10738
10739        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10740            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10741        }
10742
10743        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10744            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10745        }
10746
10747        if (!isSystemApp(pkg)) {
10748            // Only system apps can use these features.
10749            pkg.mOriginalPackages = null;
10750            pkg.mRealPackage = null;
10751            pkg.mAdoptPermissions = null;
10752        }
10753    }
10754
10755    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10756            throws PackageManagerException {
10757        if (object == null) {
10758            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10759        }
10760        return object;
10761    }
10762
10763    /**
10764     * Asserts the parsed package is valid according to the given policy. If the
10765     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10766     * <p>
10767     * Implementation detail: This method must NOT have any side effects. It would
10768     * ideally be static, but, it requires locks to read system state.
10769     *
10770     * @throws PackageManagerException If the package fails any of the validation checks
10771     */
10772    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10773            final @ScanFlags int scanFlags)
10774                    throws PackageManagerException {
10775        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10776            assertCodePolicy(pkg);
10777        }
10778
10779        if (pkg.applicationInfo.getCodePath() == null ||
10780                pkg.applicationInfo.getResourcePath() == null) {
10781            // Bail out. The resource and code paths haven't been set.
10782            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10783                    "Code and resource paths haven't been set correctly");
10784        }
10785
10786        // Make sure we're not adding any bogus keyset info
10787        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10788        ksms.assertScannedPackageValid(pkg);
10789
10790        synchronized (mPackages) {
10791            // The special "android" package can only be defined once
10792            if (pkg.packageName.equals("android")) {
10793                if (mAndroidApplication != null) {
10794                    Slog.w(TAG, "*************************************************");
10795                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10796                    Slog.w(TAG, " codePath=" + pkg.codePath);
10797                    Slog.w(TAG, "*************************************************");
10798                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10799                            "Core android package being redefined.  Skipping.");
10800                }
10801            }
10802
10803            // A package name must be unique; don't allow duplicates
10804            if (mPackages.containsKey(pkg.packageName)) {
10805                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10806                        "Application package " + pkg.packageName
10807                        + " already installed.  Skipping duplicate.");
10808            }
10809
10810            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10811                // Static libs have a synthetic package name containing the version
10812                // but we still want the base name to be unique.
10813                if (mPackages.containsKey(pkg.manifestPackageName)) {
10814                    throw new PackageManagerException(
10815                            "Duplicate static shared lib provider package");
10816                }
10817
10818                // Static shared libraries should have at least O target SDK
10819                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10820                    throw new PackageManagerException(
10821                            "Packages declaring static-shared libs must target O SDK or higher");
10822                }
10823
10824                // Package declaring static a shared lib cannot be instant apps
10825                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10826                    throw new PackageManagerException(
10827                            "Packages declaring static-shared libs cannot be instant apps");
10828                }
10829
10830                // Package declaring static a shared lib cannot be renamed since the package
10831                // name is synthetic and apps can't code around package manager internals.
10832                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10833                    throw new PackageManagerException(
10834                            "Packages declaring static-shared libs cannot be renamed");
10835                }
10836
10837                // Package declaring static a shared lib cannot declare child packages
10838                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10839                    throw new PackageManagerException(
10840                            "Packages declaring static-shared libs cannot have child packages");
10841                }
10842
10843                // Package declaring static a shared lib cannot declare dynamic libs
10844                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10845                    throw new PackageManagerException(
10846                            "Packages declaring static-shared libs cannot declare dynamic libs");
10847                }
10848
10849                // Package declaring static a shared lib cannot declare shared users
10850                if (pkg.mSharedUserId != null) {
10851                    throw new PackageManagerException(
10852                            "Packages declaring static-shared libs cannot declare shared users");
10853                }
10854
10855                // Static shared libs cannot declare activities
10856                if (!pkg.activities.isEmpty()) {
10857                    throw new PackageManagerException(
10858                            "Static shared libs cannot declare activities");
10859                }
10860
10861                // Static shared libs cannot declare services
10862                if (!pkg.services.isEmpty()) {
10863                    throw new PackageManagerException(
10864                            "Static shared libs cannot declare services");
10865                }
10866
10867                // Static shared libs cannot declare providers
10868                if (!pkg.providers.isEmpty()) {
10869                    throw new PackageManagerException(
10870                            "Static shared libs cannot declare content providers");
10871                }
10872
10873                // Static shared libs cannot declare receivers
10874                if (!pkg.receivers.isEmpty()) {
10875                    throw new PackageManagerException(
10876                            "Static shared libs cannot declare broadcast receivers");
10877                }
10878
10879                // Static shared libs cannot declare permission groups
10880                if (!pkg.permissionGroups.isEmpty()) {
10881                    throw new PackageManagerException(
10882                            "Static shared libs cannot declare permission groups");
10883                }
10884
10885                // Static shared libs cannot declare permissions
10886                if (!pkg.permissions.isEmpty()) {
10887                    throw new PackageManagerException(
10888                            "Static shared libs cannot declare permissions");
10889                }
10890
10891                // Static shared libs cannot declare protected broadcasts
10892                if (pkg.protectedBroadcasts != null) {
10893                    throw new PackageManagerException(
10894                            "Static shared libs cannot declare protected broadcasts");
10895                }
10896
10897                // Static shared libs cannot be overlay targets
10898                if (pkg.mOverlayTarget != null) {
10899                    throw new PackageManagerException(
10900                            "Static shared libs cannot be overlay targets");
10901                }
10902
10903                // The version codes must be ordered as lib versions
10904                long minVersionCode = Long.MIN_VALUE;
10905                long maxVersionCode = Long.MAX_VALUE;
10906
10907                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10908                        pkg.staticSharedLibName);
10909                if (versionedLib != null) {
10910                    final int versionCount = versionedLib.size();
10911                    for (int i = 0; i < versionCount; i++) {
10912                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10913                        final long libVersionCode = libInfo.getDeclaringPackage()
10914                                .getLongVersionCode();
10915                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10916                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10917                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10918                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10919                        } else {
10920                            minVersionCode = maxVersionCode = libVersionCode;
10921                            break;
10922                        }
10923                    }
10924                }
10925                if (pkg.getLongVersionCode() < minVersionCode
10926                        || pkg.getLongVersionCode() > maxVersionCode) {
10927                    throw new PackageManagerException("Static shared"
10928                            + " lib version codes must be ordered as lib versions");
10929                }
10930            }
10931
10932            // Only privileged apps and updated privileged apps can add child packages.
10933            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10934                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10935                    throw new PackageManagerException("Only privileged apps can add child "
10936                            + "packages. Ignoring package " + pkg.packageName);
10937                }
10938                final int childCount = pkg.childPackages.size();
10939                for (int i = 0; i < childCount; i++) {
10940                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10941                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10942                            childPkg.packageName)) {
10943                        throw new PackageManagerException("Can't override child of "
10944                                + "another disabled app. Ignoring package " + pkg.packageName);
10945                    }
10946                }
10947            }
10948
10949            // If we're only installing presumed-existing packages, require that the
10950            // scanned APK is both already known and at the path previously established
10951            // for it.  Previously unknown packages we pick up normally, but if we have an
10952            // a priori expectation about this package's install presence, enforce it.
10953            // With a singular exception for new system packages. When an OTA contains
10954            // a new system package, we allow the codepath to change from a system location
10955            // to the user-installed location. If we don't allow this change, any newer,
10956            // user-installed version of the application will be ignored.
10957            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10958                if (mExpectingBetter.containsKey(pkg.packageName)) {
10959                    logCriticalInfo(Log.WARN,
10960                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10961                } else {
10962                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10963                    if (known != null) {
10964                        if (DEBUG_PACKAGE_SCANNING) {
10965                            Log.d(TAG, "Examining " + pkg.codePath
10966                                    + " and requiring known paths " + known.codePathString
10967                                    + " & " + known.resourcePathString);
10968                        }
10969                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10970                                || !pkg.applicationInfo.getResourcePath().equals(
10971                                        known.resourcePathString)) {
10972                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10973                                    "Application package " + pkg.packageName
10974                                    + " found at " + pkg.applicationInfo.getCodePath()
10975                                    + " but expected at " + known.codePathString
10976                                    + "; ignoring.");
10977                        }
10978                    } else {
10979                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10980                                "Application package " + pkg.packageName
10981                                + " not found; ignoring.");
10982                    }
10983                }
10984            }
10985
10986            // Verify that this new package doesn't have any content providers
10987            // that conflict with existing packages.  Only do this if the
10988            // package isn't already installed, since we don't want to break
10989            // things that are installed.
10990            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10991                final int N = pkg.providers.size();
10992                int i;
10993                for (i=0; i<N; i++) {
10994                    PackageParser.Provider p = pkg.providers.get(i);
10995                    if (p.info.authority != null) {
10996                        String names[] = p.info.authority.split(";");
10997                        for (int j = 0; j < names.length; j++) {
10998                            if (mProvidersByAuthority.containsKey(names[j])) {
10999                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11000                                final String otherPackageName =
11001                                        ((other != null && other.getComponentName() != null) ?
11002                                                other.getComponentName().getPackageName() : "?");
11003                                throw new PackageManagerException(
11004                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11005                                        "Can't install because provider name " + names[j]
11006                                                + " (in package " + pkg.applicationInfo.packageName
11007                                                + ") is already used by " + otherPackageName);
11008                            }
11009                        }
11010                    }
11011                }
11012            }
11013
11014            // Verify that packages sharing a user with a privileged app are marked as privileged.
11015            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11016                SharedUserSetting sharedUserSetting = null;
11017                try {
11018                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11019                } catch (PackageManagerException ignore) {}
11020                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11021                    // Exempt SharedUsers signed with the platform key.
11022                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11023                    if ((platformPkgSetting.signatures.mSigningDetails
11024                            != PackageParser.SigningDetails.UNKNOWN)
11025                            && (compareSignatures(
11026                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11027                                    pkg.mSigningDetails.signatures)
11028                                            != PackageManager.SIGNATURE_MATCH)) {
11029                        throw new PackageManagerException("Apps that share a user with a " +
11030                                "privileged app must themselves be marked as privileged. " +
11031                                pkg.packageName + " shares privileged user " +
11032                                pkg.mSharedUserId + ".");
11033                    }
11034                }
11035            }
11036
11037            // Apply policies specific for runtime resource overlays (RROs).
11038            if (pkg.mOverlayTarget != null) {
11039                // System overlays have some restrictions on their use of the 'static' state.
11040                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11041                    // We are scanning a system overlay. This can be the first scan of the
11042                    // system/vendor/oem partition, or an update to the system overlay.
11043                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11044                        // This must be an update to a system overlay.
11045                        final PackageSetting previousPkg = assertNotNull(
11046                                mSettings.getPackageLPr(pkg.packageName),
11047                                "previous package state not present");
11048
11049                        // Static overlays cannot be updated.
11050                        if (previousPkg.pkg.mOverlayIsStatic) {
11051                            throw new PackageManagerException("Overlay " + pkg.packageName +
11052                                    " is static and cannot be upgraded.");
11053                        // Non-static overlays cannot be converted to static overlays.
11054                        } else if (pkg.mOverlayIsStatic) {
11055                            throw new PackageManagerException("Overlay " + pkg.packageName +
11056                                    " cannot be upgraded into a static overlay.");
11057                        }
11058                    }
11059                } else {
11060                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11061                    if (pkg.mOverlayIsStatic) {
11062                        throw new PackageManagerException("Overlay " + pkg.packageName +
11063                                " is static but not pre-installed.");
11064                    }
11065
11066                    // The only case where we allow installation of a non-system overlay is when
11067                    // its signature is signed with the platform certificate.
11068                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11069                    if ((platformPkgSetting.signatures.mSigningDetails
11070                            != PackageParser.SigningDetails.UNKNOWN)
11071                            && (compareSignatures(
11072                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11073                                    pkg.mSigningDetails.signatures)
11074                                            != PackageManager.SIGNATURE_MATCH)) {
11075                        throw new PackageManagerException("Overlay " + pkg.packageName +
11076                                " must be signed with the platform certificate.");
11077                    }
11078                }
11079            }
11080        }
11081    }
11082
11083    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11084            int type, String declaringPackageName, long declaringVersionCode) {
11085        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11086        if (versionedLib == null) {
11087            versionedLib = new LongSparseArray<>();
11088            mSharedLibraries.put(name, versionedLib);
11089            if (type == SharedLibraryInfo.TYPE_STATIC) {
11090                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11091            }
11092        } else if (versionedLib.indexOfKey(version) >= 0) {
11093            return false;
11094        }
11095        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11096                version, type, declaringPackageName, declaringVersionCode);
11097        versionedLib.put(version, libEntry);
11098        return true;
11099    }
11100
11101    private boolean removeSharedLibraryLPw(String name, long version) {
11102        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11103        if (versionedLib == null) {
11104            return false;
11105        }
11106        final int libIdx = versionedLib.indexOfKey(version);
11107        if (libIdx < 0) {
11108            return false;
11109        }
11110        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11111        versionedLib.remove(version);
11112        if (versionedLib.size() <= 0) {
11113            mSharedLibraries.remove(name);
11114            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11115                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11116                        .getPackageName());
11117            }
11118        }
11119        return true;
11120    }
11121
11122    /**
11123     * Adds a scanned package to the system. When this method is finished, the package will
11124     * be available for query, resolution, etc...
11125     */
11126    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11127            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11128        final String pkgName = pkg.packageName;
11129        if (mCustomResolverComponentName != null &&
11130                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11131            setUpCustomResolverActivity(pkg);
11132        }
11133
11134        if (pkg.packageName.equals("android")) {
11135            synchronized (mPackages) {
11136                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11137                    // Set up information for our fall-back user intent resolution activity.
11138                    mPlatformPackage = pkg;
11139                    pkg.mVersionCode = mSdkVersion;
11140                    pkg.mVersionCodeMajor = 0;
11141                    mAndroidApplication = pkg.applicationInfo;
11142                    if (!mResolverReplaced) {
11143                        mResolveActivity.applicationInfo = mAndroidApplication;
11144                        mResolveActivity.name = ResolverActivity.class.getName();
11145                        mResolveActivity.packageName = mAndroidApplication.packageName;
11146                        mResolveActivity.processName = "system:ui";
11147                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11148                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11149                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11150                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11151                        mResolveActivity.exported = true;
11152                        mResolveActivity.enabled = true;
11153                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11154                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11155                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11156                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11157                                | ActivityInfo.CONFIG_ORIENTATION
11158                                | ActivityInfo.CONFIG_KEYBOARD
11159                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11160                        mResolveInfo.activityInfo = mResolveActivity;
11161                        mResolveInfo.priority = 0;
11162                        mResolveInfo.preferredOrder = 0;
11163                        mResolveInfo.match = 0;
11164                        mResolveComponentName = new ComponentName(
11165                                mAndroidApplication.packageName, mResolveActivity.name);
11166                    }
11167                }
11168            }
11169        }
11170
11171        ArrayList<PackageParser.Package> clientLibPkgs = null;
11172        // writer
11173        synchronized (mPackages) {
11174            boolean hasStaticSharedLibs = false;
11175
11176            // Any app can add new static shared libraries
11177            if (pkg.staticSharedLibName != null) {
11178                // Static shared libs don't allow renaming as they have synthetic package
11179                // names to allow install of multiple versions, so use name from manifest.
11180                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11181                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11182                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11183                    hasStaticSharedLibs = true;
11184                } else {
11185                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11186                                + pkg.staticSharedLibName + " already exists; skipping");
11187                }
11188                // Static shared libs cannot be updated once installed since they
11189                // use synthetic package name which includes the version code, so
11190                // not need to update other packages's shared lib dependencies.
11191            }
11192
11193            if (!hasStaticSharedLibs
11194                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11195                // Only system apps can add new dynamic shared libraries.
11196                if (pkg.libraryNames != null) {
11197                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11198                        String name = pkg.libraryNames.get(i);
11199                        boolean allowed = false;
11200                        if (pkg.isUpdatedSystemApp()) {
11201                            // New library entries can only be added through the
11202                            // system image.  This is important to get rid of a lot
11203                            // of nasty edge cases: for example if we allowed a non-
11204                            // system update of the app to add a library, then uninstalling
11205                            // the update would make the library go away, and assumptions
11206                            // we made such as through app install filtering would now
11207                            // have allowed apps on the device which aren't compatible
11208                            // with it.  Better to just have the restriction here, be
11209                            // conservative, and create many fewer cases that can negatively
11210                            // impact the user experience.
11211                            final PackageSetting sysPs = mSettings
11212                                    .getDisabledSystemPkgLPr(pkg.packageName);
11213                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11214                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11215                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11216                                        allowed = true;
11217                                        break;
11218                                    }
11219                                }
11220                            }
11221                        } else {
11222                            allowed = true;
11223                        }
11224                        if (allowed) {
11225                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11226                                    SharedLibraryInfo.VERSION_UNDEFINED,
11227                                    SharedLibraryInfo.TYPE_DYNAMIC,
11228                                    pkg.packageName, pkg.getLongVersionCode())) {
11229                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11230                                        + name + " already exists; skipping");
11231                            }
11232                        } else {
11233                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11234                                    + name + " that is not declared on system image; skipping");
11235                        }
11236                    }
11237
11238                    if ((scanFlags & SCAN_BOOTING) == 0) {
11239                        // If we are not booting, we need to update any applications
11240                        // that are clients of our shared library.  If we are booting,
11241                        // this will all be done once the scan is complete.
11242                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11243                    }
11244                }
11245            }
11246        }
11247
11248        if ((scanFlags & SCAN_BOOTING) != 0) {
11249            // No apps can run during boot scan, so they don't need to be frozen
11250        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11251            // Caller asked to not kill app, so it's probably not frozen
11252        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11253            // Caller asked us to ignore frozen check for some reason; they
11254            // probably didn't know the package name
11255        } else {
11256            // We're doing major surgery on this package, so it better be frozen
11257            // right now to keep it from launching
11258            checkPackageFrozen(pkgName);
11259        }
11260
11261        // Also need to kill any apps that are dependent on the library.
11262        if (clientLibPkgs != null) {
11263            for (int i=0; i<clientLibPkgs.size(); i++) {
11264                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11265                killApplication(clientPkg.applicationInfo.packageName,
11266                        clientPkg.applicationInfo.uid, "update lib");
11267            }
11268        }
11269
11270        // writer
11271        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11272
11273        synchronized (mPackages) {
11274            // We don't expect installation to fail beyond this point
11275
11276            // Add the new setting to mSettings
11277            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11278            // Add the new setting to mPackages
11279            mPackages.put(pkg.applicationInfo.packageName, pkg);
11280            // Make sure we don't accidentally delete its data.
11281            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11282            while (iter.hasNext()) {
11283                PackageCleanItem item = iter.next();
11284                if (pkgName.equals(item.packageName)) {
11285                    iter.remove();
11286                }
11287            }
11288
11289            // Add the package's KeySets to the global KeySetManagerService
11290            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11291            ksms.addScannedPackageLPw(pkg);
11292
11293            int N = pkg.providers.size();
11294            StringBuilder r = null;
11295            int i;
11296            for (i=0; i<N; i++) {
11297                PackageParser.Provider p = pkg.providers.get(i);
11298                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11299                        p.info.processName);
11300                mProviders.addProvider(p);
11301                p.syncable = p.info.isSyncable;
11302                if (p.info.authority != null) {
11303                    String names[] = p.info.authority.split(";");
11304                    p.info.authority = null;
11305                    for (int j = 0; j < names.length; j++) {
11306                        if (j == 1 && p.syncable) {
11307                            // We only want the first authority for a provider to possibly be
11308                            // syncable, so if we already added this provider using a different
11309                            // authority clear the syncable flag. We copy the provider before
11310                            // changing it because the mProviders object contains a reference
11311                            // to a provider that we don't want to change.
11312                            // Only do this for the second authority since the resulting provider
11313                            // object can be the same for all future authorities for this provider.
11314                            p = new PackageParser.Provider(p);
11315                            p.syncable = false;
11316                        }
11317                        if (!mProvidersByAuthority.containsKey(names[j])) {
11318                            mProvidersByAuthority.put(names[j], p);
11319                            if (p.info.authority == null) {
11320                                p.info.authority = names[j];
11321                            } else {
11322                                p.info.authority = p.info.authority + ";" + names[j];
11323                            }
11324                            if (DEBUG_PACKAGE_SCANNING) {
11325                                if (chatty)
11326                                    Log.d(TAG, "Registered content provider: " + names[j]
11327                                            + ", className = " + p.info.name + ", isSyncable = "
11328                                            + p.info.isSyncable);
11329                            }
11330                        } else {
11331                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11332                            Slog.w(TAG, "Skipping provider name " + names[j] +
11333                                    " (in package " + pkg.applicationInfo.packageName +
11334                                    "): name already used by "
11335                                    + ((other != null && other.getComponentName() != null)
11336                                            ? other.getComponentName().getPackageName() : "?"));
11337                        }
11338                    }
11339                }
11340                if (chatty) {
11341                    if (r == null) {
11342                        r = new StringBuilder(256);
11343                    } else {
11344                        r.append(' ');
11345                    }
11346                    r.append(p.info.name);
11347                }
11348            }
11349            if (r != null) {
11350                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11351            }
11352
11353            N = pkg.services.size();
11354            r = null;
11355            for (i=0; i<N; i++) {
11356                PackageParser.Service s = pkg.services.get(i);
11357                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11358                        s.info.processName);
11359                mServices.addService(s);
11360                if (chatty) {
11361                    if (r == null) {
11362                        r = new StringBuilder(256);
11363                    } else {
11364                        r.append(' ');
11365                    }
11366                    r.append(s.info.name);
11367                }
11368            }
11369            if (r != null) {
11370                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11371            }
11372
11373            N = pkg.receivers.size();
11374            r = null;
11375            for (i=0; i<N; i++) {
11376                PackageParser.Activity a = pkg.receivers.get(i);
11377                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11378                        a.info.processName);
11379                mReceivers.addActivity(a, "receiver");
11380                if (chatty) {
11381                    if (r == null) {
11382                        r = new StringBuilder(256);
11383                    } else {
11384                        r.append(' ');
11385                    }
11386                    r.append(a.info.name);
11387                }
11388            }
11389            if (r != null) {
11390                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11391            }
11392
11393            N = pkg.activities.size();
11394            r = null;
11395            for (i=0; i<N; i++) {
11396                PackageParser.Activity a = pkg.activities.get(i);
11397                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11398                        a.info.processName);
11399                mActivities.addActivity(a, "activity");
11400                if (chatty) {
11401                    if (r == null) {
11402                        r = new StringBuilder(256);
11403                    } else {
11404                        r.append(' ');
11405                    }
11406                    r.append(a.info.name);
11407                }
11408            }
11409            if (r != null) {
11410                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11411            }
11412
11413            // Don't allow ephemeral applications to define new permissions groups.
11414            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11415                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11416                        + " ignored: instant apps cannot define new permission groups.");
11417            } else {
11418                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11419            }
11420
11421            // Don't allow ephemeral applications to define new permissions.
11422            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11423                Slog.w(TAG, "Permissions from package " + pkg.packageName
11424                        + " ignored: instant apps cannot define new permissions.");
11425            } else {
11426                mPermissionManager.addAllPermissions(pkg, chatty);
11427            }
11428
11429            N = pkg.instrumentation.size();
11430            r = null;
11431            for (i=0; i<N; i++) {
11432                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11433                a.info.packageName = pkg.applicationInfo.packageName;
11434                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11435                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11436                a.info.splitNames = pkg.splitNames;
11437                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11438                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11439                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11440                a.info.dataDir = pkg.applicationInfo.dataDir;
11441                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11442                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11443                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11444                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11445                mInstrumentation.put(a.getComponentName(), a);
11446                if (chatty) {
11447                    if (r == null) {
11448                        r = new StringBuilder(256);
11449                    } else {
11450                        r.append(' ');
11451                    }
11452                    r.append(a.info.name);
11453                }
11454            }
11455            if (r != null) {
11456                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11457            }
11458
11459            if (pkg.protectedBroadcasts != null) {
11460                N = pkg.protectedBroadcasts.size();
11461                synchronized (mProtectedBroadcasts) {
11462                    for (i = 0; i < N; i++) {
11463                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11464                    }
11465                }
11466            }
11467        }
11468
11469        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11470    }
11471
11472    /**
11473     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11474     * is derived purely on the basis of the contents of {@code scanFile} and
11475     * {@code cpuAbiOverride}.
11476     *
11477     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11478     */
11479    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11480            boolean extractLibs)
11481                    throws PackageManagerException {
11482        // Give ourselves some initial paths; we'll come back for another
11483        // pass once we've determined ABI below.
11484        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11485
11486        // We would never need to extract libs for forward-locked and external packages,
11487        // since the container service will do it for us. We shouldn't attempt to
11488        // extract libs from system app when it was not updated.
11489        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11490                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11491            extractLibs = false;
11492        }
11493
11494        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11495        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11496
11497        NativeLibraryHelper.Handle handle = null;
11498        try {
11499            handle = NativeLibraryHelper.Handle.create(pkg);
11500            // TODO(multiArch): This can be null for apps that didn't go through the
11501            // usual installation process. We can calculate it again, like we
11502            // do during install time.
11503            //
11504            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11505            // unnecessary.
11506            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11507
11508            // Null out the abis so that they can be recalculated.
11509            pkg.applicationInfo.primaryCpuAbi = null;
11510            pkg.applicationInfo.secondaryCpuAbi = null;
11511            if (isMultiArch(pkg.applicationInfo)) {
11512                // Warn if we've set an abiOverride for multi-lib packages..
11513                // By definition, we need to copy both 32 and 64 bit libraries for
11514                // such packages.
11515                if (pkg.cpuAbiOverride != null
11516                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11517                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11518                }
11519
11520                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11521                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11522                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11523                    if (extractLibs) {
11524                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11525                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11526                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11527                                useIsaSpecificSubdirs);
11528                    } else {
11529                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11530                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11531                    }
11532                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11533                }
11534
11535                // Shared library native code should be in the APK zip aligned
11536                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11537                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11538                            "Shared library native lib extraction not supported");
11539                }
11540
11541                maybeThrowExceptionForMultiArchCopy(
11542                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11543
11544                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11545                    if (extractLibs) {
11546                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11547                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11548                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11549                                useIsaSpecificSubdirs);
11550                    } else {
11551                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11552                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11553                    }
11554                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11555                }
11556
11557                maybeThrowExceptionForMultiArchCopy(
11558                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11559
11560                if (abi64 >= 0) {
11561                    // Shared library native libs should be in the APK zip aligned
11562                    if (extractLibs && pkg.isLibrary()) {
11563                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11564                                "Shared library native lib extraction not supported");
11565                    }
11566                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11567                }
11568
11569                if (abi32 >= 0) {
11570                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11571                    if (abi64 >= 0) {
11572                        if (pkg.use32bitAbi) {
11573                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11574                            pkg.applicationInfo.primaryCpuAbi = abi;
11575                        } else {
11576                            pkg.applicationInfo.secondaryCpuAbi = abi;
11577                        }
11578                    } else {
11579                        pkg.applicationInfo.primaryCpuAbi = abi;
11580                    }
11581                }
11582            } else {
11583                String[] abiList = (cpuAbiOverride != null) ?
11584                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11585
11586                // Enable gross and lame hacks for apps that are built with old
11587                // SDK tools. We must scan their APKs for renderscript bitcode and
11588                // not launch them if it's present. Don't bother checking on devices
11589                // that don't have 64 bit support.
11590                boolean needsRenderScriptOverride = false;
11591                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11592                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11593                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11594                    needsRenderScriptOverride = true;
11595                }
11596
11597                final int copyRet;
11598                if (extractLibs) {
11599                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11600                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11601                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11602                } else {
11603                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11604                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11605                }
11606                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11607
11608                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11609                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11610                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11611                }
11612
11613                if (copyRet >= 0) {
11614                    // Shared libraries that have native libs must be multi-architecture
11615                    if (pkg.isLibrary()) {
11616                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11617                                "Shared library with native libs must be multiarch");
11618                    }
11619                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11620                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11621                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11622                } else if (needsRenderScriptOverride) {
11623                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11624                }
11625            }
11626        } catch (IOException ioe) {
11627            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11628        } finally {
11629            IoUtils.closeQuietly(handle);
11630        }
11631
11632        // Now that we've calculated the ABIs and determined if it's an internal app,
11633        // we will go ahead and populate the nativeLibraryPath.
11634        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11635    }
11636
11637    /**
11638     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11639     * i.e, so that all packages can be run inside a single process if required.
11640     *
11641     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11642     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11643     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11644     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11645     * updating a package that belongs to a shared user.
11646     *
11647     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11648     * adds unnecessary complexity.
11649     */
11650    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11651            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11652        List<String> changedAbiCodePath = null;
11653        String requiredInstructionSet = null;
11654        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11655            requiredInstructionSet = VMRuntime.getInstructionSet(
11656                     scannedPackage.applicationInfo.primaryCpuAbi);
11657        }
11658
11659        PackageSetting requirer = null;
11660        for (PackageSetting ps : packagesForUser) {
11661            // If packagesForUser contains scannedPackage, we skip it. This will happen
11662            // when scannedPackage is an update of an existing package. Without this check,
11663            // we will never be able to change the ABI of any package belonging to a shared
11664            // user, even if it's compatible with other packages.
11665            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11666                if (ps.primaryCpuAbiString == null) {
11667                    continue;
11668                }
11669
11670                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11671                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11672                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11673                    // this but there's not much we can do.
11674                    String errorMessage = "Instruction set mismatch, "
11675                            + ((requirer == null) ? "[caller]" : requirer)
11676                            + " requires " + requiredInstructionSet + " whereas " + ps
11677                            + " requires " + instructionSet;
11678                    Slog.w(TAG, errorMessage);
11679                }
11680
11681                if (requiredInstructionSet == null) {
11682                    requiredInstructionSet = instructionSet;
11683                    requirer = ps;
11684                }
11685            }
11686        }
11687
11688        if (requiredInstructionSet != null) {
11689            String adjustedAbi;
11690            if (requirer != null) {
11691                // requirer != null implies that either scannedPackage was null or that scannedPackage
11692                // did not require an ABI, in which case we have to adjust scannedPackage to match
11693                // the ABI of the set (which is the same as requirer's ABI)
11694                adjustedAbi = requirer.primaryCpuAbiString;
11695                if (scannedPackage != null) {
11696                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11697                }
11698            } else {
11699                // requirer == null implies that we're updating all ABIs in the set to
11700                // match scannedPackage.
11701                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11702            }
11703
11704            for (PackageSetting ps : packagesForUser) {
11705                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11706                    if (ps.primaryCpuAbiString != null) {
11707                        continue;
11708                    }
11709
11710                    ps.primaryCpuAbiString = adjustedAbi;
11711                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11712                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11713                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11714                        if (DEBUG_ABI_SELECTION) {
11715                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11716                                    + " (requirer="
11717                                    + (requirer != null ? requirer.pkg : "null")
11718                                    + ", scannedPackage="
11719                                    + (scannedPackage != null ? scannedPackage : "null")
11720                                    + ")");
11721                        }
11722                        if (changedAbiCodePath == null) {
11723                            changedAbiCodePath = new ArrayList<>();
11724                        }
11725                        changedAbiCodePath.add(ps.codePathString);
11726                    }
11727                }
11728            }
11729        }
11730        return changedAbiCodePath;
11731    }
11732
11733    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11734        synchronized (mPackages) {
11735            mResolverReplaced = true;
11736            // Set up information for custom user intent resolution activity.
11737            mResolveActivity.applicationInfo = pkg.applicationInfo;
11738            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11739            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11740            mResolveActivity.processName = pkg.applicationInfo.packageName;
11741            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11742            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11743                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11744            mResolveActivity.theme = 0;
11745            mResolveActivity.exported = true;
11746            mResolveActivity.enabled = true;
11747            mResolveInfo.activityInfo = mResolveActivity;
11748            mResolveInfo.priority = 0;
11749            mResolveInfo.preferredOrder = 0;
11750            mResolveInfo.match = 0;
11751            mResolveComponentName = mCustomResolverComponentName;
11752            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11753                    mResolveComponentName);
11754        }
11755    }
11756
11757    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11758        if (installerActivity == null) {
11759            if (DEBUG_INSTANT) {
11760                Slog.d(TAG, "Clear ephemeral installer activity");
11761            }
11762            mInstantAppInstallerActivity = null;
11763            return;
11764        }
11765
11766        if (DEBUG_INSTANT) {
11767            Slog.d(TAG, "Set ephemeral installer activity: "
11768                    + installerActivity.getComponentName());
11769        }
11770        // Set up information for ephemeral installer activity
11771        mInstantAppInstallerActivity = installerActivity;
11772        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11773                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11774        mInstantAppInstallerActivity.exported = true;
11775        mInstantAppInstallerActivity.enabled = true;
11776        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11777        mInstantAppInstallerInfo.priority = 1;
11778        mInstantAppInstallerInfo.preferredOrder = 1;
11779        mInstantAppInstallerInfo.isDefault = true;
11780        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11781                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11782    }
11783
11784    private static String calculateBundledApkRoot(final String codePathString) {
11785        final File codePath = new File(codePathString);
11786        final File codeRoot;
11787        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11788            codeRoot = Environment.getRootDirectory();
11789        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11790            codeRoot = Environment.getOemDirectory();
11791        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11792            codeRoot = Environment.getVendorDirectory();
11793        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11794            codeRoot = Environment.getOdmDirectory();
11795        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11796            codeRoot = Environment.getProductDirectory();
11797        } else {
11798            // Unrecognized code path; take its top real segment as the apk root:
11799            // e.g. /something/app/blah.apk => /something
11800            try {
11801                File f = codePath.getCanonicalFile();
11802                File parent = f.getParentFile();    // non-null because codePath is a file
11803                File tmp;
11804                while ((tmp = parent.getParentFile()) != null) {
11805                    f = parent;
11806                    parent = tmp;
11807                }
11808                codeRoot = f;
11809                Slog.w(TAG, "Unrecognized code path "
11810                        + codePath + " - using " + codeRoot);
11811            } catch (IOException e) {
11812                // Can't canonicalize the code path -- shenanigans?
11813                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11814                return Environment.getRootDirectory().getPath();
11815            }
11816        }
11817        return codeRoot.getPath();
11818    }
11819
11820    /**
11821     * Derive and set the location of native libraries for the given package,
11822     * which varies depending on where and how the package was installed.
11823     */
11824    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11825        final ApplicationInfo info = pkg.applicationInfo;
11826        final String codePath = pkg.codePath;
11827        final File codeFile = new File(codePath);
11828        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11829        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11830
11831        info.nativeLibraryRootDir = null;
11832        info.nativeLibraryRootRequiresIsa = false;
11833        info.nativeLibraryDir = null;
11834        info.secondaryNativeLibraryDir = null;
11835
11836        if (isApkFile(codeFile)) {
11837            // Monolithic install
11838            if (bundledApp) {
11839                // If "/system/lib64/apkname" exists, assume that is the per-package
11840                // native library directory to use; otherwise use "/system/lib/apkname".
11841                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11842                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11843                        getPrimaryInstructionSet(info));
11844
11845                // This is a bundled system app so choose the path based on the ABI.
11846                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11847                // is just the default path.
11848                final String apkName = deriveCodePathName(codePath);
11849                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11850                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11851                        apkName).getAbsolutePath();
11852
11853                if (info.secondaryCpuAbi != null) {
11854                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11855                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11856                            secondaryLibDir, apkName).getAbsolutePath();
11857                }
11858            } else if (asecApp) {
11859                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11860                        .getAbsolutePath();
11861            } else {
11862                final String apkName = deriveCodePathName(codePath);
11863                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11864                        .getAbsolutePath();
11865            }
11866
11867            info.nativeLibraryRootRequiresIsa = false;
11868            info.nativeLibraryDir = info.nativeLibraryRootDir;
11869        } else {
11870            // Cluster install
11871            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11872            info.nativeLibraryRootRequiresIsa = true;
11873
11874            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11875                    getPrimaryInstructionSet(info)).getAbsolutePath();
11876
11877            if (info.secondaryCpuAbi != null) {
11878                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11879                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11880            }
11881        }
11882    }
11883
11884    /**
11885     * Calculate the abis and roots for a bundled app. These can uniquely
11886     * be determined from the contents of the system partition, i.e whether
11887     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11888     * of this information, and instead assume that the system was built
11889     * sensibly.
11890     */
11891    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11892                                           PackageSetting pkgSetting) {
11893        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11894
11895        // If "/system/lib64/apkname" exists, assume that is the per-package
11896        // native library directory to use; otherwise use "/system/lib/apkname".
11897        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11898        setBundledAppAbi(pkg, apkRoot, apkName);
11899        // pkgSetting might be null during rescan following uninstall of updates
11900        // to a bundled app, so accommodate that possibility.  The settings in
11901        // that case will be established later from the parsed package.
11902        //
11903        // If the settings aren't null, sync them up with what we've just derived.
11904        // note that apkRoot isn't stored in the package settings.
11905        if (pkgSetting != null) {
11906            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11907            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11908        }
11909    }
11910
11911    /**
11912     * Deduces the ABI of a bundled app and sets the relevant fields on the
11913     * parsed pkg object.
11914     *
11915     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11916     *        under which system libraries are installed.
11917     * @param apkName the name of the installed package.
11918     */
11919    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11920        final File codeFile = new File(pkg.codePath);
11921
11922        final boolean has64BitLibs;
11923        final boolean has32BitLibs;
11924        if (isApkFile(codeFile)) {
11925            // Monolithic install
11926            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11927            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11928        } else {
11929            // Cluster install
11930            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11931            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11932                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11933                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11934                has64BitLibs = (new File(rootDir, isa)).exists();
11935            } else {
11936                has64BitLibs = false;
11937            }
11938            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11939                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11940                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11941                has32BitLibs = (new File(rootDir, isa)).exists();
11942            } else {
11943                has32BitLibs = false;
11944            }
11945        }
11946
11947        if (has64BitLibs && !has32BitLibs) {
11948            // The package has 64 bit libs, but not 32 bit libs. Its primary
11949            // ABI should be 64 bit. We can safely assume here that the bundled
11950            // native libraries correspond to the most preferred ABI in the list.
11951
11952            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11953            pkg.applicationInfo.secondaryCpuAbi = null;
11954        } else if (has32BitLibs && !has64BitLibs) {
11955            // The package has 32 bit libs but not 64 bit libs. Its primary
11956            // ABI should be 32 bit.
11957
11958            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11959            pkg.applicationInfo.secondaryCpuAbi = null;
11960        } else if (has32BitLibs && has64BitLibs) {
11961            // The application has both 64 and 32 bit bundled libraries. We check
11962            // here that the app declares multiArch support, and warn if it doesn't.
11963            //
11964            // We will be lenient here and record both ABIs. The primary will be the
11965            // ABI that's higher on the list, i.e, a device that's configured to prefer
11966            // 64 bit apps will see a 64 bit primary ABI,
11967
11968            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11969                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11970            }
11971
11972            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11973                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11974                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11975            } else {
11976                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11977                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11978            }
11979        } else {
11980            pkg.applicationInfo.primaryCpuAbi = null;
11981            pkg.applicationInfo.secondaryCpuAbi = null;
11982        }
11983    }
11984
11985    private void killApplication(String pkgName, int appId, String reason) {
11986        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11987    }
11988
11989    private void killApplication(String pkgName, int appId, int userId, String reason) {
11990        // Request the ActivityManager to kill the process(only for existing packages)
11991        // so that we do not end up in a confused state while the user is still using the older
11992        // version of the application while the new one gets installed.
11993        final long token = Binder.clearCallingIdentity();
11994        try {
11995            IActivityManager am = ActivityManager.getService();
11996            if (am != null) {
11997                try {
11998                    am.killApplication(pkgName, appId, userId, reason);
11999                } catch (RemoteException e) {
12000                }
12001            }
12002        } finally {
12003            Binder.restoreCallingIdentity(token);
12004        }
12005    }
12006
12007    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12008        // Remove the parent package setting
12009        PackageSetting ps = (PackageSetting) pkg.mExtras;
12010        if (ps != null) {
12011            removePackageLI(ps, chatty);
12012        }
12013        // Remove the child package setting
12014        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12015        for (int i = 0; i < childCount; i++) {
12016            PackageParser.Package childPkg = pkg.childPackages.get(i);
12017            ps = (PackageSetting) childPkg.mExtras;
12018            if (ps != null) {
12019                removePackageLI(ps, chatty);
12020            }
12021        }
12022    }
12023
12024    void removePackageLI(PackageSetting ps, boolean chatty) {
12025        if (DEBUG_INSTALL) {
12026            if (chatty)
12027                Log.d(TAG, "Removing package " + ps.name);
12028        }
12029
12030        // writer
12031        synchronized (mPackages) {
12032            mPackages.remove(ps.name);
12033            final PackageParser.Package pkg = ps.pkg;
12034            if (pkg != null) {
12035                cleanPackageDataStructuresLILPw(pkg, chatty);
12036            }
12037        }
12038    }
12039
12040    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12041        if (DEBUG_INSTALL) {
12042            if (chatty)
12043                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12044        }
12045
12046        // writer
12047        synchronized (mPackages) {
12048            // Remove the parent package
12049            mPackages.remove(pkg.applicationInfo.packageName);
12050            cleanPackageDataStructuresLILPw(pkg, chatty);
12051
12052            // Remove the child packages
12053            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12054            for (int i = 0; i < childCount; i++) {
12055                PackageParser.Package childPkg = pkg.childPackages.get(i);
12056                mPackages.remove(childPkg.applicationInfo.packageName);
12057                cleanPackageDataStructuresLILPw(childPkg, chatty);
12058            }
12059        }
12060    }
12061
12062    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12063        int N = pkg.providers.size();
12064        StringBuilder r = null;
12065        int i;
12066        for (i=0; i<N; i++) {
12067            PackageParser.Provider p = pkg.providers.get(i);
12068            mProviders.removeProvider(p);
12069            if (p.info.authority == null) {
12070
12071                /* There was another ContentProvider with this authority when
12072                 * this app was installed so this authority is null,
12073                 * Ignore it as we don't have to unregister the provider.
12074                 */
12075                continue;
12076            }
12077            String names[] = p.info.authority.split(";");
12078            for (int j = 0; j < names.length; j++) {
12079                if (mProvidersByAuthority.get(names[j]) == p) {
12080                    mProvidersByAuthority.remove(names[j]);
12081                    if (DEBUG_REMOVE) {
12082                        if (chatty)
12083                            Log.d(TAG, "Unregistered content provider: " + names[j]
12084                                    + ", className = " + p.info.name + ", isSyncable = "
12085                                    + p.info.isSyncable);
12086                    }
12087                }
12088            }
12089            if (DEBUG_REMOVE && chatty) {
12090                if (r == null) {
12091                    r = new StringBuilder(256);
12092                } else {
12093                    r.append(' ');
12094                }
12095                r.append(p.info.name);
12096            }
12097        }
12098        if (r != null) {
12099            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12100        }
12101
12102        N = pkg.services.size();
12103        r = null;
12104        for (i=0; i<N; i++) {
12105            PackageParser.Service s = pkg.services.get(i);
12106            mServices.removeService(s);
12107            if (chatty) {
12108                if (r == null) {
12109                    r = new StringBuilder(256);
12110                } else {
12111                    r.append(' ');
12112                }
12113                r.append(s.info.name);
12114            }
12115        }
12116        if (r != null) {
12117            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12118        }
12119
12120        N = pkg.receivers.size();
12121        r = null;
12122        for (i=0; i<N; i++) {
12123            PackageParser.Activity a = pkg.receivers.get(i);
12124            mReceivers.removeActivity(a, "receiver");
12125            if (DEBUG_REMOVE && chatty) {
12126                if (r == null) {
12127                    r = new StringBuilder(256);
12128                } else {
12129                    r.append(' ');
12130                }
12131                r.append(a.info.name);
12132            }
12133        }
12134        if (r != null) {
12135            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12136        }
12137
12138        N = pkg.activities.size();
12139        r = null;
12140        for (i=0; i<N; i++) {
12141            PackageParser.Activity a = pkg.activities.get(i);
12142            mActivities.removeActivity(a, "activity");
12143            if (DEBUG_REMOVE && chatty) {
12144                if (r == null) {
12145                    r = new StringBuilder(256);
12146                } else {
12147                    r.append(' ');
12148                }
12149                r.append(a.info.name);
12150            }
12151        }
12152        if (r != null) {
12153            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12154        }
12155
12156        mPermissionManager.removeAllPermissions(pkg, chatty);
12157
12158        N = pkg.instrumentation.size();
12159        r = null;
12160        for (i=0; i<N; i++) {
12161            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12162            mInstrumentation.remove(a.getComponentName());
12163            if (DEBUG_REMOVE && chatty) {
12164                if (r == null) {
12165                    r = new StringBuilder(256);
12166                } else {
12167                    r.append(' ');
12168                }
12169                r.append(a.info.name);
12170            }
12171        }
12172        if (r != null) {
12173            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12174        }
12175
12176        r = null;
12177        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12178            // Only system apps can hold shared libraries.
12179            if (pkg.libraryNames != null) {
12180                for (i = 0; i < pkg.libraryNames.size(); i++) {
12181                    String name = pkg.libraryNames.get(i);
12182                    if (removeSharedLibraryLPw(name, 0)) {
12183                        if (DEBUG_REMOVE && chatty) {
12184                            if (r == null) {
12185                                r = new StringBuilder(256);
12186                            } else {
12187                                r.append(' ');
12188                            }
12189                            r.append(name);
12190                        }
12191                    }
12192                }
12193            }
12194        }
12195
12196        r = null;
12197
12198        // Any package can hold static shared libraries.
12199        if (pkg.staticSharedLibName != null) {
12200            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12201                if (DEBUG_REMOVE && chatty) {
12202                    if (r == null) {
12203                        r = new StringBuilder(256);
12204                    } else {
12205                        r.append(' ');
12206                    }
12207                    r.append(pkg.staticSharedLibName);
12208                }
12209            }
12210        }
12211
12212        if (r != null) {
12213            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12214        }
12215    }
12216
12217
12218    final class ActivityIntentResolver
12219            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12220        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12221                boolean defaultOnly, int userId) {
12222            if (!sUserManager.exists(userId)) return null;
12223            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12224            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12225        }
12226
12227        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12228                int userId) {
12229            if (!sUserManager.exists(userId)) return null;
12230            mFlags = flags;
12231            return super.queryIntent(intent, resolvedType,
12232                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12233                    userId);
12234        }
12235
12236        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12237                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12238            if (!sUserManager.exists(userId)) return null;
12239            if (packageActivities == null) {
12240                return null;
12241            }
12242            mFlags = flags;
12243            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12244            final int N = packageActivities.size();
12245            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12246                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12247
12248            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12249            for (int i = 0; i < N; ++i) {
12250                intentFilters = packageActivities.get(i).intents;
12251                if (intentFilters != null && intentFilters.size() > 0) {
12252                    PackageParser.ActivityIntentInfo[] array =
12253                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12254                    intentFilters.toArray(array);
12255                    listCut.add(array);
12256                }
12257            }
12258            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12259        }
12260
12261        /**
12262         * Finds a privileged activity that matches the specified activity names.
12263         */
12264        private PackageParser.Activity findMatchingActivity(
12265                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12266            for (PackageParser.Activity sysActivity : activityList) {
12267                if (sysActivity.info.name.equals(activityInfo.name)) {
12268                    return sysActivity;
12269                }
12270                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12271                    return sysActivity;
12272                }
12273                if (sysActivity.info.targetActivity != null) {
12274                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12275                        return sysActivity;
12276                    }
12277                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12278                        return sysActivity;
12279                    }
12280                }
12281            }
12282            return null;
12283        }
12284
12285        public class IterGenerator<E> {
12286            public Iterator<E> generate(ActivityIntentInfo info) {
12287                return null;
12288            }
12289        }
12290
12291        public class ActionIterGenerator extends IterGenerator<String> {
12292            @Override
12293            public Iterator<String> generate(ActivityIntentInfo info) {
12294                return info.actionsIterator();
12295            }
12296        }
12297
12298        public class CategoriesIterGenerator extends IterGenerator<String> {
12299            @Override
12300            public Iterator<String> generate(ActivityIntentInfo info) {
12301                return info.categoriesIterator();
12302            }
12303        }
12304
12305        public class SchemesIterGenerator extends IterGenerator<String> {
12306            @Override
12307            public Iterator<String> generate(ActivityIntentInfo info) {
12308                return info.schemesIterator();
12309            }
12310        }
12311
12312        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12313            @Override
12314            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12315                return info.authoritiesIterator();
12316            }
12317        }
12318
12319        /**
12320         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12321         * MODIFIED. Do not pass in a list that should not be changed.
12322         */
12323        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12324                IterGenerator<T> generator, Iterator<T> searchIterator) {
12325            // loop through the set of actions; every one must be found in the intent filter
12326            while (searchIterator.hasNext()) {
12327                // we must have at least one filter in the list to consider a match
12328                if (intentList.size() == 0) {
12329                    break;
12330                }
12331
12332                final T searchAction = searchIterator.next();
12333
12334                // loop through the set of intent filters
12335                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12336                while (intentIter.hasNext()) {
12337                    final ActivityIntentInfo intentInfo = intentIter.next();
12338                    boolean selectionFound = false;
12339
12340                    // loop through the intent filter's selection criteria; at least one
12341                    // of them must match the searched criteria
12342                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12343                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12344                        final T intentSelection = intentSelectionIter.next();
12345                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12346                            selectionFound = true;
12347                            break;
12348                        }
12349                    }
12350
12351                    // the selection criteria wasn't found in this filter's set; this filter
12352                    // is not a potential match
12353                    if (!selectionFound) {
12354                        intentIter.remove();
12355                    }
12356                }
12357            }
12358        }
12359
12360        private boolean isProtectedAction(ActivityIntentInfo filter) {
12361            final Iterator<String> actionsIter = filter.actionsIterator();
12362            while (actionsIter != null && actionsIter.hasNext()) {
12363                final String filterAction = actionsIter.next();
12364                if (PROTECTED_ACTIONS.contains(filterAction)) {
12365                    return true;
12366                }
12367            }
12368            return false;
12369        }
12370
12371        /**
12372         * Adjusts the priority of the given intent filter according to policy.
12373         * <p>
12374         * <ul>
12375         * <li>The priority for non privileged applications is capped to '0'</li>
12376         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12377         * <li>The priority for unbundled updates to privileged applications is capped to the
12378         *      priority defined on the system partition</li>
12379         * </ul>
12380         * <p>
12381         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12382         * allowed to obtain any priority on any action.
12383         */
12384        private void adjustPriority(
12385                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12386            // nothing to do; priority is fine as-is
12387            if (intent.getPriority() <= 0) {
12388                return;
12389            }
12390
12391            final ActivityInfo activityInfo = intent.activity.info;
12392            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12393
12394            final boolean privilegedApp =
12395                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12396            if (!privilegedApp) {
12397                // non-privileged applications can never define a priority >0
12398                if (DEBUG_FILTERS) {
12399                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12400                            + " package: " + applicationInfo.packageName
12401                            + " activity: " + intent.activity.className
12402                            + " origPrio: " + intent.getPriority());
12403                }
12404                intent.setPriority(0);
12405                return;
12406            }
12407
12408            if (systemActivities == null) {
12409                // the system package is not disabled; we're parsing the system partition
12410                if (isProtectedAction(intent)) {
12411                    if (mDeferProtectedFilters) {
12412                        // We can't deal with these just yet. No component should ever obtain a
12413                        // >0 priority for a protected actions, with ONE exception -- the setup
12414                        // wizard. The setup wizard, however, cannot be known until we're able to
12415                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12416                        // until all intent filters have been processed. Chicken, meet egg.
12417                        // Let the filter temporarily have a high priority and rectify the
12418                        // priorities after all system packages have been scanned.
12419                        mProtectedFilters.add(intent);
12420                        if (DEBUG_FILTERS) {
12421                            Slog.i(TAG, "Protected action; save for later;"
12422                                    + " package: " + applicationInfo.packageName
12423                                    + " activity: " + intent.activity.className
12424                                    + " origPrio: " + intent.getPriority());
12425                        }
12426                        return;
12427                    } else {
12428                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12429                            Slog.i(TAG, "No setup wizard;"
12430                                + " All protected intents capped to priority 0");
12431                        }
12432                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12433                            if (DEBUG_FILTERS) {
12434                                Slog.i(TAG, "Found setup wizard;"
12435                                    + " allow priority " + intent.getPriority() + ";"
12436                                    + " package: " + intent.activity.info.packageName
12437                                    + " activity: " + intent.activity.className
12438                                    + " priority: " + intent.getPriority());
12439                            }
12440                            // setup wizard gets whatever it wants
12441                            return;
12442                        }
12443                        if (DEBUG_FILTERS) {
12444                            Slog.i(TAG, "Protected action; cap priority to 0;"
12445                                    + " package: " + intent.activity.info.packageName
12446                                    + " activity: " + intent.activity.className
12447                                    + " origPrio: " + intent.getPriority());
12448                        }
12449                        intent.setPriority(0);
12450                        return;
12451                    }
12452                }
12453                // privileged apps on the system image get whatever priority they request
12454                return;
12455            }
12456
12457            // privileged app unbundled update ... try to find the same activity
12458            final PackageParser.Activity foundActivity =
12459                    findMatchingActivity(systemActivities, activityInfo);
12460            if (foundActivity == null) {
12461                // this is a new activity; it cannot obtain >0 priority
12462                if (DEBUG_FILTERS) {
12463                    Slog.i(TAG, "New activity; cap priority to 0;"
12464                            + " package: " + applicationInfo.packageName
12465                            + " activity: " + intent.activity.className
12466                            + " origPrio: " + intent.getPriority());
12467                }
12468                intent.setPriority(0);
12469                return;
12470            }
12471
12472            // found activity, now check for filter equivalence
12473
12474            // a shallow copy is enough; we modify the list, not its contents
12475            final List<ActivityIntentInfo> intentListCopy =
12476                    new ArrayList<>(foundActivity.intents);
12477            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12478
12479            // find matching action subsets
12480            final Iterator<String> actionsIterator = intent.actionsIterator();
12481            if (actionsIterator != null) {
12482                getIntentListSubset(
12483                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12484                if (intentListCopy.size() == 0) {
12485                    // no more intents to match; we're not equivalent
12486                    if (DEBUG_FILTERS) {
12487                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12488                                + " package: " + applicationInfo.packageName
12489                                + " activity: " + intent.activity.className
12490                                + " origPrio: " + intent.getPriority());
12491                    }
12492                    intent.setPriority(0);
12493                    return;
12494                }
12495            }
12496
12497            // find matching category subsets
12498            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12499            if (categoriesIterator != null) {
12500                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12501                        categoriesIterator);
12502                if (intentListCopy.size() == 0) {
12503                    // no more intents to match; we're not equivalent
12504                    if (DEBUG_FILTERS) {
12505                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12506                                + " package: " + applicationInfo.packageName
12507                                + " activity: " + intent.activity.className
12508                                + " origPrio: " + intent.getPriority());
12509                    }
12510                    intent.setPriority(0);
12511                    return;
12512                }
12513            }
12514
12515            // find matching schemes subsets
12516            final Iterator<String> schemesIterator = intent.schemesIterator();
12517            if (schemesIterator != null) {
12518                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12519                        schemesIterator);
12520                if (intentListCopy.size() == 0) {
12521                    // no more intents to match; we're not equivalent
12522                    if (DEBUG_FILTERS) {
12523                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12524                                + " package: " + applicationInfo.packageName
12525                                + " activity: " + intent.activity.className
12526                                + " origPrio: " + intent.getPriority());
12527                    }
12528                    intent.setPriority(0);
12529                    return;
12530                }
12531            }
12532
12533            // find matching authorities subsets
12534            final Iterator<IntentFilter.AuthorityEntry>
12535                    authoritiesIterator = intent.authoritiesIterator();
12536            if (authoritiesIterator != null) {
12537                getIntentListSubset(intentListCopy,
12538                        new AuthoritiesIterGenerator(),
12539                        authoritiesIterator);
12540                if (intentListCopy.size() == 0) {
12541                    // no more intents to match; we're not equivalent
12542                    if (DEBUG_FILTERS) {
12543                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12544                                + " package: " + applicationInfo.packageName
12545                                + " activity: " + intent.activity.className
12546                                + " origPrio: " + intent.getPriority());
12547                    }
12548                    intent.setPriority(0);
12549                    return;
12550                }
12551            }
12552
12553            // we found matching filter(s); app gets the max priority of all intents
12554            int cappedPriority = 0;
12555            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12556                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12557            }
12558            if (intent.getPriority() > cappedPriority) {
12559                if (DEBUG_FILTERS) {
12560                    Slog.i(TAG, "Found matching filter(s);"
12561                            + " cap priority to " + cappedPriority + ";"
12562                            + " package: " + applicationInfo.packageName
12563                            + " activity: " + intent.activity.className
12564                            + " origPrio: " + intent.getPriority());
12565                }
12566                intent.setPriority(cappedPriority);
12567                return;
12568            }
12569            // all this for nothing; the requested priority was <= what was on the system
12570        }
12571
12572        public final void addActivity(PackageParser.Activity a, String type) {
12573            mActivities.put(a.getComponentName(), a);
12574            if (DEBUG_SHOW_INFO)
12575                Log.v(
12576                TAG, "  " + type + " " +
12577                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12578            if (DEBUG_SHOW_INFO)
12579                Log.v(TAG, "    Class=" + a.info.name);
12580            final int NI = a.intents.size();
12581            for (int j=0; j<NI; j++) {
12582                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12583                if ("activity".equals(type)) {
12584                    final PackageSetting ps =
12585                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12586                    final List<PackageParser.Activity> systemActivities =
12587                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12588                    adjustPriority(systemActivities, intent);
12589                }
12590                if (DEBUG_SHOW_INFO) {
12591                    Log.v(TAG, "    IntentFilter:");
12592                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12593                }
12594                if (!intent.debugCheck()) {
12595                    Log.w(TAG, "==> For Activity " + a.info.name);
12596                }
12597                addFilter(intent);
12598            }
12599        }
12600
12601        public final void removeActivity(PackageParser.Activity a, String type) {
12602            mActivities.remove(a.getComponentName());
12603            if (DEBUG_SHOW_INFO) {
12604                Log.v(TAG, "  " + type + " "
12605                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12606                                : a.info.name) + ":");
12607                Log.v(TAG, "    Class=" + a.info.name);
12608            }
12609            final int NI = a.intents.size();
12610            for (int j=0; j<NI; j++) {
12611                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12612                if (DEBUG_SHOW_INFO) {
12613                    Log.v(TAG, "    IntentFilter:");
12614                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12615                }
12616                removeFilter(intent);
12617            }
12618        }
12619
12620        @Override
12621        protected boolean allowFilterResult(
12622                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12623            ActivityInfo filterAi = filter.activity.info;
12624            for (int i=dest.size()-1; i>=0; i--) {
12625                ActivityInfo destAi = dest.get(i).activityInfo;
12626                if (destAi.name == filterAi.name
12627                        && destAi.packageName == filterAi.packageName) {
12628                    return false;
12629                }
12630            }
12631            return true;
12632        }
12633
12634        @Override
12635        protected ActivityIntentInfo[] newArray(int size) {
12636            return new ActivityIntentInfo[size];
12637        }
12638
12639        @Override
12640        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12641            if (!sUserManager.exists(userId)) return true;
12642            PackageParser.Package p = filter.activity.owner;
12643            if (p != null) {
12644                PackageSetting ps = (PackageSetting)p.mExtras;
12645                if (ps != null) {
12646                    // System apps are never considered stopped for purposes of
12647                    // filtering, because there may be no way for the user to
12648                    // actually re-launch them.
12649                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12650                            && ps.getStopped(userId);
12651                }
12652            }
12653            return false;
12654        }
12655
12656        @Override
12657        protected boolean isPackageForFilter(String packageName,
12658                PackageParser.ActivityIntentInfo info) {
12659            return packageName.equals(info.activity.owner.packageName);
12660        }
12661
12662        @Override
12663        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12664                int match, int userId) {
12665            if (!sUserManager.exists(userId)) return null;
12666            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12667                return null;
12668            }
12669            final PackageParser.Activity activity = info.activity;
12670            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12671            if (ps == null) {
12672                return null;
12673            }
12674            final PackageUserState userState = ps.readUserState(userId);
12675            ActivityInfo ai =
12676                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12677            if (ai == null) {
12678                return null;
12679            }
12680            final boolean matchExplicitlyVisibleOnly =
12681                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12682            final boolean matchVisibleToInstantApp =
12683                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12684            final boolean componentVisible =
12685                    matchVisibleToInstantApp
12686                    && info.isVisibleToInstantApp()
12687                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12688            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12689            // throw out filters that aren't visible to ephemeral apps
12690            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12691                return null;
12692            }
12693            // throw out instant app filters if we're not explicitly requesting them
12694            if (!matchInstantApp && userState.instantApp) {
12695                return null;
12696            }
12697            // throw out instant app filters if updates are available; will trigger
12698            // instant app resolution
12699            if (userState.instantApp && ps.isUpdateAvailable()) {
12700                return null;
12701            }
12702            final ResolveInfo res = new ResolveInfo();
12703            res.activityInfo = ai;
12704            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12705                res.filter = info;
12706            }
12707            if (info != null) {
12708                res.handleAllWebDataURI = info.handleAllWebDataURI();
12709            }
12710            res.priority = info.getPriority();
12711            res.preferredOrder = activity.owner.mPreferredOrder;
12712            //System.out.println("Result: " + res.activityInfo.className +
12713            //                   " = " + res.priority);
12714            res.match = match;
12715            res.isDefault = info.hasDefault;
12716            res.labelRes = info.labelRes;
12717            res.nonLocalizedLabel = info.nonLocalizedLabel;
12718            if (userNeedsBadging(userId)) {
12719                res.noResourceId = true;
12720            } else {
12721                res.icon = info.icon;
12722            }
12723            res.iconResourceId = info.icon;
12724            res.system = res.activityInfo.applicationInfo.isSystemApp();
12725            res.isInstantAppAvailable = userState.instantApp;
12726            return res;
12727        }
12728
12729        @Override
12730        protected void sortResults(List<ResolveInfo> results) {
12731            Collections.sort(results, mResolvePrioritySorter);
12732        }
12733
12734        @Override
12735        protected void dumpFilter(PrintWriter out, String prefix,
12736                PackageParser.ActivityIntentInfo filter) {
12737            out.print(prefix); out.print(
12738                    Integer.toHexString(System.identityHashCode(filter.activity)));
12739                    out.print(' ');
12740                    filter.activity.printComponentShortName(out);
12741                    out.print(" filter ");
12742                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12743        }
12744
12745        @Override
12746        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12747            return filter.activity;
12748        }
12749
12750        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12751            PackageParser.Activity activity = (PackageParser.Activity)label;
12752            out.print(prefix); out.print(
12753                    Integer.toHexString(System.identityHashCode(activity)));
12754                    out.print(' ');
12755                    activity.printComponentShortName(out);
12756            if (count > 1) {
12757                out.print(" ("); out.print(count); out.print(" filters)");
12758            }
12759            out.println();
12760        }
12761
12762        // Keys are String (activity class name), values are Activity.
12763        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12764                = new ArrayMap<ComponentName, PackageParser.Activity>();
12765        private int mFlags;
12766    }
12767
12768    private final class ServiceIntentResolver
12769            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12770        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12771                boolean defaultOnly, int userId) {
12772            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12773            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12774        }
12775
12776        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12777                int userId) {
12778            if (!sUserManager.exists(userId)) return null;
12779            mFlags = flags;
12780            return super.queryIntent(intent, resolvedType,
12781                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12782                    userId);
12783        }
12784
12785        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12786                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12787            if (!sUserManager.exists(userId)) return null;
12788            if (packageServices == null) {
12789                return null;
12790            }
12791            mFlags = flags;
12792            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12793            final int N = packageServices.size();
12794            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12795                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12796
12797            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12798            for (int i = 0; i < N; ++i) {
12799                intentFilters = packageServices.get(i).intents;
12800                if (intentFilters != null && intentFilters.size() > 0) {
12801                    PackageParser.ServiceIntentInfo[] array =
12802                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12803                    intentFilters.toArray(array);
12804                    listCut.add(array);
12805                }
12806            }
12807            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12808        }
12809
12810        public final void addService(PackageParser.Service s) {
12811            mServices.put(s.getComponentName(), s);
12812            if (DEBUG_SHOW_INFO) {
12813                Log.v(TAG, "  "
12814                        + (s.info.nonLocalizedLabel != null
12815                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12816                Log.v(TAG, "    Class=" + s.info.name);
12817            }
12818            final int NI = s.intents.size();
12819            int j;
12820            for (j=0; j<NI; j++) {
12821                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12822                if (DEBUG_SHOW_INFO) {
12823                    Log.v(TAG, "    IntentFilter:");
12824                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12825                }
12826                if (!intent.debugCheck()) {
12827                    Log.w(TAG, "==> For Service " + s.info.name);
12828                }
12829                addFilter(intent);
12830            }
12831        }
12832
12833        public final void removeService(PackageParser.Service s) {
12834            mServices.remove(s.getComponentName());
12835            if (DEBUG_SHOW_INFO) {
12836                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12837                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12838                Log.v(TAG, "    Class=" + s.info.name);
12839            }
12840            final int NI = s.intents.size();
12841            int j;
12842            for (j=0; j<NI; j++) {
12843                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12844                if (DEBUG_SHOW_INFO) {
12845                    Log.v(TAG, "    IntentFilter:");
12846                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12847                }
12848                removeFilter(intent);
12849            }
12850        }
12851
12852        @Override
12853        protected boolean allowFilterResult(
12854                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12855            ServiceInfo filterSi = filter.service.info;
12856            for (int i=dest.size()-1; i>=0; i--) {
12857                ServiceInfo destAi = dest.get(i).serviceInfo;
12858                if (destAi.name == filterSi.name
12859                        && destAi.packageName == filterSi.packageName) {
12860                    return false;
12861                }
12862            }
12863            return true;
12864        }
12865
12866        @Override
12867        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12868            return new PackageParser.ServiceIntentInfo[size];
12869        }
12870
12871        @Override
12872        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12873            if (!sUserManager.exists(userId)) return true;
12874            PackageParser.Package p = filter.service.owner;
12875            if (p != null) {
12876                PackageSetting ps = (PackageSetting)p.mExtras;
12877                if (ps != null) {
12878                    // System apps are never considered stopped for purposes of
12879                    // filtering, because there may be no way for the user to
12880                    // actually re-launch them.
12881                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12882                            && ps.getStopped(userId);
12883                }
12884            }
12885            return false;
12886        }
12887
12888        @Override
12889        protected boolean isPackageForFilter(String packageName,
12890                PackageParser.ServiceIntentInfo info) {
12891            return packageName.equals(info.service.owner.packageName);
12892        }
12893
12894        @Override
12895        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12896                int match, int userId) {
12897            if (!sUserManager.exists(userId)) return null;
12898            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12899            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12900                return null;
12901            }
12902            final PackageParser.Service service = info.service;
12903            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12904            if (ps == null) {
12905                return null;
12906            }
12907            final PackageUserState userState = ps.readUserState(userId);
12908            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12909                    userState, userId);
12910            if (si == null) {
12911                return null;
12912            }
12913            final boolean matchVisibleToInstantApp =
12914                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12915            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12916            // throw out filters that aren't visible to ephemeral apps
12917            if (matchVisibleToInstantApp
12918                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12919                return null;
12920            }
12921            // throw out ephemeral filters if we're not explicitly requesting them
12922            if (!isInstantApp && userState.instantApp) {
12923                return null;
12924            }
12925            // throw out instant app filters if updates are available; will trigger
12926            // instant app resolution
12927            if (userState.instantApp && ps.isUpdateAvailable()) {
12928                return null;
12929            }
12930            final ResolveInfo res = new ResolveInfo();
12931            res.serviceInfo = si;
12932            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12933                res.filter = filter;
12934            }
12935            res.priority = info.getPriority();
12936            res.preferredOrder = service.owner.mPreferredOrder;
12937            res.match = match;
12938            res.isDefault = info.hasDefault;
12939            res.labelRes = info.labelRes;
12940            res.nonLocalizedLabel = info.nonLocalizedLabel;
12941            res.icon = info.icon;
12942            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12943            return res;
12944        }
12945
12946        @Override
12947        protected void sortResults(List<ResolveInfo> results) {
12948            Collections.sort(results, mResolvePrioritySorter);
12949        }
12950
12951        @Override
12952        protected void dumpFilter(PrintWriter out, String prefix,
12953                PackageParser.ServiceIntentInfo filter) {
12954            out.print(prefix); out.print(
12955                    Integer.toHexString(System.identityHashCode(filter.service)));
12956                    out.print(' ');
12957                    filter.service.printComponentShortName(out);
12958                    out.print(" filter ");
12959                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12960                    if (filter.service.info.permission != null) {
12961                        out.print(" permission "); out.println(filter.service.info.permission);
12962                    } else {
12963                        out.println();
12964                    }
12965        }
12966
12967        @Override
12968        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12969            return filter.service;
12970        }
12971
12972        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12973            PackageParser.Service service = (PackageParser.Service)label;
12974            out.print(prefix); out.print(
12975                    Integer.toHexString(System.identityHashCode(service)));
12976                    out.print(' ');
12977                    service.printComponentShortName(out);
12978            if (count > 1) {
12979                out.print(" ("); out.print(count); out.print(" filters)");
12980            }
12981            out.println();
12982        }
12983
12984//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12985//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12986//            final List<ResolveInfo> retList = Lists.newArrayList();
12987//            while (i.hasNext()) {
12988//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12989//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12990//                    retList.add(resolveInfo);
12991//                }
12992//            }
12993//            return retList;
12994//        }
12995
12996        // Keys are String (activity class name), values are Activity.
12997        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12998                = new ArrayMap<ComponentName, PackageParser.Service>();
12999        private int mFlags;
13000    }
13001
13002    private final class ProviderIntentResolver
13003            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13004        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13005                boolean defaultOnly, int userId) {
13006            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13007            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13008        }
13009
13010        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13011                int userId) {
13012            if (!sUserManager.exists(userId))
13013                return null;
13014            mFlags = flags;
13015            return super.queryIntent(intent, resolvedType,
13016                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13017                    userId);
13018        }
13019
13020        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13021                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13022            if (!sUserManager.exists(userId))
13023                return null;
13024            if (packageProviders == null) {
13025                return null;
13026            }
13027            mFlags = flags;
13028            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13029            final int N = packageProviders.size();
13030            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13031                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13032
13033            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13034            for (int i = 0; i < N; ++i) {
13035                intentFilters = packageProviders.get(i).intents;
13036                if (intentFilters != null && intentFilters.size() > 0) {
13037                    PackageParser.ProviderIntentInfo[] array =
13038                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13039                    intentFilters.toArray(array);
13040                    listCut.add(array);
13041                }
13042            }
13043            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13044        }
13045
13046        public final void addProvider(PackageParser.Provider p) {
13047            if (mProviders.containsKey(p.getComponentName())) {
13048                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13049                return;
13050            }
13051
13052            mProviders.put(p.getComponentName(), p);
13053            if (DEBUG_SHOW_INFO) {
13054                Log.v(TAG, "  "
13055                        + (p.info.nonLocalizedLabel != null
13056                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13057                Log.v(TAG, "    Class=" + p.info.name);
13058            }
13059            final int NI = p.intents.size();
13060            int j;
13061            for (j = 0; j < NI; j++) {
13062                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13063                if (DEBUG_SHOW_INFO) {
13064                    Log.v(TAG, "    IntentFilter:");
13065                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13066                }
13067                if (!intent.debugCheck()) {
13068                    Log.w(TAG, "==> For Provider " + p.info.name);
13069                }
13070                addFilter(intent);
13071            }
13072        }
13073
13074        public final void removeProvider(PackageParser.Provider p) {
13075            mProviders.remove(p.getComponentName());
13076            if (DEBUG_SHOW_INFO) {
13077                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13078                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13079                Log.v(TAG, "    Class=" + p.info.name);
13080            }
13081            final int NI = p.intents.size();
13082            int j;
13083            for (j = 0; j < NI; j++) {
13084                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13085                if (DEBUG_SHOW_INFO) {
13086                    Log.v(TAG, "    IntentFilter:");
13087                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13088                }
13089                removeFilter(intent);
13090            }
13091        }
13092
13093        @Override
13094        protected boolean allowFilterResult(
13095                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13096            ProviderInfo filterPi = filter.provider.info;
13097            for (int i = dest.size() - 1; i >= 0; i--) {
13098                ProviderInfo destPi = dest.get(i).providerInfo;
13099                if (destPi.name == filterPi.name
13100                        && destPi.packageName == filterPi.packageName) {
13101                    return false;
13102                }
13103            }
13104            return true;
13105        }
13106
13107        @Override
13108        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13109            return new PackageParser.ProviderIntentInfo[size];
13110        }
13111
13112        @Override
13113        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13114            if (!sUserManager.exists(userId))
13115                return true;
13116            PackageParser.Package p = filter.provider.owner;
13117            if (p != null) {
13118                PackageSetting ps = (PackageSetting) p.mExtras;
13119                if (ps != null) {
13120                    // System apps are never considered stopped for purposes of
13121                    // filtering, because there may be no way for the user to
13122                    // actually re-launch them.
13123                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13124                            && ps.getStopped(userId);
13125                }
13126            }
13127            return false;
13128        }
13129
13130        @Override
13131        protected boolean isPackageForFilter(String packageName,
13132                PackageParser.ProviderIntentInfo info) {
13133            return packageName.equals(info.provider.owner.packageName);
13134        }
13135
13136        @Override
13137        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13138                int match, int userId) {
13139            if (!sUserManager.exists(userId))
13140                return null;
13141            final PackageParser.ProviderIntentInfo info = filter;
13142            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13143                return null;
13144            }
13145            final PackageParser.Provider provider = info.provider;
13146            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13147            if (ps == null) {
13148                return null;
13149            }
13150            final PackageUserState userState = ps.readUserState(userId);
13151            final boolean matchVisibleToInstantApp =
13152                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13153            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13154            // throw out filters that aren't visible to instant applications
13155            if (matchVisibleToInstantApp
13156                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13157                return null;
13158            }
13159            // throw out instant application filters if we're not explicitly requesting them
13160            if (!isInstantApp && userState.instantApp) {
13161                return null;
13162            }
13163            // throw out instant application filters if updates are available; will trigger
13164            // instant application resolution
13165            if (userState.instantApp && ps.isUpdateAvailable()) {
13166                return null;
13167            }
13168            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13169                    userState, userId);
13170            if (pi == null) {
13171                return null;
13172            }
13173            final ResolveInfo res = new ResolveInfo();
13174            res.providerInfo = pi;
13175            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13176                res.filter = filter;
13177            }
13178            res.priority = info.getPriority();
13179            res.preferredOrder = provider.owner.mPreferredOrder;
13180            res.match = match;
13181            res.isDefault = info.hasDefault;
13182            res.labelRes = info.labelRes;
13183            res.nonLocalizedLabel = info.nonLocalizedLabel;
13184            res.icon = info.icon;
13185            res.system = res.providerInfo.applicationInfo.isSystemApp();
13186            return res;
13187        }
13188
13189        @Override
13190        protected void sortResults(List<ResolveInfo> results) {
13191            Collections.sort(results, mResolvePrioritySorter);
13192        }
13193
13194        @Override
13195        protected void dumpFilter(PrintWriter out, String prefix,
13196                PackageParser.ProviderIntentInfo filter) {
13197            out.print(prefix);
13198            out.print(
13199                    Integer.toHexString(System.identityHashCode(filter.provider)));
13200            out.print(' ');
13201            filter.provider.printComponentShortName(out);
13202            out.print(" filter ");
13203            out.println(Integer.toHexString(System.identityHashCode(filter)));
13204        }
13205
13206        @Override
13207        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13208            return filter.provider;
13209        }
13210
13211        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13212            PackageParser.Provider provider = (PackageParser.Provider)label;
13213            out.print(prefix); out.print(
13214                    Integer.toHexString(System.identityHashCode(provider)));
13215                    out.print(' ');
13216                    provider.printComponentShortName(out);
13217            if (count > 1) {
13218                out.print(" ("); out.print(count); out.print(" filters)");
13219            }
13220            out.println();
13221        }
13222
13223        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13224                = new ArrayMap<ComponentName, PackageParser.Provider>();
13225        private int mFlags;
13226    }
13227
13228    static final class InstantAppIntentResolver
13229            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13230            AuxiliaryResolveInfo.AuxiliaryFilter> {
13231        /**
13232         * The result that has the highest defined order. Ordering applies on a
13233         * per-package basis. Mapping is from package name to Pair of order and
13234         * EphemeralResolveInfo.
13235         * <p>
13236         * NOTE: This is implemented as a field variable for convenience and efficiency.
13237         * By having a field variable, we're able to track filter ordering as soon as
13238         * a non-zero order is defined. Otherwise, multiple loops across the result set
13239         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13240         * this needs to be contained entirely within {@link #filterResults}.
13241         */
13242        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13243
13244        @Override
13245        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13246            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13247        }
13248
13249        @Override
13250        protected boolean isPackageForFilter(String packageName,
13251                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13252            return true;
13253        }
13254
13255        @Override
13256        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13257                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13258            if (!sUserManager.exists(userId)) {
13259                return null;
13260            }
13261            final String packageName = responseObj.resolveInfo.getPackageName();
13262            final Integer order = responseObj.getOrder();
13263            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13264                    mOrderResult.get(packageName);
13265            // ordering is enabled and this item's order isn't high enough
13266            if (lastOrderResult != null && lastOrderResult.first >= order) {
13267                return null;
13268            }
13269            final InstantAppResolveInfo res = responseObj.resolveInfo;
13270            if (order > 0) {
13271                // non-zero order, enable ordering
13272                mOrderResult.put(packageName, new Pair<>(order, res));
13273            }
13274            return responseObj;
13275        }
13276
13277        @Override
13278        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13279            // only do work if ordering is enabled [most of the time it won't be]
13280            if (mOrderResult.size() == 0) {
13281                return;
13282            }
13283            int resultSize = results.size();
13284            for (int i = 0; i < resultSize; i++) {
13285                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13286                final String packageName = info.getPackageName();
13287                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13288                if (savedInfo == null) {
13289                    // package doesn't having ordering
13290                    continue;
13291                }
13292                if (savedInfo.second == info) {
13293                    // circled back to the highest ordered item; remove from order list
13294                    mOrderResult.remove(packageName);
13295                    if (mOrderResult.size() == 0) {
13296                        // no more ordered items
13297                        break;
13298                    }
13299                    continue;
13300                }
13301                // item has a worse order, remove it from the result list
13302                results.remove(i);
13303                resultSize--;
13304                i--;
13305            }
13306        }
13307    }
13308
13309    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13310            new Comparator<ResolveInfo>() {
13311        public int compare(ResolveInfo r1, ResolveInfo r2) {
13312            int v1 = r1.priority;
13313            int v2 = r2.priority;
13314            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13315            if (v1 != v2) {
13316                return (v1 > v2) ? -1 : 1;
13317            }
13318            v1 = r1.preferredOrder;
13319            v2 = r2.preferredOrder;
13320            if (v1 != v2) {
13321                return (v1 > v2) ? -1 : 1;
13322            }
13323            if (r1.isDefault != r2.isDefault) {
13324                return r1.isDefault ? -1 : 1;
13325            }
13326            v1 = r1.match;
13327            v2 = r2.match;
13328            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13329            if (v1 != v2) {
13330                return (v1 > v2) ? -1 : 1;
13331            }
13332            if (r1.system != r2.system) {
13333                return r1.system ? -1 : 1;
13334            }
13335            if (r1.activityInfo != null) {
13336                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13337            }
13338            if (r1.serviceInfo != null) {
13339                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13340            }
13341            if (r1.providerInfo != null) {
13342                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13343            }
13344            return 0;
13345        }
13346    };
13347
13348    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13349            new Comparator<ProviderInfo>() {
13350        public int compare(ProviderInfo p1, ProviderInfo p2) {
13351            final int v1 = p1.initOrder;
13352            final int v2 = p2.initOrder;
13353            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13354        }
13355    };
13356
13357    @Override
13358    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13359            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13360            final int[] userIds, int[] instantUserIds) {
13361        mHandler.post(new Runnable() {
13362            @Override
13363            public void run() {
13364                try {
13365                    final IActivityManager am = ActivityManager.getService();
13366                    if (am == null) return;
13367                    final int[] resolvedUserIds;
13368                    if (userIds == null) {
13369                        resolvedUserIds = am.getRunningUserIds();
13370                    } else {
13371                        resolvedUserIds = userIds;
13372                    }
13373                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13374                            resolvedUserIds, false);
13375                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13376                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13377                                instantUserIds, true);
13378                    }
13379                } catch (RemoteException ex) {
13380                }
13381            }
13382        });
13383    }
13384
13385    @Override
13386    public void notifyPackageAdded(String packageName) {
13387        final PackageListObserver[] observers;
13388        synchronized (mPackages) {
13389            if (mPackageListObservers.size() == 0) {
13390                return;
13391            }
13392            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13393        }
13394        for (int i = observers.length - 1; i >= 0; --i) {
13395            observers[i].onPackageAdded(packageName);
13396        }
13397    }
13398
13399    @Override
13400    public void notifyPackageRemoved(String packageName) {
13401        final PackageListObserver[] observers;
13402        synchronized (mPackages) {
13403            if (mPackageListObservers.size() == 0) {
13404                return;
13405            }
13406            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13407        }
13408        for (int i = observers.length - 1; i >= 0; --i) {
13409            observers[i].onPackageRemoved(packageName);
13410        }
13411    }
13412
13413    /**
13414     * Sends a broadcast for the given action.
13415     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13416     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13417     * the system and applications allowed to see instant applications to receive package
13418     * lifecycle events for instant applications.
13419     */
13420    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13421            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13422            int[] userIds, boolean isInstantApp)
13423                    throws RemoteException {
13424        for (int id : userIds) {
13425            final Intent intent = new Intent(action,
13426                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13427            final String[] requiredPermissions =
13428                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13429            if (extras != null) {
13430                intent.putExtras(extras);
13431            }
13432            if (targetPkg != null) {
13433                intent.setPackage(targetPkg);
13434            }
13435            // Modify the UID when posting to other users
13436            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13437            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13438                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13439                intent.putExtra(Intent.EXTRA_UID, uid);
13440            }
13441            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13442            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13443            if (DEBUG_BROADCASTS) {
13444                RuntimeException here = new RuntimeException("here");
13445                here.fillInStackTrace();
13446                Slog.d(TAG, "Sending to user " + id + ": "
13447                        + intent.toShortString(false, true, false, false)
13448                        + " " + intent.getExtras(), here);
13449            }
13450            am.broadcastIntent(null, intent, null, finishedReceiver,
13451                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13452                    null, finishedReceiver != null, false, id);
13453        }
13454    }
13455
13456    /**
13457     * Check if the external storage media is available. This is true if there
13458     * is a mounted external storage medium or if the external storage is
13459     * emulated.
13460     */
13461    private boolean isExternalMediaAvailable() {
13462        return mMediaMounted || Environment.isExternalStorageEmulated();
13463    }
13464
13465    @Override
13466    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13467        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13468            return null;
13469        }
13470        if (!isExternalMediaAvailable()) {
13471                // If the external storage is no longer mounted at this point,
13472                // the caller may not have been able to delete all of this
13473                // packages files and can not delete any more.  Bail.
13474            return null;
13475        }
13476        synchronized (mPackages) {
13477            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13478            if (lastPackage != null) {
13479                pkgs.remove(lastPackage);
13480            }
13481            if (pkgs.size() > 0) {
13482                return pkgs.get(0);
13483            }
13484        }
13485        return null;
13486    }
13487
13488    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13489        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13490                userId, andCode ? 1 : 0, packageName);
13491        if (mSystemReady) {
13492            msg.sendToTarget();
13493        } else {
13494            if (mPostSystemReadyMessages == null) {
13495                mPostSystemReadyMessages = new ArrayList<>();
13496            }
13497            mPostSystemReadyMessages.add(msg);
13498        }
13499    }
13500
13501    void startCleaningPackages() {
13502        // reader
13503        if (!isExternalMediaAvailable()) {
13504            return;
13505        }
13506        synchronized (mPackages) {
13507            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13508                return;
13509            }
13510        }
13511        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13512        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13513        IActivityManager am = ActivityManager.getService();
13514        if (am != null) {
13515            int dcsUid = -1;
13516            synchronized (mPackages) {
13517                if (!mDefaultContainerWhitelisted) {
13518                    mDefaultContainerWhitelisted = true;
13519                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13520                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13521                }
13522            }
13523            try {
13524                if (dcsUid > 0) {
13525                    am.backgroundWhitelistUid(dcsUid);
13526                }
13527                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13528                        UserHandle.USER_SYSTEM);
13529            } catch (RemoteException e) {
13530            }
13531        }
13532    }
13533
13534    /**
13535     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13536     * it is acting on behalf on an enterprise or the user).
13537     *
13538     * Note that the ordering of the conditionals in this method is important. The checks we perform
13539     * are as follows, in this order:
13540     *
13541     * 1) If the install is being performed by a system app, we can trust the app to have set the
13542     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13543     *    what it is.
13544     * 2) If the install is being performed by a device or profile owner app, the install reason
13545     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13546     *    set the install reason correctly. If the app targets an older SDK version where install
13547     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13548     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13549     * 3) In all other cases, the install is being performed by a regular app that is neither part
13550     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13551     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13552     *    set to enterprise policy and if so, change it to unknown instead.
13553     */
13554    private int fixUpInstallReason(String installerPackageName, int installerUid,
13555            int installReason) {
13556        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13557                == PERMISSION_GRANTED) {
13558            // If the install is being performed by a system app, we trust that app to have set the
13559            // install reason correctly.
13560            return installReason;
13561        }
13562
13563        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13564            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13565        if (dpm != null) {
13566            ComponentName owner = null;
13567            try {
13568                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13569                if (owner == null) {
13570                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13571                }
13572            } catch (RemoteException e) {
13573            }
13574            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13575                // If the install is being performed by a device or profile owner, the install
13576                // reason should be enterprise policy.
13577                return PackageManager.INSTALL_REASON_POLICY;
13578            }
13579        }
13580
13581        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13582            // If the install is being performed by a regular app (i.e. neither system app nor
13583            // device or profile owner), we have no reason to believe that the app is acting on
13584            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13585            // change it to unknown instead.
13586            return PackageManager.INSTALL_REASON_UNKNOWN;
13587        }
13588
13589        // If the install is being performed by a regular app and the install reason was set to any
13590        // value but enterprise policy, leave the install reason unchanged.
13591        return installReason;
13592    }
13593
13594    void installStage(String packageName, File stagedDir,
13595            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13596            String installerPackageName, int installerUid, UserHandle user,
13597            PackageParser.SigningDetails signingDetails) {
13598        if (DEBUG_INSTANT) {
13599            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13600                Slog.d(TAG, "Ephemeral install of " + packageName);
13601            }
13602        }
13603        final VerificationInfo verificationInfo = new VerificationInfo(
13604                sessionParams.originatingUri, sessionParams.referrerUri,
13605                sessionParams.originatingUid, installerUid);
13606
13607        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13608
13609        final Message msg = mHandler.obtainMessage(INIT_COPY);
13610        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13611                sessionParams.installReason);
13612        final InstallParams params = new InstallParams(origin, null, observer,
13613                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13614                verificationInfo, user, sessionParams.abiOverride,
13615                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13616        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13617        msg.obj = params;
13618
13619        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13620                System.identityHashCode(msg.obj));
13621        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13622                System.identityHashCode(msg.obj));
13623
13624        mHandler.sendMessage(msg);
13625    }
13626
13627    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13628            int userId) {
13629        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13630        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13631        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13632        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13633        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13634                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13635
13636        // Send a session commit broadcast
13637        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13638        info.installReason = pkgSetting.getInstallReason(userId);
13639        info.appPackageName = packageName;
13640        sendSessionCommitBroadcast(info, userId);
13641    }
13642
13643    @Override
13644    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13645            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13646        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13647            return;
13648        }
13649        Bundle extras = new Bundle(1);
13650        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13651        final int uid = UserHandle.getUid(
13652                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13653        extras.putInt(Intent.EXTRA_UID, uid);
13654
13655        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13656                packageName, extras, 0, null, null, userIds, instantUserIds);
13657        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13658            mHandler.post(() -> {
13659                        for (int userId : userIds) {
13660                            sendBootCompletedBroadcastToSystemApp(
13661                                    packageName, includeStopped, userId);
13662                        }
13663                    }
13664            );
13665        }
13666    }
13667
13668    /**
13669     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13670     * automatically without needing an explicit launch.
13671     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13672     */
13673    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13674            int userId) {
13675        // If user is not running, the app didn't miss any broadcast
13676        if (!mUserManagerInternal.isUserRunning(userId)) {
13677            return;
13678        }
13679        final IActivityManager am = ActivityManager.getService();
13680        try {
13681            // Deliver LOCKED_BOOT_COMPLETED first
13682            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13683                    .setPackage(packageName);
13684            if (includeStopped) {
13685                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13686            }
13687            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13688            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13689                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13690
13691            // Deliver BOOT_COMPLETED only if user is unlocked
13692            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13693                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13694                if (includeStopped) {
13695                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13696                }
13697                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13698                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13699            }
13700        } catch (RemoteException e) {
13701            throw e.rethrowFromSystemServer();
13702        }
13703    }
13704
13705    @Override
13706    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13707            int userId) {
13708        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13709        PackageSetting pkgSetting;
13710        final int callingUid = Binder.getCallingUid();
13711        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13712                true /* requireFullPermission */, true /* checkShell */,
13713                "setApplicationHiddenSetting for user " + userId);
13714
13715        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13716            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13717            return false;
13718        }
13719
13720        long callingId = Binder.clearCallingIdentity();
13721        try {
13722            boolean sendAdded = false;
13723            boolean sendRemoved = false;
13724            // writer
13725            synchronized (mPackages) {
13726                pkgSetting = mSettings.mPackages.get(packageName);
13727                if (pkgSetting == null) {
13728                    return false;
13729                }
13730                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13731                    return false;
13732                }
13733                // Do not allow "android" is being disabled
13734                if ("android".equals(packageName)) {
13735                    Slog.w(TAG, "Cannot hide package: android");
13736                    return false;
13737                }
13738                // Cannot hide static shared libs as they are considered
13739                // a part of the using app (emulating static linking). Also
13740                // static libs are installed always on internal storage.
13741                PackageParser.Package pkg = mPackages.get(packageName);
13742                if (pkg != null && pkg.staticSharedLibName != null) {
13743                    Slog.w(TAG, "Cannot hide package: " + packageName
13744                            + " providing static shared library: "
13745                            + pkg.staticSharedLibName);
13746                    return false;
13747                }
13748                // Only allow protected packages to hide themselves.
13749                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13750                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13751                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13752                    return false;
13753                }
13754
13755                if (pkgSetting.getHidden(userId) != hidden) {
13756                    pkgSetting.setHidden(hidden, userId);
13757                    mSettings.writePackageRestrictionsLPr(userId);
13758                    if (hidden) {
13759                        sendRemoved = true;
13760                    } else {
13761                        sendAdded = true;
13762                    }
13763                }
13764            }
13765            if (sendAdded) {
13766                sendPackageAddedForUser(packageName, pkgSetting, userId);
13767                return true;
13768            }
13769            if (sendRemoved) {
13770                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13771                        "hiding pkg");
13772                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13773                return true;
13774            }
13775        } finally {
13776            Binder.restoreCallingIdentity(callingId);
13777        }
13778        return false;
13779    }
13780
13781    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13782            int userId) {
13783        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13784        info.removedPackage = packageName;
13785        info.installerPackageName = pkgSetting.installerPackageName;
13786        info.removedUsers = new int[] {userId};
13787        info.broadcastUsers = new int[] {userId};
13788        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13789        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13790    }
13791
13792    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13793        if (pkgList.length > 0) {
13794            Bundle extras = new Bundle(1);
13795            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13796
13797            sendPackageBroadcast(
13798                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13799                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13800                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13801                    new int[] {userId}, null);
13802        }
13803    }
13804
13805    /**
13806     * Returns true if application is not found or there was an error. Otherwise it returns
13807     * the hidden state of the package for the given user.
13808     */
13809    @Override
13810    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13811        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13812        final int callingUid = Binder.getCallingUid();
13813        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13814                true /* requireFullPermission */, false /* checkShell */,
13815                "getApplicationHidden for user " + userId);
13816        PackageSetting ps;
13817        long callingId = Binder.clearCallingIdentity();
13818        try {
13819            // writer
13820            synchronized (mPackages) {
13821                ps = mSettings.mPackages.get(packageName);
13822                if (ps == null) {
13823                    return true;
13824                }
13825                if (filterAppAccessLPr(ps, callingUid, userId)) {
13826                    return true;
13827                }
13828                return ps.getHidden(userId);
13829            }
13830        } finally {
13831            Binder.restoreCallingIdentity(callingId);
13832        }
13833    }
13834
13835    /**
13836     * @hide
13837     */
13838    @Override
13839    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13840            int installReason) {
13841        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13842                null);
13843        PackageSetting pkgSetting;
13844        final int callingUid = Binder.getCallingUid();
13845        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13846                true /* requireFullPermission */, true /* checkShell */,
13847                "installExistingPackage for user " + userId);
13848        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13849            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13850        }
13851
13852        long callingId = Binder.clearCallingIdentity();
13853        try {
13854            boolean installed = false;
13855            final boolean instantApp =
13856                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13857            final boolean fullApp =
13858                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13859
13860            // writer
13861            synchronized (mPackages) {
13862                pkgSetting = mSettings.mPackages.get(packageName);
13863                if (pkgSetting == null) {
13864                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13865                }
13866                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13867                    // only allow the existing package to be used if it's installed as a full
13868                    // application for at least one user
13869                    boolean installAllowed = false;
13870                    for (int checkUserId : sUserManager.getUserIds()) {
13871                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13872                        if (installAllowed) {
13873                            break;
13874                        }
13875                    }
13876                    if (!installAllowed) {
13877                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13878                    }
13879                }
13880                if (!pkgSetting.getInstalled(userId)) {
13881                    pkgSetting.setInstalled(true, userId);
13882                    pkgSetting.setHidden(false, userId);
13883                    pkgSetting.setInstallReason(installReason, userId);
13884                    mSettings.writePackageRestrictionsLPr(userId);
13885                    mSettings.writeKernelMappingLPr(pkgSetting);
13886                    installed = true;
13887                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13888                    // upgrade app from instant to full; we don't allow app downgrade
13889                    installed = true;
13890                }
13891                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13892            }
13893
13894            if (installed) {
13895                if (pkgSetting.pkg != null) {
13896                    synchronized (mInstallLock) {
13897                        // We don't need to freeze for a brand new install
13898                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13899                    }
13900                }
13901                sendPackageAddedForUser(packageName, pkgSetting, userId);
13902                synchronized (mPackages) {
13903                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13904                }
13905            }
13906        } finally {
13907            Binder.restoreCallingIdentity(callingId);
13908        }
13909
13910        return PackageManager.INSTALL_SUCCEEDED;
13911    }
13912
13913    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13914            boolean instantApp, boolean fullApp) {
13915        // no state specified; do nothing
13916        if (!instantApp && !fullApp) {
13917            return;
13918        }
13919        if (userId != UserHandle.USER_ALL) {
13920            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13921                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13922            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13923                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13924            }
13925        } else {
13926            for (int currentUserId : sUserManager.getUserIds()) {
13927                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13928                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13929                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13930                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13931                }
13932            }
13933        }
13934    }
13935
13936    boolean isUserRestricted(int userId, String restrictionKey) {
13937        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13938        if (restrictions.getBoolean(restrictionKey, false)) {
13939            Log.w(TAG, "User is restricted: " + restrictionKey);
13940            return true;
13941        }
13942        return false;
13943    }
13944
13945    @Override
13946    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13947            int userId) {
13948        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13949        final int callingUid = Binder.getCallingUid();
13950        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13951                true /* requireFullPermission */, true /* checkShell */,
13952                "setPackagesSuspended for user " + userId);
13953
13954        if (ArrayUtils.isEmpty(packageNames)) {
13955            return packageNames;
13956        }
13957
13958        // List of package names for whom the suspended state has changed.
13959        List<String> changedPackages = new ArrayList<>(packageNames.length);
13960        // List of package names for whom the suspended state is not set as requested in this
13961        // method.
13962        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13963        long callingId = Binder.clearCallingIdentity();
13964        try {
13965            for (int i = 0; i < packageNames.length; i++) {
13966                String packageName = packageNames[i];
13967                boolean changed = false;
13968                final int appId;
13969                synchronized (mPackages) {
13970                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13971                    if (pkgSetting == null
13972                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13973                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13974                                + "\". Skipping suspending/un-suspending.");
13975                        unactionedPackages.add(packageName);
13976                        continue;
13977                    }
13978                    appId = pkgSetting.appId;
13979                    if (pkgSetting.getSuspended(userId) != suspended) {
13980                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13981                            unactionedPackages.add(packageName);
13982                            continue;
13983                        }
13984                        pkgSetting.setSuspended(suspended, userId);
13985                        mSettings.writePackageRestrictionsLPr(userId);
13986                        changed = true;
13987                        changedPackages.add(packageName);
13988                    }
13989                }
13990
13991                if (changed && suspended) {
13992                    killApplication(packageName, UserHandle.getUid(userId, appId),
13993                            "suspending package");
13994                }
13995            }
13996        } finally {
13997            Binder.restoreCallingIdentity(callingId);
13998        }
13999
14000        if (!changedPackages.isEmpty()) {
14001            sendPackagesSuspendedForUser(changedPackages.toArray(
14002                    new String[changedPackages.size()]), userId, suspended);
14003        }
14004
14005        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14006    }
14007
14008    @Override
14009    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14010        final int callingUid = Binder.getCallingUid();
14011        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14012                true /* requireFullPermission */, false /* checkShell */,
14013                "isPackageSuspendedForUser for user " + userId);
14014        synchronized (mPackages) {
14015            final PackageSetting ps = mSettings.mPackages.get(packageName);
14016            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14017                throw new IllegalArgumentException("Unknown target package: " + packageName);
14018            }
14019            return ps.getSuspended(userId);
14020        }
14021    }
14022
14023    @GuardedBy("mPackages")
14024    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14025        if (isPackageDeviceAdmin(packageName, userId)) {
14026            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14027                    + "\": has an active device admin");
14028            return false;
14029        }
14030
14031        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14032        if (packageName.equals(activeLauncherPackageName)) {
14033            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14034                    + "\": contains the active launcher");
14035            return false;
14036        }
14037
14038        if (packageName.equals(mRequiredInstallerPackage)) {
14039            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14040                    + "\": required for package installation");
14041            return false;
14042        }
14043
14044        if (packageName.equals(mRequiredUninstallerPackage)) {
14045            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14046                    + "\": required for package uninstallation");
14047            return false;
14048        }
14049
14050        if (packageName.equals(mRequiredVerifierPackage)) {
14051            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14052                    + "\": required for package verification");
14053            return false;
14054        }
14055
14056        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14057            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14058                    + "\": is the default dialer");
14059            return false;
14060        }
14061
14062        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14063            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14064                    + "\": protected package");
14065            return false;
14066        }
14067
14068        // Cannot suspend static shared libs as they are considered
14069        // a part of the using app (emulating static linking). Also
14070        // static libs are installed always on internal storage.
14071        PackageParser.Package pkg = mPackages.get(packageName);
14072        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14073            Slog.w(TAG, "Cannot suspend package: " + packageName
14074                    + " providing static shared library: "
14075                    + pkg.staticSharedLibName);
14076            return false;
14077        }
14078
14079        return true;
14080    }
14081
14082    private String getActiveLauncherPackageName(int userId) {
14083        Intent intent = new Intent(Intent.ACTION_MAIN);
14084        intent.addCategory(Intent.CATEGORY_HOME);
14085        ResolveInfo resolveInfo = resolveIntent(
14086                intent,
14087                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14088                PackageManager.MATCH_DEFAULT_ONLY,
14089                userId);
14090
14091        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14092    }
14093
14094    private String getDefaultDialerPackageName(int userId) {
14095        synchronized (mPackages) {
14096            return mSettings.getDefaultDialerPackageNameLPw(userId);
14097        }
14098    }
14099
14100    @Override
14101    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14102        mContext.enforceCallingOrSelfPermission(
14103                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14104                "Only package verification agents can verify applications");
14105
14106        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14107        final PackageVerificationResponse response = new PackageVerificationResponse(
14108                verificationCode, Binder.getCallingUid());
14109        msg.arg1 = id;
14110        msg.obj = response;
14111        mHandler.sendMessage(msg);
14112    }
14113
14114    @Override
14115    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14116            long millisecondsToDelay) {
14117        mContext.enforceCallingOrSelfPermission(
14118                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14119                "Only package verification agents can extend verification timeouts");
14120
14121        final PackageVerificationState state = mPendingVerification.get(id);
14122        final PackageVerificationResponse response = new PackageVerificationResponse(
14123                verificationCodeAtTimeout, Binder.getCallingUid());
14124
14125        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14126            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14127        }
14128        if (millisecondsToDelay < 0) {
14129            millisecondsToDelay = 0;
14130        }
14131        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14132                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14133            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14134        }
14135
14136        if ((state != null) && !state.timeoutExtended()) {
14137            state.extendTimeout();
14138
14139            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14140            msg.arg1 = id;
14141            msg.obj = response;
14142            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14143        }
14144    }
14145
14146    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14147            int verificationCode, UserHandle user) {
14148        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14149        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14150        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14151        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14152        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14153
14154        mContext.sendBroadcastAsUser(intent, user,
14155                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14156    }
14157
14158    private ComponentName matchComponentForVerifier(String packageName,
14159            List<ResolveInfo> receivers) {
14160        ActivityInfo targetReceiver = null;
14161
14162        final int NR = receivers.size();
14163        for (int i = 0; i < NR; i++) {
14164            final ResolveInfo info = receivers.get(i);
14165            if (info.activityInfo == null) {
14166                continue;
14167            }
14168
14169            if (packageName.equals(info.activityInfo.packageName)) {
14170                targetReceiver = info.activityInfo;
14171                break;
14172            }
14173        }
14174
14175        if (targetReceiver == null) {
14176            return null;
14177        }
14178
14179        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14180    }
14181
14182    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14183            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14184        if (pkgInfo.verifiers.length == 0) {
14185            return null;
14186        }
14187
14188        final int N = pkgInfo.verifiers.length;
14189        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14190        for (int i = 0; i < N; i++) {
14191            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14192
14193            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14194                    receivers);
14195            if (comp == null) {
14196                continue;
14197            }
14198
14199            final int verifierUid = getUidForVerifier(verifierInfo);
14200            if (verifierUid == -1) {
14201                continue;
14202            }
14203
14204            if (DEBUG_VERIFY) {
14205                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14206                        + " with the correct signature");
14207            }
14208            sufficientVerifiers.add(comp);
14209            verificationState.addSufficientVerifier(verifierUid);
14210        }
14211
14212        return sufficientVerifiers;
14213    }
14214
14215    private int getUidForVerifier(VerifierInfo verifierInfo) {
14216        synchronized (mPackages) {
14217            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14218            if (pkg == null) {
14219                return -1;
14220            } else if (pkg.mSigningDetails.signatures.length != 1) {
14221                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14222                        + " has more than one signature; ignoring");
14223                return -1;
14224            }
14225
14226            /*
14227             * If the public key of the package's signature does not match
14228             * our expected public key, then this is a different package and
14229             * we should skip.
14230             */
14231
14232            final byte[] expectedPublicKey;
14233            try {
14234                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14235                final PublicKey publicKey = verifierSig.getPublicKey();
14236                expectedPublicKey = publicKey.getEncoded();
14237            } catch (CertificateException e) {
14238                return -1;
14239            }
14240
14241            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14242
14243            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14244                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14245                        + " does not have the expected public key; ignoring");
14246                return -1;
14247            }
14248
14249            return pkg.applicationInfo.uid;
14250        }
14251    }
14252
14253    @Override
14254    public void finishPackageInstall(int token, boolean didLaunch) {
14255        enforceSystemOrRoot("Only the system is allowed to finish installs");
14256
14257        if (DEBUG_INSTALL) {
14258            Slog.v(TAG, "BM finishing package install for " + token);
14259        }
14260        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14261
14262        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14263        mHandler.sendMessage(msg);
14264    }
14265
14266    /**
14267     * Get the verification agent timeout.  Used for both the APK verifier and the
14268     * intent filter verifier.
14269     *
14270     * @return verification timeout in milliseconds
14271     */
14272    private long getVerificationTimeout() {
14273        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14274                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14275                DEFAULT_VERIFICATION_TIMEOUT);
14276    }
14277
14278    /**
14279     * Get the default verification agent response code.
14280     *
14281     * @return default verification response code
14282     */
14283    private int getDefaultVerificationResponse(UserHandle user) {
14284        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14285            return PackageManager.VERIFICATION_REJECT;
14286        }
14287        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14288                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14289                DEFAULT_VERIFICATION_RESPONSE);
14290    }
14291
14292    /**
14293     * Check whether or not package verification has been enabled.
14294     *
14295     * @return true if verification should be performed
14296     */
14297    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14298        if (!DEFAULT_VERIFY_ENABLE) {
14299            return false;
14300        }
14301
14302        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14303
14304        // Check if installing from ADB
14305        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14306            // Do not run verification in a test harness environment
14307            if (ActivityManager.isRunningInTestHarness()) {
14308                return false;
14309            }
14310            if (ensureVerifyAppsEnabled) {
14311                return true;
14312            }
14313            // Check if the developer does not want package verification for ADB installs
14314            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14315                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14316                return false;
14317            }
14318        } else {
14319            // only when not installed from ADB, skip verification for instant apps when
14320            // the installer and verifier are the same.
14321            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14322                if (mInstantAppInstallerActivity != null
14323                        && mInstantAppInstallerActivity.packageName.equals(
14324                                mRequiredVerifierPackage)) {
14325                    try {
14326                        mContext.getSystemService(AppOpsManager.class)
14327                                .checkPackage(installerUid, mRequiredVerifierPackage);
14328                        if (DEBUG_VERIFY) {
14329                            Slog.i(TAG, "disable verification for instant app");
14330                        }
14331                        return false;
14332                    } catch (SecurityException ignore) { }
14333                }
14334            }
14335        }
14336
14337        if (ensureVerifyAppsEnabled) {
14338            return true;
14339        }
14340
14341        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14342                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14343    }
14344
14345    @Override
14346    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14347            throws RemoteException {
14348        mContext.enforceCallingOrSelfPermission(
14349                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14350                "Only intentfilter verification agents can verify applications");
14351
14352        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14353        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14354                Binder.getCallingUid(), verificationCode, failedDomains);
14355        msg.arg1 = id;
14356        msg.obj = response;
14357        mHandler.sendMessage(msg);
14358    }
14359
14360    @Override
14361    public int getIntentVerificationStatus(String packageName, int userId) {
14362        final int callingUid = Binder.getCallingUid();
14363        if (UserHandle.getUserId(callingUid) != userId) {
14364            mContext.enforceCallingOrSelfPermission(
14365                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14366                    "getIntentVerificationStatus" + userId);
14367        }
14368        if (getInstantAppPackageName(callingUid) != null) {
14369            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14370        }
14371        synchronized (mPackages) {
14372            final PackageSetting ps = mSettings.mPackages.get(packageName);
14373            if (ps == null
14374                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14375                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14376            }
14377            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14378        }
14379    }
14380
14381    @Override
14382    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14383        mContext.enforceCallingOrSelfPermission(
14384                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14385
14386        boolean result = false;
14387        synchronized (mPackages) {
14388            final PackageSetting ps = mSettings.mPackages.get(packageName);
14389            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14390                return false;
14391            }
14392            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14393        }
14394        if (result) {
14395            scheduleWritePackageRestrictionsLocked(userId);
14396        }
14397        return result;
14398    }
14399
14400    @Override
14401    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14402            String packageName) {
14403        final int callingUid = Binder.getCallingUid();
14404        if (getInstantAppPackageName(callingUid) != null) {
14405            return ParceledListSlice.emptyList();
14406        }
14407        synchronized (mPackages) {
14408            final PackageSetting ps = mSettings.mPackages.get(packageName);
14409            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14410                return ParceledListSlice.emptyList();
14411            }
14412            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14413        }
14414    }
14415
14416    @Override
14417    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14418        if (TextUtils.isEmpty(packageName)) {
14419            return ParceledListSlice.emptyList();
14420        }
14421        final int callingUid = Binder.getCallingUid();
14422        final int callingUserId = UserHandle.getUserId(callingUid);
14423        synchronized (mPackages) {
14424            PackageParser.Package pkg = mPackages.get(packageName);
14425            if (pkg == null || pkg.activities == null) {
14426                return ParceledListSlice.emptyList();
14427            }
14428            if (pkg.mExtras == null) {
14429                return ParceledListSlice.emptyList();
14430            }
14431            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14432            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14433                return ParceledListSlice.emptyList();
14434            }
14435            final int count = pkg.activities.size();
14436            ArrayList<IntentFilter> result = new ArrayList<>();
14437            for (int n=0; n<count; n++) {
14438                PackageParser.Activity activity = pkg.activities.get(n);
14439                if (activity.intents != null && activity.intents.size() > 0) {
14440                    result.addAll(activity.intents);
14441                }
14442            }
14443            return new ParceledListSlice<>(result);
14444        }
14445    }
14446
14447    @Override
14448    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14449        mContext.enforceCallingOrSelfPermission(
14450                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14451        if (UserHandle.getCallingUserId() != userId) {
14452            mContext.enforceCallingOrSelfPermission(
14453                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14454        }
14455
14456        synchronized (mPackages) {
14457            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14458            if (packageName != null) {
14459                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14460                        packageName, userId);
14461            }
14462            return result;
14463        }
14464    }
14465
14466    @Override
14467    public String getDefaultBrowserPackageName(int userId) {
14468        if (UserHandle.getCallingUserId() != userId) {
14469            mContext.enforceCallingOrSelfPermission(
14470                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14471        }
14472        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14473            return null;
14474        }
14475        synchronized (mPackages) {
14476            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14477        }
14478    }
14479
14480    /**
14481     * Get the "allow unknown sources" setting.
14482     *
14483     * @return the current "allow unknown sources" setting
14484     */
14485    private int getUnknownSourcesSettings() {
14486        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14487                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14488                -1);
14489    }
14490
14491    @Override
14492    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14493        final int callingUid = Binder.getCallingUid();
14494        if (getInstantAppPackageName(callingUid) != null) {
14495            return;
14496        }
14497        // writer
14498        synchronized (mPackages) {
14499            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14500            if (targetPackageSetting == null
14501                    || filterAppAccessLPr(
14502                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14503                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14504            }
14505
14506            PackageSetting installerPackageSetting;
14507            if (installerPackageName != null) {
14508                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14509                if (installerPackageSetting == null) {
14510                    throw new IllegalArgumentException("Unknown installer package: "
14511                            + installerPackageName);
14512                }
14513            } else {
14514                installerPackageSetting = null;
14515            }
14516
14517            Signature[] callerSignature;
14518            Object obj = mSettings.getUserIdLPr(callingUid);
14519            if (obj != null) {
14520                if (obj instanceof SharedUserSetting) {
14521                    callerSignature =
14522                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14523                } else if (obj instanceof PackageSetting) {
14524                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14525                } else {
14526                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14527                }
14528            } else {
14529                throw new SecurityException("Unknown calling UID: " + callingUid);
14530            }
14531
14532            // Verify: can't set installerPackageName to a package that is
14533            // not signed with the same cert as the caller.
14534            if (installerPackageSetting != null) {
14535                if (compareSignatures(callerSignature,
14536                        installerPackageSetting.signatures.mSigningDetails.signatures)
14537                        != PackageManager.SIGNATURE_MATCH) {
14538                    throw new SecurityException(
14539                            "Caller does not have same cert as new installer package "
14540                            + installerPackageName);
14541                }
14542            }
14543
14544            // Verify: if target already has an installer package, it must
14545            // be signed with the same cert as the caller.
14546            if (targetPackageSetting.installerPackageName != null) {
14547                PackageSetting setting = mSettings.mPackages.get(
14548                        targetPackageSetting.installerPackageName);
14549                // If the currently set package isn't valid, then it's always
14550                // okay to change it.
14551                if (setting != null) {
14552                    if (compareSignatures(callerSignature,
14553                            setting.signatures.mSigningDetails.signatures)
14554                            != PackageManager.SIGNATURE_MATCH) {
14555                        throw new SecurityException(
14556                                "Caller does not have same cert as old installer package "
14557                                + targetPackageSetting.installerPackageName);
14558                    }
14559                }
14560            }
14561
14562            // Okay!
14563            targetPackageSetting.installerPackageName = installerPackageName;
14564            if (installerPackageName != null) {
14565                mSettings.mInstallerPackages.add(installerPackageName);
14566            }
14567            scheduleWriteSettingsLocked();
14568        }
14569    }
14570
14571    @Override
14572    public void setApplicationCategoryHint(String packageName, int categoryHint,
14573            String callerPackageName) {
14574        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14575            throw new SecurityException("Instant applications don't have access to this method");
14576        }
14577        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14578                callerPackageName);
14579        synchronized (mPackages) {
14580            PackageSetting ps = mSettings.mPackages.get(packageName);
14581            if (ps == null) {
14582                throw new IllegalArgumentException("Unknown target package " + packageName);
14583            }
14584            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14585                throw new IllegalArgumentException("Unknown target package " + packageName);
14586            }
14587            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14588                throw new IllegalArgumentException("Calling package " + callerPackageName
14589                        + " is not installer for " + packageName);
14590            }
14591
14592            if (ps.categoryHint != categoryHint) {
14593                ps.categoryHint = categoryHint;
14594                scheduleWriteSettingsLocked();
14595            }
14596        }
14597    }
14598
14599    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14600        // Queue up an async operation since the package installation may take a little while.
14601        mHandler.post(new Runnable() {
14602            public void run() {
14603                mHandler.removeCallbacks(this);
14604                 // Result object to be returned
14605                PackageInstalledInfo res = new PackageInstalledInfo();
14606                res.setReturnCode(currentStatus);
14607                res.uid = -1;
14608                res.pkg = null;
14609                res.removedInfo = null;
14610                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14611                    args.doPreInstall(res.returnCode);
14612                    synchronized (mInstallLock) {
14613                        installPackageTracedLI(args, res);
14614                    }
14615                    args.doPostInstall(res.returnCode, res.uid);
14616                }
14617
14618                // A restore should be performed at this point if (a) the install
14619                // succeeded, (b) the operation is not an update, and (c) the new
14620                // package has not opted out of backup participation.
14621                final boolean update = res.removedInfo != null
14622                        && res.removedInfo.removedPackage != null;
14623                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14624                boolean doRestore = !update
14625                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14626
14627                // Set up the post-install work request bookkeeping.  This will be used
14628                // and cleaned up by the post-install event handling regardless of whether
14629                // there's a restore pass performed.  Token values are >= 1.
14630                int token;
14631                if (mNextInstallToken < 0) mNextInstallToken = 1;
14632                token = mNextInstallToken++;
14633
14634                PostInstallData data = new PostInstallData(args, res);
14635                mRunningInstalls.put(token, data);
14636                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14637
14638                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14639                    // Pass responsibility to the Backup Manager.  It will perform a
14640                    // restore if appropriate, then pass responsibility back to the
14641                    // Package Manager to run the post-install observer callbacks
14642                    // and broadcasts.
14643                    IBackupManager bm = IBackupManager.Stub.asInterface(
14644                            ServiceManager.getService(Context.BACKUP_SERVICE));
14645                    if (bm != null) {
14646                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14647                                + " to BM for possible restore");
14648                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14649                        try {
14650                            // TODO: http://b/22388012
14651                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14652                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14653                            } else {
14654                                doRestore = false;
14655                            }
14656                        } catch (RemoteException e) {
14657                            // can't happen; the backup manager is local
14658                        } catch (Exception e) {
14659                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14660                            doRestore = false;
14661                        }
14662                    } else {
14663                        Slog.e(TAG, "Backup Manager not found!");
14664                        doRestore = false;
14665                    }
14666                }
14667
14668                if (!doRestore) {
14669                    // No restore possible, or the Backup Manager was mysteriously not
14670                    // available -- just fire the post-install work request directly.
14671                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14672
14673                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14674
14675                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14676                    mHandler.sendMessage(msg);
14677                }
14678            }
14679        });
14680    }
14681
14682    /**
14683     * Callback from PackageSettings whenever an app is first transitioned out of the
14684     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14685     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14686     * here whether the app is the target of an ongoing install, and only send the
14687     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14688     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14689     * handling.
14690     */
14691    void notifyFirstLaunch(final String packageName, final String installerPackage,
14692            final int userId) {
14693        // Serialize this with the rest of the install-process message chain.  In the
14694        // restore-at-install case, this Runnable will necessarily run before the
14695        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14696        // are coherent.  In the non-restore case, the app has already completed install
14697        // and been launched through some other means, so it is not in a problematic
14698        // state for observers to see the FIRST_LAUNCH signal.
14699        mHandler.post(new Runnable() {
14700            @Override
14701            public void run() {
14702                for (int i = 0; i < mRunningInstalls.size(); i++) {
14703                    final PostInstallData data = mRunningInstalls.valueAt(i);
14704                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14705                        continue;
14706                    }
14707                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14708                        // right package; but is it for the right user?
14709                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14710                            if (userId == data.res.newUsers[uIndex]) {
14711                                if (DEBUG_BACKUP) {
14712                                    Slog.i(TAG, "Package " + packageName
14713                                            + " being restored so deferring FIRST_LAUNCH");
14714                                }
14715                                return;
14716                            }
14717                        }
14718                    }
14719                }
14720                // didn't find it, so not being restored
14721                if (DEBUG_BACKUP) {
14722                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14723                }
14724                final boolean isInstantApp = isInstantApp(packageName, userId);
14725                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14726                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14727                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14728            }
14729        });
14730    }
14731
14732    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14733            int[] userIds, int[] instantUserIds) {
14734        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14735                installerPkg, null, userIds, instantUserIds);
14736    }
14737
14738    private abstract class HandlerParams {
14739        private static final int MAX_RETRIES = 4;
14740
14741        /**
14742         * Number of times startCopy() has been attempted and had a non-fatal
14743         * error.
14744         */
14745        private int mRetries = 0;
14746
14747        /** User handle for the user requesting the information or installation. */
14748        private final UserHandle mUser;
14749        String traceMethod;
14750        int traceCookie;
14751
14752        HandlerParams(UserHandle user) {
14753            mUser = user;
14754        }
14755
14756        UserHandle getUser() {
14757            return mUser;
14758        }
14759
14760        HandlerParams setTraceMethod(String traceMethod) {
14761            this.traceMethod = traceMethod;
14762            return this;
14763        }
14764
14765        HandlerParams setTraceCookie(int traceCookie) {
14766            this.traceCookie = traceCookie;
14767            return this;
14768        }
14769
14770        final boolean startCopy() {
14771            boolean res;
14772            try {
14773                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14774
14775                if (++mRetries > MAX_RETRIES) {
14776                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14777                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14778                    handleServiceError();
14779                    return false;
14780                } else {
14781                    handleStartCopy();
14782                    res = true;
14783                }
14784            } catch (RemoteException e) {
14785                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14786                mHandler.sendEmptyMessage(MCS_RECONNECT);
14787                res = false;
14788            }
14789            handleReturnCode();
14790            return res;
14791        }
14792
14793        final void serviceError() {
14794            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14795            handleServiceError();
14796            handleReturnCode();
14797        }
14798
14799        abstract void handleStartCopy() throws RemoteException;
14800        abstract void handleServiceError();
14801        abstract void handleReturnCode();
14802    }
14803
14804    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14805        for (File path : paths) {
14806            try {
14807                mcs.clearDirectory(path.getAbsolutePath());
14808            } catch (RemoteException e) {
14809            }
14810        }
14811    }
14812
14813    static class OriginInfo {
14814        /**
14815         * Location where install is coming from, before it has been
14816         * copied/renamed into place. This could be a single monolithic APK
14817         * file, or a cluster directory. This location may be untrusted.
14818         */
14819        final File file;
14820
14821        /**
14822         * Flag indicating that {@link #file} or {@link #cid} has already been
14823         * staged, meaning downstream users don't need to defensively copy the
14824         * contents.
14825         */
14826        final boolean staged;
14827
14828        /**
14829         * Flag indicating that {@link #file} or {@link #cid} is an already
14830         * installed app that is being moved.
14831         */
14832        final boolean existing;
14833
14834        final String resolvedPath;
14835        final File resolvedFile;
14836
14837        static OriginInfo fromNothing() {
14838            return new OriginInfo(null, false, false);
14839        }
14840
14841        static OriginInfo fromUntrustedFile(File file) {
14842            return new OriginInfo(file, false, false);
14843        }
14844
14845        static OriginInfo fromExistingFile(File file) {
14846            return new OriginInfo(file, false, true);
14847        }
14848
14849        static OriginInfo fromStagedFile(File file) {
14850            return new OriginInfo(file, true, false);
14851        }
14852
14853        private OriginInfo(File file, boolean staged, boolean existing) {
14854            this.file = file;
14855            this.staged = staged;
14856            this.existing = existing;
14857
14858            if (file != null) {
14859                resolvedPath = file.getAbsolutePath();
14860                resolvedFile = file;
14861            } else {
14862                resolvedPath = null;
14863                resolvedFile = null;
14864            }
14865        }
14866    }
14867
14868    static class MoveInfo {
14869        final int moveId;
14870        final String fromUuid;
14871        final String toUuid;
14872        final String packageName;
14873        final String dataAppName;
14874        final int appId;
14875        final String seinfo;
14876        final int targetSdkVersion;
14877
14878        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14879                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14880            this.moveId = moveId;
14881            this.fromUuid = fromUuid;
14882            this.toUuid = toUuid;
14883            this.packageName = packageName;
14884            this.dataAppName = dataAppName;
14885            this.appId = appId;
14886            this.seinfo = seinfo;
14887            this.targetSdkVersion = targetSdkVersion;
14888        }
14889    }
14890
14891    static class VerificationInfo {
14892        /** A constant used to indicate that a uid value is not present. */
14893        public static final int NO_UID = -1;
14894
14895        /** URI referencing where the package was downloaded from. */
14896        final Uri originatingUri;
14897
14898        /** HTTP referrer URI associated with the originatingURI. */
14899        final Uri referrer;
14900
14901        /** UID of the application that the install request originated from. */
14902        final int originatingUid;
14903
14904        /** UID of application requesting the install */
14905        final int installerUid;
14906
14907        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14908            this.originatingUri = originatingUri;
14909            this.referrer = referrer;
14910            this.originatingUid = originatingUid;
14911            this.installerUid = installerUid;
14912        }
14913    }
14914
14915    class InstallParams extends HandlerParams {
14916        final OriginInfo origin;
14917        final MoveInfo move;
14918        final IPackageInstallObserver2 observer;
14919        int installFlags;
14920        final String installerPackageName;
14921        final String volumeUuid;
14922        private InstallArgs mArgs;
14923        private int mRet;
14924        final String packageAbiOverride;
14925        final String[] grantedRuntimePermissions;
14926        final VerificationInfo verificationInfo;
14927        final PackageParser.SigningDetails signingDetails;
14928        final int installReason;
14929
14930        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14931                int installFlags, String installerPackageName, String volumeUuid,
14932                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14933                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
14934            super(user);
14935            this.origin = origin;
14936            this.move = move;
14937            this.observer = observer;
14938            this.installFlags = installFlags;
14939            this.installerPackageName = installerPackageName;
14940            this.volumeUuid = volumeUuid;
14941            this.verificationInfo = verificationInfo;
14942            this.packageAbiOverride = packageAbiOverride;
14943            this.grantedRuntimePermissions = grantedPermissions;
14944            this.signingDetails = signingDetails;
14945            this.installReason = installReason;
14946        }
14947
14948        @Override
14949        public String toString() {
14950            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14951                    + " file=" + origin.file + "}";
14952        }
14953
14954        private int installLocationPolicy(PackageInfoLite pkgLite) {
14955            String packageName = pkgLite.packageName;
14956            int installLocation = pkgLite.installLocation;
14957            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14958            // reader
14959            synchronized (mPackages) {
14960                // Currently installed package which the new package is attempting to replace or
14961                // null if no such package is installed.
14962                PackageParser.Package installedPkg = mPackages.get(packageName);
14963                // Package which currently owns the data which the new package will own if installed.
14964                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14965                // will be null whereas dataOwnerPkg will contain information about the package
14966                // which was uninstalled while keeping its data.
14967                PackageParser.Package dataOwnerPkg = installedPkg;
14968                if (dataOwnerPkg  == null) {
14969                    PackageSetting ps = mSettings.mPackages.get(packageName);
14970                    if (ps != null) {
14971                        dataOwnerPkg = ps.pkg;
14972                    }
14973                }
14974
14975                if (dataOwnerPkg != null) {
14976                    // If installed, the package will get access to data left on the device by its
14977                    // predecessor. As a security measure, this is permited only if this is not a
14978                    // version downgrade or if the predecessor package is marked as debuggable and
14979                    // a downgrade is explicitly requested.
14980                    //
14981                    // On debuggable platform builds, downgrades are permitted even for
14982                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14983                    // not offer security guarantees and thus it's OK to disable some security
14984                    // mechanisms to make debugging/testing easier on those builds. However, even on
14985                    // debuggable builds downgrades of packages are permitted only if requested via
14986                    // installFlags. This is because we aim to keep the behavior of debuggable
14987                    // platform builds as close as possible to the behavior of non-debuggable
14988                    // platform builds.
14989                    final boolean downgradeRequested =
14990                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14991                    final boolean packageDebuggable =
14992                                (dataOwnerPkg.applicationInfo.flags
14993                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14994                    final boolean downgradePermitted =
14995                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14996                    if (!downgradePermitted) {
14997                        try {
14998                            checkDowngrade(dataOwnerPkg, pkgLite);
14999                        } catch (PackageManagerException e) {
15000                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15001                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15002                        }
15003                    }
15004                }
15005
15006                if (installedPkg != null) {
15007                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15008                        // Check for updated system application.
15009                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15010                            if (onSd) {
15011                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15012                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15013                            }
15014                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15015                        } else {
15016                            if (onSd) {
15017                                // Install flag overrides everything.
15018                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15019                            }
15020                            // If current upgrade specifies particular preference
15021                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15022                                // Application explicitly specified internal.
15023                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15024                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15025                                // App explictly prefers external. Let policy decide
15026                            } else {
15027                                // Prefer previous location
15028                                if (isExternal(installedPkg)) {
15029                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15030                                }
15031                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15032                            }
15033                        }
15034                    } else {
15035                        // Invalid install. Return error code
15036                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15037                    }
15038                }
15039            }
15040            // All the special cases have been taken care of.
15041            // Return result based on recommended install location.
15042            if (onSd) {
15043                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15044            }
15045            return pkgLite.recommendedInstallLocation;
15046        }
15047
15048        /*
15049         * Invoke remote method to get package information and install
15050         * location values. Override install location based on default
15051         * policy if needed and then create install arguments based
15052         * on the install location.
15053         */
15054        public void handleStartCopy() throws RemoteException {
15055            int ret = PackageManager.INSTALL_SUCCEEDED;
15056
15057            // If we're already staged, we've firmly committed to an install location
15058            if (origin.staged) {
15059                if (origin.file != null) {
15060                    installFlags |= PackageManager.INSTALL_INTERNAL;
15061                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15062                } else {
15063                    throw new IllegalStateException("Invalid stage location");
15064                }
15065            }
15066
15067            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15068            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15069            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15070            PackageInfoLite pkgLite = null;
15071
15072            if (onInt && onSd) {
15073                // Check if both bits are set.
15074                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15075                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15076            } else if (onSd && ephemeral) {
15077                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15078                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15079            } else {
15080                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15081                        packageAbiOverride);
15082
15083                if (DEBUG_INSTANT && ephemeral) {
15084                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15085                }
15086
15087                /*
15088                 * If we have too little free space, try to free cache
15089                 * before giving up.
15090                 */
15091                if (!origin.staged && pkgLite.recommendedInstallLocation
15092                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15093                    // TODO: focus freeing disk space on the target device
15094                    final StorageManager storage = StorageManager.from(mContext);
15095                    final long lowThreshold = storage.getStorageLowBytes(
15096                            Environment.getDataDirectory());
15097
15098                    final long sizeBytes = mContainerService.calculateInstalledSize(
15099                            origin.resolvedPath, packageAbiOverride);
15100
15101                    try {
15102                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15103                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15104                                installFlags, packageAbiOverride);
15105                    } catch (InstallerException e) {
15106                        Slog.w(TAG, "Failed to free cache", e);
15107                    }
15108
15109                    /*
15110                     * The cache free must have deleted the file we
15111                     * downloaded to install.
15112                     *
15113                     * TODO: fix the "freeCache" call to not delete
15114                     *       the file we care about.
15115                     */
15116                    if (pkgLite.recommendedInstallLocation
15117                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15118                        pkgLite.recommendedInstallLocation
15119                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15120                    }
15121                }
15122            }
15123
15124            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15125                int loc = pkgLite.recommendedInstallLocation;
15126                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15127                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15128                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15129                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15130                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15131                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15132                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15133                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15134                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15135                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15136                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15137                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15138                } else {
15139                    // Override with defaults if needed.
15140                    loc = installLocationPolicy(pkgLite);
15141                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15142                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15143                    } else if (!onSd && !onInt) {
15144                        // Override install location with flags
15145                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15146                            // Set the flag to install on external media.
15147                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15148                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15149                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15150                            if (DEBUG_INSTANT) {
15151                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15152                            }
15153                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15154                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15155                                    |PackageManager.INSTALL_INTERNAL);
15156                        } else {
15157                            // Make sure the flag for installing on external
15158                            // media is unset
15159                            installFlags |= PackageManager.INSTALL_INTERNAL;
15160                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15161                        }
15162                    }
15163                }
15164            }
15165
15166            final InstallArgs args = createInstallArgs(this);
15167            mArgs = args;
15168
15169            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15170                // TODO: http://b/22976637
15171                // Apps installed for "all" users use the device owner to verify the app
15172                UserHandle verifierUser = getUser();
15173                if (verifierUser == UserHandle.ALL) {
15174                    verifierUser = UserHandle.SYSTEM;
15175                }
15176
15177                /*
15178                 * Determine if we have any installed package verifiers. If we
15179                 * do, then we'll defer to them to verify the packages.
15180                 */
15181                final int requiredUid = mRequiredVerifierPackage == null ? -1
15182                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15183                                verifierUser.getIdentifier());
15184                final int installerUid =
15185                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15186                if (!origin.existing && requiredUid != -1
15187                        && isVerificationEnabled(
15188                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15189                    final Intent verification = new Intent(
15190                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15191                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15192                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15193                            PACKAGE_MIME_TYPE);
15194                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15195
15196                    // Query all live verifiers based on current user state
15197                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15198                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15199                            false /*allowDynamicSplits*/);
15200
15201                    if (DEBUG_VERIFY) {
15202                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15203                                + verification.toString() + " with " + pkgLite.verifiers.length
15204                                + " optional verifiers");
15205                    }
15206
15207                    final int verificationId = mPendingVerificationToken++;
15208
15209                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15210
15211                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15212                            installerPackageName);
15213
15214                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15215                            installFlags);
15216
15217                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15218                            pkgLite.packageName);
15219
15220                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15221                            pkgLite.versionCode);
15222
15223                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15224                            pkgLite.getLongVersionCode());
15225
15226                    if (verificationInfo != null) {
15227                        if (verificationInfo.originatingUri != null) {
15228                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15229                                    verificationInfo.originatingUri);
15230                        }
15231                        if (verificationInfo.referrer != null) {
15232                            verification.putExtra(Intent.EXTRA_REFERRER,
15233                                    verificationInfo.referrer);
15234                        }
15235                        if (verificationInfo.originatingUid >= 0) {
15236                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15237                                    verificationInfo.originatingUid);
15238                        }
15239                        if (verificationInfo.installerUid >= 0) {
15240                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15241                                    verificationInfo.installerUid);
15242                        }
15243                    }
15244
15245                    final PackageVerificationState verificationState = new PackageVerificationState(
15246                            requiredUid, args);
15247
15248                    mPendingVerification.append(verificationId, verificationState);
15249
15250                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15251                            receivers, verificationState);
15252
15253                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15254                    final long idleDuration = getVerificationTimeout();
15255
15256                    /*
15257                     * If any sufficient verifiers were listed in the package
15258                     * manifest, attempt to ask them.
15259                     */
15260                    if (sufficientVerifiers != null) {
15261                        final int N = sufficientVerifiers.size();
15262                        if (N == 0) {
15263                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15264                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15265                        } else {
15266                            for (int i = 0; i < N; i++) {
15267                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15268                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15269                                        verifierComponent.getPackageName(), idleDuration,
15270                                        verifierUser.getIdentifier(), false, "package verifier");
15271
15272                                final Intent sufficientIntent = new Intent(verification);
15273                                sufficientIntent.setComponent(verifierComponent);
15274                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15275                            }
15276                        }
15277                    }
15278
15279                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15280                            mRequiredVerifierPackage, receivers);
15281                    if (ret == PackageManager.INSTALL_SUCCEEDED
15282                            && mRequiredVerifierPackage != null) {
15283                        Trace.asyncTraceBegin(
15284                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15285                        /*
15286                         * Send the intent to the required verification agent,
15287                         * but only start the verification timeout after the
15288                         * target BroadcastReceivers have run.
15289                         */
15290                        verification.setComponent(requiredVerifierComponent);
15291                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15292                                mRequiredVerifierPackage, idleDuration,
15293                                verifierUser.getIdentifier(), false, "package verifier");
15294                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15295                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15296                                new BroadcastReceiver() {
15297                                    @Override
15298                                    public void onReceive(Context context, Intent intent) {
15299                                        final Message msg = mHandler
15300                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15301                                        msg.arg1 = verificationId;
15302                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15303                                    }
15304                                }, null, 0, null, null);
15305
15306                        /*
15307                         * We don't want the copy to proceed until verification
15308                         * succeeds, so null out this field.
15309                         */
15310                        mArgs = null;
15311                    }
15312                } else {
15313                    /*
15314                     * No package verification is enabled, so immediately start
15315                     * the remote call to initiate copy using temporary file.
15316                     */
15317                    ret = args.copyApk(mContainerService, true);
15318                }
15319            }
15320
15321            mRet = ret;
15322        }
15323
15324        @Override
15325        void handleReturnCode() {
15326            // If mArgs is null, then MCS couldn't be reached. When it
15327            // reconnects, it will try again to install. At that point, this
15328            // will succeed.
15329            if (mArgs != null) {
15330                processPendingInstall(mArgs, mRet);
15331            }
15332        }
15333
15334        @Override
15335        void handleServiceError() {
15336            mArgs = createInstallArgs(this);
15337            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15338        }
15339    }
15340
15341    private InstallArgs createInstallArgs(InstallParams params) {
15342        if (params.move != null) {
15343            return new MoveInstallArgs(params);
15344        } else {
15345            return new FileInstallArgs(params);
15346        }
15347    }
15348
15349    /**
15350     * Create args that describe an existing installed package. Typically used
15351     * when cleaning up old installs, or used as a move source.
15352     */
15353    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15354            String resourcePath, String[] instructionSets) {
15355        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15356    }
15357
15358    static abstract class InstallArgs {
15359        /** @see InstallParams#origin */
15360        final OriginInfo origin;
15361        /** @see InstallParams#move */
15362        final MoveInfo move;
15363
15364        final IPackageInstallObserver2 observer;
15365        // Always refers to PackageManager flags only
15366        final int installFlags;
15367        final String installerPackageName;
15368        final String volumeUuid;
15369        final UserHandle user;
15370        final String abiOverride;
15371        final String[] installGrantPermissions;
15372        /** If non-null, drop an async trace when the install completes */
15373        final String traceMethod;
15374        final int traceCookie;
15375        final PackageParser.SigningDetails signingDetails;
15376        final int installReason;
15377
15378        // The list of instruction sets supported by this app. This is currently
15379        // only used during the rmdex() phase to clean up resources. We can get rid of this
15380        // if we move dex files under the common app path.
15381        /* nullable */ String[] instructionSets;
15382
15383        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15384                int installFlags, String installerPackageName, String volumeUuid,
15385                UserHandle user, String[] instructionSets,
15386                String abiOverride, String[] installGrantPermissions,
15387                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15388                int installReason) {
15389            this.origin = origin;
15390            this.move = move;
15391            this.installFlags = installFlags;
15392            this.observer = observer;
15393            this.installerPackageName = installerPackageName;
15394            this.volumeUuid = volumeUuid;
15395            this.user = user;
15396            this.instructionSets = instructionSets;
15397            this.abiOverride = abiOverride;
15398            this.installGrantPermissions = installGrantPermissions;
15399            this.traceMethod = traceMethod;
15400            this.traceCookie = traceCookie;
15401            this.signingDetails = signingDetails;
15402            this.installReason = installReason;
15403        }
15404
15405        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15406        abstract int doPreInstall(int status);
15407
15408        /**
15409         * Rename package into final resting place. All paths on the given
15410         * scanned package should be updated to reflect the rename.
15411         */
15412        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15413        abstract int doPostInstall(int status, int uid);
15414
15415        /** @see PackageSettingBase#codePathString */
15416        abstract String getCodePath();
15417        /** @see PackageSettingBase#resourcePathString */
15418        abstract String getResourcePath();
15419
15420        // Need installer lock especially for dex file removal.
15421        abstract void cleanUpResourcesLI();
15422        abstract boolean doPostDeleteLI(boolean delete);
15423
15424        /**
15425         * Called before the source arguments are copied. This is used mostly
15426         * for MoveParams when it needs to read the source file to put it in the
15427         * destination.
15428         */
15429        int doPreCopy() {
15430            return PackageManager.INSTALL_SUCCEEDED;
15431        }
15432
15433        /**
15434         * Called after the source arguments are copied. This is used mostly for
15435         * MoveParams when it needs to read the source file to put it in the
15436         * destination.
15437         */
15438        int doPostCopy(int uid) {
15439            return PackageManager.INSTALL_SUCCEEDED;
15440        }
15441
15442        protected boolean isFwdLocked() {
15443            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15444        }
15445
15446        protected boolean isExternalAsec() {
15447            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15448        }
15449
15450        protected boolean isEphemeral() {
15451            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15452        }
15453
15454        UserHandle getUser() {
15455            return user;
15456        }
15457    }
15458
15459    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15460        if (!allCodePaths.isEmpty()) {
15461            if (instructionSets == null) {
15462                throw new IllegalStateException("instructionSet == null");
15463            }
15464            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15465            for (String codePath : allCodePaths) {
15466                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15467                    try {
15468                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15469                    } catch (InstallerException ignored) {
15470                    }
15471                }
15472            }
15473        }
15474    }
15475
15476    /**
15477     * Logic to handle installation of non-ASEC applications, including copying
15478     * and renaming logic.
15479     */
15480    class FileInstallArgs extends InstallArgs {
15481        private File codeFile;
15482        private File resourceFile;
15483
15484        // Example topology:
15485        // /data/app/com.example/base.apk
15486        // /data/app/com.example/split_foo.apk
15487        // /data/app/com.example/lib/arm/libfoo.so
15488        // /data/app/com.example/lib/arm64/libfoo.so
15489        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15490
15491        /** New install */
15492        FileInstallArgs(InstallParams params) {
15493            super(params.origin, params.move, params.observer, params.installFlags,
15494                    params.installerPackageName, params.volumeUuid,
15495                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15496                    params.grantedRuntimePermissions,
15497                    params.traceMethod, params.traceCookie, params.signingDetails,
15498                    params.installReason);
15499            if (isFwdLocked()) {
15500                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15501            }
15502        }
15503
15504        /** Existing install */
15505        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15506            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15507                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15508                    PackageManager.INSTALL_REASON_UNKNOWN);
15509            this.codeFile = (codePath != null) ? new File(codePath) : null;
15510            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15511        }
15512
15513        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15514            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15515            try {
15516                return doCopyApk(imcs, temp);
15517            } finally {
15518                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15519            }
15520        }
15521
15522        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15523            if (origin.staged) {
15524                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15525                codeFile = origin.file;
15526                resourceFile = origin.file;
15527                return PackageManager.INSTALL_SUCCEEDED;
15528            }
15529
15530            try {
15531                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15532                final File tempDir =
15533                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15534                codeFile = tempDir;
15535                resourceFile = tempDir;
15536            } catch (IOException e) {
15537                Slog.w(TAG, "Failed to create copy file: " + e);
15538                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15539            }
15540
15541            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15542                @Override
15543                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15544                    if (!FileUtils.isValidExtFilename(name)) {
15545                        throw new IllegalArgumentException("Invalid filename: " + name);
15546                    }
15547                    try {
15548                        final File file = new File(codeFile, name);
15549                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15550                                O_RDWR | O_CREAT, 0644);
15551                        Os.chmod(file.getAbsolutePath(), 0644);
15552                        return new ParcelFileDescriptor(fd);
15553                    } catch (ErrnoException e) {
15554                        throw new RemoteException("Failed to open: " + e.getMessage());
15555                    }
15556                }
15557            };
15558
15559            int ret = PackageManager.INSTALL_SUCCEEDED;
15560            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15561            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15562                Slog.e(TAG, "Failed to copy package");
15563                return ret;
15564            }
15565
15566            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15567            NativeLibraryHelper.Handle handle = null;
15568            try {
15569                handle = NativeLibraryHelper.Handle.create(codeFile);
15570                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15571                        abiOverride);
15572            } catch (IOException e) {
15573                Slog.e(TAG, "Copying native libraries failed", e);
15574                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15575            } finally {
15576                IoUtils.closeQuietly(handle);
15577            }
15578
15579            return ret;
15580        }
15581
15582        int doPreInstall(int status) {
15583            if (status != PackageManager.INSTALL_SUCCEEDED) {
15584                cleanUp();
15585            }
15586            return status;
15587        }
15588
15589        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15590            if (status != PackageManager.INSTALL_SUCCEEDED) {
15591                cleanUp();
15592                return false;
15593            }
15594
15595            final File targetDir = codeFile.getParentFile();
15596            final File beforeCodeFile = codeFile;
15597            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15598
15599            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15600            try {
15601                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15602            } catch (ErrnoException e) {
15603                Slog.w(TAG, "Failed to rename", e);
15604                return false;
15605            }
15606
15607            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15608                Slog.w(TAG, "Failed to restorecon");
15609                return false;
15610            }
15611
15612            // Reflect the rename internally
15613            codeFile = afterCodeFile;
15614            resourceFile = afterCodeFile;
15615
15616            // Reflect the rename in scanned details
15617            try {
15618                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15619            } catch (IOException e) {
15620                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15621                return false;
15622            }
15623            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15624                    afterCodeFile, pkg.baseCodePath));
15625            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15626                    afterCodeFile, pkg.splitCodePaths));
15627
15628            // Reflect the rename in app info
15629            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15630            pkg.setApplicationInfoCodePath(pkg.codePath);
15631            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15632            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15633            pkg.setApplicationInfoResourcePath(pkg.codePath);
15634            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15635            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15636
15637            return true;
15638        }
15639
15640        int doPostInstall(int status, int uid) {
15641            if (status != PackageManager.INSTALL_SUCCEEDED) {
15642                cleanUp();
15643            }
15644            return status;
15645        }
15646
15647        @Override
15648        String getCodePath() {
15649            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15650        }
15651
15652        @Override
15653        String getResourcePath() {
15654            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15655        }
15656
15657        private boolean cleanUp() {
15658            if (codeFile == null || !codeFile.exists()) {
15659                return false;
15660            }
15661
15662            removeCodePathLI(codeFile);
15663
15664            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15665                resourceFile.delete();
15666            }
15667
15668            return true;
15669        }
15670
15671        void cleanUpResourcesLI() {
15672            // Try enumerating all code paths before deleting
15673            List<String> allCodePaths = Collections.EMPTY_LIST;
15674            if (codeFile != null && codeFile.exists()) {
15675                try {
15676                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15677                    allCodePaths = pkg.getAllCodePaths();
15678                } catch (PackageParserException e) {
15679                    // Ignored; we tried our best
15680                }
15681            }
15682
15683            cleanUp();
15684            removeDexFiles(allCodePaths, instructionSets);
15685        }
15686
15687        boolean doPostDeleteLI(boolean delete) {
15688            // XXX err, shouldn't we respect the delete flag?
15689            cleanUpResourcesLI();
15690            return true;
15691        }
15692    }
15693
15694    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15695            PackageManagerException {
15696        if (copyRet < 0) {
15697            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15698                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15699                throw new PackageManagerException(copyRet, message);
15700            }
15701        }
15702    }
15703
15704    /**
15705     * Extract the StorageManagerService "container ID" from the full code path of an
15706     * .apk.
15707     */
15708    static String cidFromCodePath(String fullCodePath) {
15709        int eidx = fullCodePath.lastIndexOf("/");
15710        String subStr1 = fullCodePath.substring(0, eidx);
15711        int sidx = subStr1.lastIndexOf("/");
15712        return subStr1.substring(sidx+1, eidx);
15713    }
15714
15715    /**
15716     * Logic to handle movement of existing installed applications.
15717     */
15718    class MoveInstallArgs extends InstallArgs {
15719        private File codeFile;
15720        private File resourceFile;
15721
15722        /** New install */
15723        MoveInstallArgs(InstallParams params) {
15724            super(params.origin, params.move, params.observer, params.installFlags,
15725                    params.installerPackageName, params.volumeUuid,
15726                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15727                    params.grantedRuntimePermissions,
15728                    params.traceMethod, params.traceCookie, params.signingDetails,
15729                    params.installReason);
15730        }
15731
15732        int copyApk(IMediaContainerService imcs, boolean temp) {
15733            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15734                    + move.fromUuid + " to " + move.toUuid);
15735            synchronized (mInstaller) {
15736                try {
15737                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15738                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15739                } catch (InstallerException e) {
15740                    Slog.w(TAG, "Failed to move app", e);
15741                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15742                }
15743            }
15744
15745            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15746            resourceFile = codeFile;
15747            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15748
15749            return PackageManager.INSTALL_SUCCEEDED;
15750        }
15751
15752        int doPreInstall(int status) {
15753            if (status != PackageManager.INSTALL_SUCCEEDED) {
15754                cleanUp(move.toUuid);
15755            }
15756            return status;
15757        }
15758
15759        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15760            if (status != PackageManager.INSTALL_SUCCEEDED) {
15761                cleanUp(move.toUuid);
15762                return false;
15763            }
15764
15765            // Reflect the move in app info
15766            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15767            pkg.setApplicationInfoCodePath(pkg.codePath);
15768            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15769            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15770            pkg.setApplicationInfoResourcePath(pkg.codePath);
15771            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15772            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15773
15774            return true;
15775        }
15776
15777        int doPostInstall(int status, int uid) {
15778            if (status == PackageManager.INSTALL_SUCCEEDED) {
15779                cleanUp(move.fromUuid);
15780            } else {
15781                cleanUp(move.toUuid);
15782            }
15783            return status;
15784        }
15785
15786        @Override
15787        String getCodePath() {
15788            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15789        }
15790
15791        @Override
15792        String getResourcePath() {
15793            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15794        }
15795
15796        private boolean cleanUp(String volumeUuid) {
15797            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15798                    move.dataAppName);
15799            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15800            final int[] userIds = sUserManager.getUserIds();
15801            synchronized (mInstallLock) {
15802                // Clean up both app data and code
15803                // All package moves are frozen until finished
15804                for (int userId : userIds) {
15805                    try {
15806                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15807                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15808                    } catch (InstallerException e) {
15809                        Slog.w(TAG, String.valueOf(e));
15810                    }
15811                }
15812                removeCodePathLI(codeFile);
15813            }
15814            return true;
15815        }
15816
15817        void cleanUpResourcesLI() {
15818            throw new UnsupportedOperationException();
15819        }
15820
15821        boolean doPostDeleteLI(boolean delete) {
15822            throw new UnsupportedOperationException();
15823        }
15824    }
15825
15826    static String getAsecPackageName(String packageCid) {
15827        int idx = packageCid.lastIndexOf("-");
15828        if (idx == -1) {
15829            return packageCid;
15830        }
15831        return packageCid.substring(0, idx);
15832    }
15833
15834    // Utility method used to create code paths based on package name and available index.
15835    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15836        String idxStr = "";
15837        int idx = 1;
15838        // Fall back to default value of idx=1 if prefix is not
15839        // part of oldCodePath
15840        if (oldCodePath != null) {
15841            String subStr = oldCodePath;
15842            // Drop the suffix right away
15843            if (suffix != null && subStr.endsWith(suffix)) {
15844                subStr = subStr.substring(0, subStr.length() - suffix.length());
15845            }
15846            // If oldCodePath already contains prefix find out the
15847            // ending index to either increment or decrement.
15848            int sidx = subStr.lastIndexOf(prefix);
15849            if (sidx != -1) {
15850                subStr = subStr.substring(sidx + prefix.length());
15851                if (subStr != null) {
15852                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15853                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15854                    }
15855                    try {
15856                        idx = Integer.parseInt(subStr);
15857                        if (idx <= 1) {
15858                            idx++;
15859                        } else {
15860                            idx--;
15861                        }
15862                    } catch(NumberFormatException e) {
15863                    }
15864                }
15865            }
15866        }
15867        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15868        return prefix + idxStr;
15869    }
15870
15871    private File getNextCodePath(File targetDir, String packageName) {
15872        File result;
15873        SecureRandom random = new SecureRandom();
15874        byte[] bytes = new byte[16];
15875        do {
15876            random.nextBytes(bytes);
15877            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15878            result = new File(targetDir, packageName + "-" + suffix);
15879        } while (result.exists());
15880        return result;
15881    }
15882
15883    // Utility method that returns the relative package path with respect
15884    // to the installation directory. Like say for /data/data/com.test-1.apk
15885    // string com.test-1 is returned.
15886    static String deriveCodePathName(String codePath) {
15887        if (codePath == null) {
15888            return null;
15889        }
15890        final File codeFile = new File(codePath);
15891        final String name = codeFile.getName();
15892        if (codeFile.isDirectory()) {
15893            return name;
15894        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15895            final int lastDot = name.lastIndexOf('.');
15896            return name.substring(0, lastDot);
15897        } else {
15898            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15899            return null;
15900        }
15901    }
15902
15903    static class PackageInstalledInfo {
15904        String name;
15905        int uid;
15906        // The set of users that originally had this package installed.
15907        int[] origUsers;
15908        // The set of users that now have this package installed.
15909        int[] newUsers;
15910        PackageParser.Package pkg;
15911        int returnCode;
15912        String returnMsg;
15913        String installerPackageName;
15914        PackageRemovedInfo removedInfo;
15915        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15916
15917        public void setError(int code, String msg) {
15918            setReturnCode(code);
15919            setReturnMessage(msg);
15920            Slog.w(TAG, msg);
15921        }
15922
15923        public void setError(String msg, PackageParserException e) {
15924            setReturnCode(e.error);
15925            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15926            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15927            for (int i = 0; i < childCount; i++) {
15928                addedChildPackages.valueAt(i).setError(msg, e);
15929            }
15930            Slog.w(TAG, msg, e);
15931        }
15932
15933        public void setError(String msg, PackageManagerException e) {
15934            returnCode = e.error;
15935            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15936            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15937            for (int i = 0; i < childCount; i++) {
15938                addedChildPackages.valueAt(i).setError(msg, e);
15939            }
15940            Slog.w(TAG, msg, e);
15941        }
15942
15943        public void setReturnCode(int returnCode) {
15944            this.returnCode = returnCode;
15945            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15946            for (int i = 0; i < childCount; i++) {
15947                addedChildPackages.valueAt(i).returnCode = returnCode;
15948            }
15949        }
15950
15951        private void setReturnMessage(String returnMsg) {
15952            this.returnMsg = returnMsg;
15953            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15954            for (int i = 0; i < childCount; i++) {
15955                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15956            }
15957        }
15958
15959        // In some error cases we want to convey more info back to the observer
15960        String origPackage;
15961        String origPermission;
15962    }
15963
15964    /*
15965     * Install a non-existing package.
15966     */
15967    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15968            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15969            String volumeUuid, PackageInstalledInfo res, int installReason) {
15970        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15971
15972        // Remember this for later, in case we need to rollback this install
15973        String pkgName = pkg.packageName;
15974
15975        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15976
15977        synchronized(mPackages) {
15978            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15979            if (renamedPackage != null) {
15980                // A package with the same name is already installed, though
15981                // it has been renamed to an older name.  The package we
15982                // are trying to install should be installed as an update to
15983                // the existing one, but that has not been requested, so bail.
15984                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15985                        + " without first uninstalling package running as "
15986                        + renamedPackage);
15987                return;
15988            }
15989            if (mPackages.containsKey(pkgName)) {
15990                // Don't allow installation over an existing package with the same name.
15991                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15992                        + " without first uninstalling.");
15993                return;
15994            }
15995        }
15996
15997        try {
15998            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15999                    System.currentTimeMillis(), user);
16000
16001            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16002
16003            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16004                prepareAppDataAfterInstallLIF(newPackage);
16005
16006            } else {
16007                // Remove package from internal structures, but keep around any
16008                // data that might have already existed
16009                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16010                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16011            }
16012        } catch (PackageManagerException e) {
16013            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16014        }
16015
16016        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16017    }
16018
16019    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16020        try (DigestInputStream digestStream =
16021                new DigestInputStream(new FileInputStream(file), digest)) {
16022            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16023        }
16024    }
16025
16026    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16027            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16028            PackageInstalledInfo res, int installReason) {
16029        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16030
16031        final PackageParser.Package oldPackage;
16032        final PackageSetting ps;
16033        final String pkgName = pkg.packageName;
16034        final int[] allUsers;
16035        final int[] installedUsers;
16036
16037        synchronized(mPackages) {
16038            oldPackage = mPackages.get(pkgName);
16039            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16040
16041            // don't allow upgrade to target a release SDK from a pre-release SDK
16042            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16043                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16044            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16045                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16046            if (oldTargetsPreRelease
16047                    && !newTargetsPreRelease
16048                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16049                Slog.w(TAG, "Can't install package targeting released sdk");
16050                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16051                return;
16052            }
16053
16054            ps = mSettings.mPackages.get(pkgName);
16055
16056            // verify signatures are valid
16057            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16058            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16059                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16060                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16061                            "New package not signed by keys specified by upgrade-keysets: "
16062                                    + pkgName);
16063                    return;
16064                }
16065            } else {
16066
16067                // default to original signature matching
16068                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16069                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16070                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16071                            "New package has a different signature: " + pkgName);
16072                    return;
16073                }
16074            }
16075
16076            // don't allow a system upgrade unless the upgrade hash matches
16077            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16078                byte[] digestBytes = null;
16079                try {
16080                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16081                    updateDigest(digest, new File(pkg.baseCodePath));
16082                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16083                        for (String path : pkg.splitCodePaths) {
16084                            updateDigest(digest, new File(path));
16085                        }
16086                    }
16087                    digestBytes = digest.digest();
16088                } catch (NoSuchAlgorithmException | IOException e) {
16089                    res.setError(INSTALL_FAILED_INVALID_APK,
16090                            "Could not compute hash: " + pkgName);
16091                    return;
16092                }
16093                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16094                    res.setError(INSTALL_FAILED_INVALID_APK,
16095                            "New package fails restrict-update check: " + pkgName);
16096                    return;
16097                }
16098                // retain upgrade restriction
16099                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16100            }
16101
16102            // Check for shared user id changes
16103            String invalidPackageName =
16104                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16105            if (invalidPackageName != null) {
16106                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16107                        "Package " + invalidPackageName + " tried to change user "
16108                                + oldPackage.mSharedUserId);
16109                return;
16110            }
16111
16112            // check if the new package supports all of the abis which the old package supports
16113            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16114            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16115            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16116                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16117                        "Update to package " + pkgName + " doesn't support multi arch");
16118                return;
16119            }
16120
16121            // In case of rollback, remember per-user/profile install state
16122            allUsers = sUserManager.getUserIds();
16123            installedUsers = ps.queryInstalledUsers(allUsers, true);
16124
16125            // don't allow an upgrade from full to ephemeral
16126            if (isInstantApp) {
16127                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16128                    for (int currentUser : allUsers) {
16129                        if (!ps.getInstantApp(currentUser)) {
16130                            // can't downgrade from full to instant
16131                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16132                                    + " for user: " + currentUser);
16133                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16134                            return;
16135                        }
16136                    }
16137                } else if (!ps.getInstantApp(user.getIdentifier())) {
16138                    // can't downgrade from full to instant
16139                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16140                            + " for user: " + user.getIdentifier());
16141                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16142                    return;
16143                }
16144            }
16145        }
16146
16147        // Update what is removed
16148        res.removedInfo = new PackageRemovedInfo(this);
16149        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16150        res.removedInfo.removedPackage = oldPackage.packageName;
16151        res.removedInfo.installerPackageName = ps.installerPackageName;
16152        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16153        res.removedInfo.isUpdate = true;
16154        res.removedInfo.origUsers = installedUsers;
16155        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16156        for (int i = 0; i < installedUsers.length; i++) {
16157            final int userId = installedUsers[i];
16158            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16159        }
16160
16161        final int childCount = (oldPackage.childPackages != null)
16162                ? oldPackage.childPackages.size() : 0;
16163        for (int i = 0; i < childCount; i++) {
16164            boolean childPackageUpdated = false;
16165            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16166            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16167            if (res.addedChildPackages != null) {
16168                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16169                if (childRes != null) {
16170                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16171                    childRes.removedInfo.removedPackage = childPkg.packageName;
16172                    if (childPs != null) {
16173                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16174                    }
16175                    childRes.removedInfo.isUpdate = true;
16176                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16177                    childPackageUpdated = true;
16178                }
16179            }
16180            if (!childPackageUpdated) {
16181                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16182                childRemovedRes.removedPackage = childPkg.packageName;
16183                if (childPs != null) {
16184                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16185                }
16186                childRemovedRes.isUpdate = false;
16187                childRemovedRes.dataRemoved = true;
16188                synchronized (mPackages) {
16189                    if (childPs != null) {
16190                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16191                    }
16192                }
16193                if (res.removedInfo.removedChildPackages == null) {
16194                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16195                }
16196                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16197            }
16198        }
16199
16200        boolean sysPkg = (isSystemApp(oldPackage));
16201        if (sysPkg) {
16202            // Set the system/privileged/oem/vendor/product flags as needed
16203            final boolean privileged =
16204                    (oldPackage.applicationInfo.privateFlags
16205                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16206            final boolean oem =
16207                    (oldPackage.applicationInfo.privateFlags
16208                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16209            final boolean vendor =
16210                    (oldPackage.applicationInfo.privateFlags
16211                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16212            final boolean product =
16213                    (oldPackage.applicationInfo.privateFlags
16214                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16215            final @ParseFlags int systemParseFlags = parseFlags;
16216            final @ScanFlags int systemScanFlags = scanFlags
16217                    | SCAN_AS_SYSTEM
16218                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16219                    | (oem ? SCAN_AS_OEM : 0)
16220                    | (vendor ? SCAN_AS_VENDOR : 0)
16221                    | (product ? SCAN_AS_PRODUCT : 0);
16222
16223            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16224                    user, allUsers, installerPackageName, res, installReason);
16225        } else {
16226            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16227                    user, allUsers, installerPackageName, res, installReason);
16228        }
16229    }
16230
16231    @Override
16232    public List<String> getPreviousCodePaths(String packageName) {
16233        final int callingUid = Binder.getCallingUid();
16234        final List<String> result = new ArrayList<>();
16235        if (getInstantAppPackageName(callingUid) != null) {
16236            return result;
16237        }
16238        final PackageSetting ps = mSettings.mPackages.get(packageName);
16239        if (ps != null
16240                && ps.oldCodePaths != null
16241                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16242            result.addAll(ps.oldCodePaths);
16243        }
16244        return result;
16245    }
16246
16247    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16248            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16249            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16250            String installerPackageName, PackageInstalledInfo res, int installReason) {
16251        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16252                + deletedPackage);
16253
16254        String pkgName = deletedPackage.packageName;
16255        boolean deletedPkg = true;
16256        boolean addedPkg = false;
16257        boolean updatedSettings = false;
16258        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16259        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16260                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16261
16262        final long origUpdateTime = (pkg.mExtras != null)
16263                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16264
16265        // First delete the existing package while retaining the data directory
16266        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16267                res.removedInfo, true, pkg)) {
16268            // If the existing package wasn't successfully deleted
16269            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16270            deletedPkg = false;
16271        } else {
16272            // Successfully deleted the old package; proceed with replace.
16273
16274            // If deleted package lived in a container, give users a chance to
16275            // relinquish resources before killing.
16276            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16277                if (DEBUG_INSTALL) {
16278                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16279                }
16280                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16281                final ArrayList<String> pkgList = new ArrayList<String>(1);
16282                pkgList.add(deletedPackage.applicationInfo.packageName);
16283                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16284            }
16285
16286            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16287                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16288
16289            try {
16290                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16291                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16292                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16293                        installReason);
16294
16295                // Update the in-memory copy of the previous code paths.
16296                PackageSetting ps = mSettings.mPackages.get(pkgName);
16297                if (!killApp) {
16298                    if (ps.oldCodePaths == null) {
16299                        ps.oldCodePaths = new ArraySet<>();
16300                    }
16301                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16302                    if (deletedPackage.splitCodePaths != null) {
16303                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16304                    }
16305                } else {
16306                    ps.oldCodePaths = null;
16307                }
16308                if (ps.childPackageNames != null) {
16309                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16310                        final String childPkgName = ps.childPackageNames.get(i);
16311                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16312                        childPs.oldCodePaths = ps.oldCodePaths;
16313                    }
16314                }
16315                // set instant app status, but, only if it's explicitly specified
16316                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16317                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16318                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16319                prepareAppDataAfterInstallLIF(newPackage);
16320                addedPkg = true;
16321                mDexManager.notifyPackageUpdated(newPackage.packageName,
16322                        newPackage.baseCodePath, newPackage.splitCodePaths);
16323            } catch (PackageManagerException e) {
16324                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16325            }
16326        }
16327
16328        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16329            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16330
16331            // Revert all internal state mutations and added folders for the failed install
16332            if (addedPkg) {
16333                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16334                        res.removedInfo, true, null);
16335            }
16336
16337            // Restore the old package
16338            if (deletedPkg) {
16339                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16340                File restoreFile = new File(deletedPackage.codePath);
16341                // Parse old package
16342                boolean oldExternal = isExternal(deletedPackage);
16343                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16344                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16345                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16346                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16347                try {
16348                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16349                            null);
16350                } catch (PackageManagerException e) {
16351                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16352                            + e.getMessage());
16353                    return;
16354                }
16355
16356                synchronized (mPackages) {
16357                    // Ensure the installer package name up to date
16358                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16359
16360                    // Update permissions for restored package
16361                    mPermissionManager.updatePermissions(
16362                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16363                            mPermissionCallback);
16364
16365                    mSettings.writeLPr();
16366                }
16367
16368                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16369            }
16370        } else {
16371            synchronized (mPackages) {
16372                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16373                if (ps != null) {
16374                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16375                    if (res.removedInfo.removedChildPackages != null) {
16376                        final int childCount = res.removedInfo.removedChildPackages.size();
16377                        // Iterate in reverse as we may modify the collection
16378                        for (int i = childCount - 1; i >= 0; i--) {
16379                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16380                            if (res.addedChildPackages.containsKey(childPackageName)) {
16381                                res.removedInfo.removedChildPackages.removeAt(i);
16382                            } else {
16383                                PackageRemovedInfo childInfo = res.removedInfo
16384                                        .removedChildPackages.valueAt(i);
16385                                childInfo.removedForAllUsers = mPackages.get(
16386                                        childInfo.removedPackage) == null;
16387                            }
16388                        }
16389                    }
16390                }
16391            }
16392        }
16393    }
16394
16395    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16396            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16397            final @ScanFlags int scanFlags, UserHandle user,
16398            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16399            int installReason) {
16400        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16401                + ", old=" + deletedPackage);
16402
16403        final boolean disabledSystem;
16404
16405        // Remove existing system package
16406        removePackageLI(deletedPackage, true);
16407
16408        synchronized (mPackages) {
16409            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16410        }
16411        if (!disabledSystem) {
16412            // We didn't need to disable the .apk as a current system package,
16413            // which means we are replacing another update that is already
16414            // installed.  We need to make sure to delete the older one's .apk.
16415            res.removedInfo.args = createInstallArgsForExisting(0,
16416                    deletedPackage.applicationInfo.getCodePath(),
16417                    deletedPackage.applicationInfo.getResourcePath(),
16418                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16419        } else {
16420            res.removedInfo.args = null;
16421        }
16422
16423        // Successfully disabled the old package. Now proceed with re-installation
16424        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16425                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16426
16427        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16428        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16429                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16430
16431        PackageParser.Package newPackage = null;
16432        try {
16433            // Add the package to the internal data structures
16434            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16435
16436            // Set the update and install times
16437            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16438            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16439                    System.currentTimeMillis());
16440
16441            // Update the package dynamic state if succeeded
16442            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16443                // Now that the install succeeded make sure we remove data
16444                // directories for any child package the update removed.
16445                final int deletedChildCount = (deletedPackage.childPackages != null)
16446                        ? deletedPackage.childPackages.size() : 0;
16447                final int newChildCount = (newPackage.childPackages != null)
16448                        ? newPackage.childPackages.size() : 0;
16449                for (int i = 0; i < deletedChildCount; i++) {
16450                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16451                    boolean childPackageDeleted = true;
16452                    for (int j = 0; j < newChildCount; j++) {
16453                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16454                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16455                            childPackageDeleted = false;
16456                            break;
16457                        }
16458                    }
16459                    if (childPackageDeleted) {
16460                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16461                                deletedChildPkg.packageName);
16462                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16463                            PackageRemovedInfo removedChildRes = res.removedInfo
16464                                    .removedChildPackages.get(deletedChildPkg.packageName);
16465                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16466                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16467                        }
16468                    }
16469                }
16470
16471                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16472                        installReason);
16473                prepareAppDataAfterInstallLIF(newPackage);
16474
16475                mDexManager.notifyPackageUpdated(newPackage.packageName,
16476                            newPackage.baseCodePath, newPackage.splitCodePaths);
16477            }
16478        } catch (PackageManagerException e) {
16479            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16480            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16481        }
16482
16483        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16484            // Re installation failed. Restore old information
16485            // Remove new pkg information
16486            if (newPackage != null) {
16487                removeInstalledPackageLI(newPackage, true);
16488            }
16489            // Add back the old system package
16490            try {
16491                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16492            } catch (PackageManagerException e) {
16493                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16494            }
16495
16496            synchronized (mPackages) {
16497                if (disabledSystem) {
16498                    enableSystemPackageLPw(deletedPackage);
16499                }
16500
16501                // Ensure the installer package name up to date
16502                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16503
16504                // Update permissions for restored package
16505                mPermissionManager.updatePermissions(
16506                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16507                        mPermissionCallback);
16508
16509                mSettings.writeLPr();
16510            }
16511
16512            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16513                    + " after failed upgrade");
16514        }
16515    }
16516
16517    /**
16518     * Checks whether the parent or any of the child packages have a change shared
16519     * user. For a package to be a valid update the shred users of the parent and
16520     * the children should match. We may later support changing child shared users.
16521     * @param oldPkg The updated package.
16522     * @param newPkg The update package.
16523     * @return The shared user that change between the versions.
16524     */
16525    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16526            PackageParser.Package newPkg) {
16527        // Check parent shared user
16528        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16529            return newPkg.packageName;
16530        }
16531        // Check child shared users
16532        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16533        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16534        for (int i = 0; i < newChildCount; i++) {
16535            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16536            // If this child was present, did it have the same shared user?
16537            for (int j = 0; j < oldChildCount; j++) {
16538                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16539                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16540                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16541                    return newChildPkg.packageName;
16542                }
16543            }
16544        }
16545        return null;
16546    }
16547
16548    private void removeNativeBinariesLI(PackageSetting ps) {
16549        // Remove the lib path for the parent package
16550        if (ps != null) {
16551            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16552            // Remove the lib path for the child packages
16553            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16554            for (int i = 0; i < childCount; i++) {
16555                PackageSetting childPs = null;
16556                synchronized (mPackages) {
16557                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16558                }
16559                if (childPs != null) {
16560                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16561                            .legacyNativeLibraryPathString);
16562                }
16563            }
16564        }
16565    }
16566
16567    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16568        // Enable the parent package
16569        mSettings.enableSystemPackageLPw(pkg.packageName);
16570        // Enable the child packages
16571        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16572        for (int i = 0; i < childCount; i++) {
16573            PackageParser.Package childPkg = pkg.childPackages.get(i);
16574            mSettings.enableSystemPackageLPw(childPkg.packageName);
16575        }
16576    }
16577
16578    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16579            PackageParser.Package newPkg) {
16580        // Disable the parent package (parent always replaced)
16581        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16582        // Disable the child packages
16583        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16584        for (int i = 0; i < childCount; i++) {
16585            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16586            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16587            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16588        }
16589        return disabled;
16590    }
16591
16592    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16593            String installerPackageName) {
16594        // Enable the parent package
16595        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16596        // Enable the child packages
16597        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16598        for (int i = 0; i < childCount; i++) {
16599            PackageParser.Package childPkg = pkg.childPackages.get(i);
16600            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16601        }
16602    }
16603
16604    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16605            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16606        // Update the parent package setting
16607        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16608                res, user, installReason);
16609        // Update the child packages setting
16610        final int childCount = (newPackage.childPackages != null)
16611                ? newPackage.childPackages.size() : 0;
16612        for (int i = 0; i < childCount; i++) {
16613            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16614            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16615            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16616                    childRes.origUsers, childRes, user, installReason);
16617        }
16618    }
16619
16620    private void updateSettingsInternalLI(PackageParser.Package pkg,
16621            String installerPackageName, int[] allUsers, int[] installedForUsers,
16622            PackageInstalledInfo res, UserHandle user, int installReason) {
16623        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16624
16625        final String pkgName = pkg.packageName;
16626
16627        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16628        synchronized (mPackages) {
16629// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16630            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16631                    mPermissionCallback);
16632            // For system-bundled packages, we assume that installing an upgraded version
16633            // of the package implies that the user actually wants to run that new code,
16634            // so we enable the package.
16635            PackageSetting ps = mSettings.mPackages.get(pkgName);
16636            final int userId = user.getIdentifier();
16637            if (ps != null) {
16638                if (isSystemApp(pkg)) {
16639                    if (DEBUG_INSTALL) {
16640                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16641                    }
16642                    // Enable system package for requested users
16643                    if (res.origUsers != null) {
16644                        for (int origUserId : res.origUsers) {
16645                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16646                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16647                                        origUserId, installerPackageName);
16648                            }
16649                        }
16650                    }
16651                    // Also convey the prior install/uninstall state
16652                    if (allUsers != null && installedForUsers != null) {
16653                        for (int currentUserId : allUsers) {
16654                            final boolean installed = ArrayUtils.contains(
16655                                    installedForUsers, currentUserId);
16656                            if (DEBUG_INSTALL) {
16657                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16658                            }
16659                            ps.setInstalled(installed, currentUserId);
16660                        }
16661                        // these install state changes will be persisted in the
16662                        // upcoming call to mSettings.writeLPr().
16663                    }
16664                }
16665                // It's implied that when a user requests installation, they want the app to be
16666                // installed and enabled.
16667                if (userId != UserHandle.USER_ALL) {
16668                    ps.setInstalled(true, userId);
16669                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16670                } else {
16671                    for (int currentUserId : sUserManager.getUserIds()) {
16672                        ps.setInstalled(true, currentUserId);
16673                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16674                                installerPackageName);
16675                    }
16676                }
16677
16678                // When replacing an existing package, preserve the original install reason for all
16679                // users that had the package installed before.
16680                final Set<Integer> previousUserIds = new ArraySet<>();
16681                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16682                    final int installReasonCount = res.removedInfo.installReasons.size();
16683                    for (int i = 0; i < installReasonCount; i++) {
16684                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16685                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16686                        ps.setInstallReason(previousInstallReason, previousUserId);
16687                        previousUserIds.add(previousUserId);
16688                    }
16689                }
16690
16691                // Set install reason for users that are having the package newly installed.
16692                if (userId == UserHandle.USER_ALL) {
16693                    for (int currentUserId : sUserManager.getUserIds()) {
16694                        if (!previousUserIds.contains(currentUserId)) {
16695                            ps.setInstallReason(installReason, currentUserId);
16696                        }
16697                    }
16698                } else if (!previousUserIds.contains(userId)) {
16699                    ps.setInstallReason(installReason, userId);
16700                }
16701                mSettings.writeKernelMappingLPr(ps);
16702            }
16703            res.name = pkgName;
16704            res.uid = pkg.applicationInfo.uid;
16705            res.pkg = pkg;
16706            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16707            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16708            //to update install status
16709            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16710            mSettings.writeLPr();
16711            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16712        }
16713
16714        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16715    }
16716
16717    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16718        try {
16719            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16720            installPackageLI(args, res);
16721        } finally {
16722            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16723        }
16724    }
16725
16726    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16727        final int installFlags = args.installFlags;
16728        final String installerPackageName = args.installerPackageName;
16729        final String volumeUuid = args.volumeUuid;
16730        final File tmpPackageFile = new File(args.getCodePath());
16731        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16732        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16733                || (args.volumeUuid != null));
16734        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16735        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16736        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16737        final boolean virtualPreload =
16738                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16739        boolean replace = false;
16740        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16741        if (args.move != null) {
16742            // moving a complete application; perform an initial scan on the new install location
16743            scanFlags |= SCAN_INITIAL;
16744        }
16745        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16746            scanFlags |= SCAN_DONT_KILL_APP;
16747        }
16748        if (instantApp) {
16749            scanFlags |= SCAN_AS_INSTANT_APP;
16750        }
16751        if (fullApp) {
16752            scanFlags |= SCAN_AS_FULL_APP;
16753        }
16754        if (virtualPreload) {
16755            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16756        }
16757
16758        // Result object to be returned
16759        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16760        res.installerPackageName = installerPackageName;
16761
16762        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16763
16764        // Sanity check
16765        if (instantApp && (forwardLocked || onExternal)) {
16766            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16767                    + " external=" + onExternal);
16768            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16769            return;
16770        }
16771
16772        // Retrieve PackageSettings and parse package
16773        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16774                | PackageParser.PARSE_ENFORCE_CODE
16775                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16776                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16777                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16778        PackageParser pp = new PackageParser();
16779        pp.setSeparateProcesses(mSeparateProcesses);
16780        pp.setDisplayMetrics(mMetrics);
16781        pp.setCallback(mPackageParserCallback);
16782
16783        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16784        final PackageParser.Package pkg;
16785        try {
16786            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16787            DexMetadataHelper.validatePackageDexMetadata(pkg);
16788        } catch (PackageParserException e) {
16789            res.setError("Failed parse during installPackageLI", e);
16790            return;
16791        } finally {
16792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16793        }
16794
16795        // Instant apps have several additional install-time checks.
16796        if (instantApp) {
16797            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16798                Slog.w(TAG,
16799                        "Instant app package " + pkg.packageName + " does not target at least O");
16800                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16801                        "Instant app package must target at least O");
16802                return;
16803            }
16804            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16805                Slog.w(TAG, "Instant app package " + pkg.packageName
16806                        + " does not target targetSandboxVersion 2");
16807                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16808                        "Instant app package must use targetSandboxVersion 2");
16809                return;
16810            }
16811            if (pkg.mSharedUserId != null) {
16812                Slog.w(TAG, "Instant app package " + pkg.packageName
16813                        + " may not declare sharedUserId.");
16814                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16815                        "Instant app package may not declare a sharedUserId");
16816                return;
16817            }
16818        }
16819
16820        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16821            // Static shared libraries have synthetic package names
16822            renameStaticSharedLibraryPackage(pkg);
16823
16824            // No static shared libs on external storage
16825            if (onExternal) {
16826                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16827                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16828                        "Packages declaring static-shared libs cannot be updated");
16829                return;
16830            }
16831        }
16832
16833        // If we are installing a clustered package add results for the children
16834        if (pkg.childPackages != null) {
16835            synchronized (mPackages) {
16836                final int childCount = pkg.childPackages.size();
16837                for (int i = 0; i < childCount; i++) {
16838                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16839                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16840                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16841                    childRes.pkg = childPkg;
16842                    childRes.name = childPkg.packageName;
16843                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16844                    if (childPs != null) {
16845                        childRes.origUsers = childPs.queryInstalledUsers(
16846                                sUserManager.getUserIds(), true);
16847                    }
16848                    if ((mPackages.containsKey(childPkg.packageName))) {
16849                        childRes.removedInfo = new PackageRemovedInfo(this);
16850                        childRes.removedInfo.removedPackage = childPkg.packageName;
16851                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16852                    }
16853                    if (res.addedChildPackages == null) {
16854                        res.addedChildPackages = new ArrayMap<>();
16855                    }
16856                    res.addedChildPackages.put(childPkg.packageName, childRes);
16857                }
16858            }
16859        }
16860
16861        // If package doesn't declare API override, mark that we have an install
16862        // time CPU ABI override.
16863        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16864            pkg.cpuAbiOverride = args.abiOverride;
16865        }
16866
16867        String pkgName = res.name = pkg.packageName;
16868        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16869            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16870                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16871                return;
16872            }
16873        }
16874
16875        try {
16876            // either use what we've been given or parse directly from the APK
16877            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16878                pkg.setSigningDetails(args.signingDetails);
16879            } else {
16880                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16881            }
16882        } catch (PackageParserException e) {
16883            res.setError("Failed collect during installPackageLI", e);
16884            return;
16885        }
16886
16887        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16888                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16889            Slog.w(TAG, "Instant app package " + pkg.packageName
16890                    + " is not signed with at least APK Signature Scheme v2");
16891            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16892                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16893            return;
16894        }
16895
16896        // Get rid of all references to package scan path via parser.
16897        pp = null;
16898        String oldCodePath = null;
16899        boolean systemApp = false;
16900        synchronized (mPackages) {
16901            // Check if installing already existing package
16902            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16903                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16904                if (pkg.mOriginalPackages != null
16905                        && pkg.mOriginalPackages.contains(oldName)
16906                        && mPackages.containsKey(oldName)) {
16907                    // This package is derived from an original package,
16908                    // and this device has been updating from that original
16909                    // name.  We must continue using the original name, so
16910                    // rename the new package here.
16911                    pkg.setPackageName(oldName);
16912                    pkgName = pkg.packageName;
16913                    replace = true;
16914                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16915                            + oldName + " pkgName=" + pkgName);
16916                } else if (mPackages.containsKey(pkgName)) {
16917                    // This package, under its official name, already exists
16918                    // on the device; we should replace it.
16919                    replace = true;
16920                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16921                }
16922
16923                // Child packages are installed through the parent package
16924                if (pkg.parentPackage != null) {
16925                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16926                            "Package " + pkg.packageName + " is child of package "
16927                                    + pkg.parentPackage.parentPackage + ". Child packages "
16928                                    + "can be updated only through the parent package.");
16929                    return;
16930                }
16931
16932                if (replace) {
16933                    // Prevent apps opting out from runtime permissions
16934                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16935                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16936                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16937                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16938                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16939                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16940                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16941                                        + " doesn't support runtime permissions but the old"
16942                                        + " target SDK " + oldTargetSdk + " does.");
16943                        return;
16944                    }
16945                    // Prevent persistent apps from being updated
16946                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
16947                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
16948                                "Package " + oldPackage.packageName + " is a persistent app. "
16949                                        + "Persistent apps are not updateable.");
16950                        return;
16951                    }
16952                    // Prevent apps from downgrading their targetSandbox.
16953                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16954                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16955                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16956                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16957                                "Package " + pkg.packageName + " new target sandbox "
16958                                + newTargetSandbox + " is incompatible with the previous value of"
16959                                + oldTargetSandbox + ".");
16960                        return;
16961                    }
16962
16963                    // Prevent installing of child packages
16964                    if (oldPackage.parentPackage != null) {
16965                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16966                                "Package " + pkg.packageName + " is child of package "
16967                                        + oldPackage.parentPackage + ". Child packages "
16968                                        + "can be updated only through the parent package.");
16969                        return;
16970                    }
16971                }
16972            }
16973
16974            PackageSetting ps = mSettings.mPackages.get(pkgName);
16975            if (ps != null) {
16976                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16977
16978                // Static shared libs have same package with different versions where
16979                // we internally use a synthetic package name to allow multiple versions
16980                // of the same package, therefore we need to compare signatures against
16981                // the package setting for the latest library version.
16982                PackageSetting signatureCheckPs = ps;
16983                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16984                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16985                    if (libraryEntry != null) {
16986                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16987                    }
16988                }
16989
16990                // Quick sanity check that we're signed correctly if updating;
16991                // we'll check this again later when scanning, but we want to
16992                // bail early here before tripping over redefined permissions.
16993                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16994                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16995                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16996                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16997                                + pkg.packageName + " upgrade keys do not match the "
16998                                + "previously installed version");
16999                        return;
17000                    }
17001                } else {
17002                    try {
17003                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17004                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17005                        // We don't care about disabledPkgSetting on install for now.
17006                        final boolean compatMatch = verifySignatures(
17007                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17008                                compareRecover);
17009                        // The new KeySets will be re-added later in the scanning process.
17010                        if (compatMatch) {
17011                            synchronized (mPackages) {
17012                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17013                            }
17014                        }
17015                    } catch (PackageManagerException e) {
17016                        res.setError(e.error, e.getMessage());
17017                        return;
17018                    }
17019                }
17020
17021                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17022                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17023                    systemApp = (ps.pkg.applicationInfo.flags &
17024                            ApplicationInfo.FLAG_SYSTEM) != 0;
17025                }
17026                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17027            }
17028
17029            int N = pkg.permissions.size();
17030            for (int i = N-1; i >= 0; i--) {
17031                final PackageParser.Permission perm = pkg.permissions.get(i);
17032                final BasePermission bp =
17033                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17034
17035                // Don't allow anyone but the system to define ephemeral permissions.
17036                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17037                        && !systemApp) {
17038                    Slog.w(TAG, "Non-System package " + pkg.packageName
17039                            + " attempting to delcare ephemeral permission "
17040                            + perm.info.name + "; Removing ephemeral.");
17041                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17042                }
17043
17044                // Check whether the newly-scanned package wants to define an already-defined perm
17045                if (bp != null) {
17046                    // If the defining package is signed with our cert, it's okay.  This
17047                    // also includes the "updating the same package" case, of course.
17048                    // "updating same package" could also involve key-rotation.
17049                    final boolean sigsOk;
17050                    final String sourcePackageName = bp.getSourcePackageName();
17051                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17052                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17053                    if (sourcePackageName.equals(pkg.packageName)
17054                            && (ksms.shouldCheckUpgradeKeySetLocked(
17055                                    sourcePackageSetting, scanFlags))) {
17056                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17057                    } else {
17058
17059                        // in the event of signing certificate rotation, we need to see if the
17060                        // package's certificate has rotated from the current one, or if it is an
17061                        // older certificate with which the current is ok with sharing permissions
17062                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17063                                        pkg.mSigningDetails,
17064                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17065                            sigsOk = true;
17066                        } else if (pkg.mSigningDetails.checkCapability(
17067                                        sourcePackageSetting.signatures.mSigningDetails,
17068                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17069
17070                            // the scanned package checks out, has signing certificate rotation
17071                            // history, and is newer; bring it over
17072                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17073                            sigsOk = true;
17074                        } else {
17075                            sigsOk = false;
17076                        }
17077                    }
17078                    if (!sigsOk) {
17079                        // If the owning package is the system itself, we log but allow
17080                        // install to proceed; we fail the install on all other permission
17081                        // redefinitions.
17082                        if (!sourcePackageName.equals("android")) {
17083                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17084                                    + pkg.packageName + " attempting to redeclare permission "
17085                                    + perm.info.name + " already owned by " + sourcePackageName);
17086                            res.origPermission = perm.info.name;
17087                            res.origPackage = sourcePackageName;
17088                            return;
17089                        } else {
17090                            Slog.w(TAG, "Package " + pkg.packageName
17091                                    + " attempting to redeclare system permission "
17092                                    + perm.info.name + "; ignoring new declaration");
17093                            pkg.permissions.remove(i);
17094                        }
17095                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17096                        // Prevent apps to change protection level to dangerous from any other
17097                        // type as this would allow a privilege escalation where an app adds a
17098                        // normal/signature permission in other app's group and later redefines
17099                        // it as dangerous leading to the group auto-grant.
17100                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17101                                == PermissionInfo.PROTECTION_DANGEROUS) {
17102                            if (bp != null && !bp.isRuntime()) {
17103                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17104                                        + "non-runtime permission " + perm.info.name
17105                                        + " to runtime; keeping old protection level");
17106                                perm.info.protectionLevel = bp.getProtectionLevel();
17107                            }
17108                        }
17109                    }
17110                }
17111            }
17112        }
17113
17114        if (systemApp) {
17115            if (onExternal) {
17116                // Abort update; system app can't be replaced with app on sdcard
17117                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17118                        "Cannot install updates to system apps on sdcard");
17119                return;
17120            } else if (instantApp) {
17121                // Abort update; system app can't be replaced with an instant app
17122                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17123                        "Cannot update a system app with an instant app");
17124                return;
17125            }
17126        }
17127
17128        if (args.move != null) {
17129            // We did an in-place move, so dex is ready to roll
17130            scanFlags |= SCAN_NO_DEX;
17131            scanFlags |= SCAN_MOVE;
17132
17133            synchronized (mPackages) {
17134                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17135                if (ps == null) {
17136                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17137                            "Missing settings for moved package " + pkgName);
17138                }
17139
17140                // We moved the entire application as-is, so bring over the
17141                // previously derived ABI information.
17142                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17143                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17144            }
17145
17146        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17147            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17148            scanFlags |= SCAN_NO_DEX;
17149
17150            try {
17151                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17152                    args.abiOverride : pkg.cpuAbiOverride);
17153                final boolean extractNativeLibs = !pkg.isLibrary();
17154                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17155            } catch (PackageManagerException pme) {
17156                Slog.e(TAG, "Error deriving application ABI", pme);
17157                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17158                return;
17159            }
17160
17161            // Shared libraries for the package need to be updated.
17162            synchronized (mPackages) {
17163                try {
17164                    updateSharedLibrariesLPr(pkg, null);
17165                } catch (PackageManagerException e) {
17166                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17167                }
17168            }
17169        }
17170
17171        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17172            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17173            return;
17174        }
17175
17176        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17177            String apkPath = null;
17178            synchronized (mPackages) {
17179                // Note that if the attacker managed to skip verify setup, for example by tampering
17180                // with the package settings, upon reboot we will do full apk verification when
17181                // verity is not detected.
17182                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17183                if (ps != null && ps.isPrivileged()) {
17184                    apkPath = pkg.baseCodePath;
17185                }
17186            }
17187
17188            if (apkPath != null) {
17189                final VerityUtils.SetupResult result =
17190                        VerityUtils.generateApkVeritySetupData(apkPath);
17191                if (result.isOk()) {
17192                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17193                    FileDescriptor fd = result.getUnownedFileDescriptor();
17194                    try {
17195                        mInstaller.installApkVerity(apkPath, fd);
17196                    } catch (InstallerException e) {
17197                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17198                                "Failed to set up verity: " + e);
17199                        return;
17200                    } finally {
17201                        IoUtils.closeQuietly(fd);
17202                    }
17203                } else if (result.isFailed()) {
17204                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17205                    return;
17206                } else {
17207                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17208                    // reboot.
17209                }
17210            }
17211        }
17212
17213        if (!instantApp) {
17214            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17215        } else {
17216            if (DEBUG_DOMAIN_VERIFICATION) {
17217                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17218            }
17219        }
17220
17221        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17222                "installPackageLI")) {
17223            if (replace) {
17224                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17225                    // Static libs have a synthetic package name containing the version
17226                    // and cannot be updated as an update would get a new package name,
17227                    // unless this is the exact same version code which is useful for
17228                    // development.
17229                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17230                    if (existingPkg != null &&
17231                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17232                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17233                                + "static-shared libs cannot be updated");
17234                        return;
17235                    }
17236                }
17237                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17238                        installerPackageName, res, args.installReason);
17239            } else {
17240                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17241                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17242            }
17243        }
17244
17245        // Prepare the application profiles for the new code paths.
17246        // This needs to be done before invoking dexopt so that any install-time profile
17247        // can be used for optimizations.
17248        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17249
17250        // Check whether we need to dexopt the app.
17251        //
17252        // NOTE: it is IMPORTANT to call dexopt:
17253        //   - after doRename which will sync the package data from PackageParser.Package and its
17254        //     corresponding ApplicationInfo.
17255        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17256        //     uid of the application (pkg.applicationInfo.uid).
17257        //     This update happens in place!
17258        //
17259        // We only need to dexopt if the package meets ALL of the following conditions:
17260        //   1) it is not forward locked.
17261        //   2) it is not on on an external ASEC container.
17262        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17263        //
17264        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17265        // complete, so we skip this step during installation. Instead, we'll take extra time
17266        // the first time the instant app starts. It's preferred to do it this way to provide
17267        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17268        // middle of running an instant app. The default behaviour can be overridden
17269        // via gservices.
17270        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17271                && !forwardLocked
17272                && !pkg.applicationInfo.isExternalAsec()
17273                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17274                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17275
17276        if (performDexopt) {
17277            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17278            // Do not run PackageDexOptimizer through the local performDexOpt
17279            // method because `pkg` may not be in `mPackages` yet.
17280            //
17281            // Also, don't fail application installs if the dexopt step fails.
17282            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17283                    REASON_INSTALL,
17284                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17285                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17286            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17287                    null /* instructionSets */,
17288                    getOrCreateCompilerPackageStats(pkg),
17289                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17290                    dexoptOptions);
17291            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17292        }
17293
17294        // Notify BackgroundDexOptService that the package has been changed.
17295        // If this is an update of a package which used to fail to compile,
17296        // BackgroundDexOptService will remove it from its blacklist.
17297        // TODO: Layering violation
17298        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17299
17300        synchronized (mPackages) {
17301            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17302            if (ps != null) {
17303                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17304                ps.setUpdateAvailable(false /*updateAvailable*/);
17305            }
17306
17307            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17308            for (int i = 0; i < childCount; i++) {
17309                PackageParser.Package childPkg = pkg.childPackages.get(i);
17310                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17311                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17312                if (childPs != null) {
17313                    childRes.newUsers = childPs.queryInstalledUsers(
17314                            sUserManager.getUserIds(), true);
17315                }
17316            }
17317
17318            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17319                updateSequenceNumberLP(ps, res.newUsers);
17320                updateInstantAppInstallerLocked(pkgName);
17321            }
17322        }
17323    }
17324
17325    private void startIntentFilterVerifications(int userId, boolean replacing,
17326            PackageParser.Package pkg) {
17327        if (mIntentFilterVerifierComponent == null) {
17328            Slog.w(TAG, "No IntentFilter verification will not be done as "
17329                    + "there is no IntentFilterVerifier available!");
17330            return;
17331        }
17332
17333        final int verifierUid = getPackageUid(
17334                mIntentFilterVerifierComponent.getPackageName(),
17335                MATCH_DEBUG_TRIAGED_MISSING,
17336                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17337
17338        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17339        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17340        mHandler.sendMessage(msg);
17341
17342        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17343        for (int i = 0; i < childCount; i++) {
17344            PackageParser.Package childPkg = pkg.childPackages.get(i);
17345            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17346            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17347            mHandler.sendMessage(msg);
17348        }
17349    }
17350
17351    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17352            PackageParser.Package pkg) {
17353        int size = pkg.activities.size();
17354        if (size == 0) {
17355            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17356                    "No activity, so no need to verify any IntentFilter!");
17357            return;
17358        }
17359
17360        final boolean hasDomainURLs = hasDomainURLs(pkg);
17361        if (!hasDomainURLs) {
17362            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17363                    "No domain URLs, so no need to verify any IntentFilter!");
17364            return;
17365        }
17366
17367        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17368                + " if any IntentFilter from the " + size
17369                + " Activities needs verification ...");
17370
17371        int count = 0;
17372        final String packageName = pkg.packageName;
17373
17374        synchronized (mPackages) {
17375            // If this is a new install and we see that we've already run verification for this
17376            // package, we have nothing to do: it means the state was restored from backup.
17377            if (!replacing) {
17378                IntentFilterVerificationInfo ivi =
17379                        mSettings.getIntentFilterVerificationLPr(packageName);
17380                if (ivi != null) {
17381                    if (DEBUG_DOMAIN_VERIFICATION) {
17382                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17383                                + ivi.getStatusString());
17384                    }
17385                    return;
17386                }
17387            }
17388
17389            // If any filters need to be verified, then all need to be.
17390            boolean needToVerify = false;
17391            for (PackageParser.Activity a : pkg.activities) {
17392                for (ActivityIntentInfo filter : a.intents) {
17393                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17394                        if (DEBUG_DOMAIN_VERIFICATION) {
17395                            Slog.d(TAG,
17396                                    "Intent filter needs verification, so processing all filters");
17397                        }
17398                        needToVerify = true;
17399                        break;
17400                    }
17401                }
17402            }
17403
17404            if (needToVerify) {
17405                final int verificationId = mIntentFilterVerificationToken++;
17406                for (PackageParser.Activity a : pkg.activities) {
17407                    for (ActivityIntentInfo filter : a.intents) {
17408                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17409                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17410                                    "Verification needed for IntentFilter:" + filter.toString());
17411                            mIntentFilterVerifier.addOneIntentFilterVerification(
17412                                    verifierUid, userId, verificationId, filter, packageName);
17413                            count++;
17414                        }
17415                    }
17416                }
17417            }
17418        }
17419
17420        if (count > 0) {
17421            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17422                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17423                    +  " for userId:" + userId);
17424            mIntentFilterVerifier.startVerifications(userId);
17425        } else {
17426            if (DEBUG_DOMAIN_VERIFICATION) {
17427                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17428            }
17429        }
17430    }
17431
17432    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17433        final ComponentName cn  = filter.activity.getComponentName();
17434        final String packageName = cn.getPackageName();
17435
17436        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17437                packageName);
17438        if (ivi == null) {
17439            return true;
17440        }
17441        int status = ivi.getStatus();
17442        switch (status) {
17443            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17444            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17445                return true;
17446
17447            default:
17448                // Nothing to do
17449                return false;
17450        }
17451    }
17452
17453    private static boolean isMultiArch(ApplicationInfo info) {
17454        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17455    }
17456
17457    private static boolean isExternal(PackageParser.Package pkg) {
17458        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17459    }
17460
17461    private static boolean isExternal(PackageSetting ps) {
17462        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17463    }
17464
17465    private static boolean isSystemApp(PackageParser.Package pkg) {
17466        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17467    }
17468
17469    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17470        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17471    }
17472
17473    private static boolean isOemApp(PackageParser.Package pkg) {
17474        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17475    }
17476
17477    private static boolean isVendorApp(PackageParser.Package pkg) {
17478        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17479    }
17480
17481    private static boolean isProductApp(PackageParser.Package pkg) {
17482        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17483    }
17484
17485    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17486        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17487    }
17488
17489    private static boolean isSystemApp(PackageSetting ps) {
17490        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17491    }
17492
17493    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17494        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17495    }
17496
17497    private int packageFlagsToInstallFlags(PackageSetting ps) {
17498        int installFlags = 0;
17499        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17500            // This existing package was an external ASEC install when we have
17501            // the external flag without a UUID
17502            installFlags |= PackageManager.INSTALL_EXTERNAL;
17503        }
17504        if (ps.isForwardLocked()) {
17505            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17506        }
17507        return installFlags;
17508    }
17509
17510    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17511        if (isExternal(pkg)) {
17512            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17513                return mSettings.getExternalVersion();
17514            } else {
17515                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17516            }
17517        } else {
17518            return mSettings.getInternalVersion();
17519        }
17520    }
17521
17522    private void deleteTempPackageFiles() {
17523        final FilenameFilter filter = new FilenameFilter() {
17524            public boolean accept(File dir, String name) {
17525                return name.startsWith("vmdl") && name.endsWith(".tmp");
17526            }
17527        };
17528        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17529            file.delete();
17530        }
17531    }
17532
17533    @Override
17534    public void deletePackageAsUser(String packageName, int versionCode,
17535            IPackageDeleteObserver observer, int userId, int flags) {
17536        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17537                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17538    }
17539
17540    @Override
17541    public void deletePackageVersioned(VersionedPackage versionedPackage,
17542            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17543        final int callingUid = Binder.getCallingUid();
17544        mContext.enforceCallingOrSelfPermission(
17545                android.Manifest.permission.DELETE_PACKAGES, null);
17546        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17547        Preconditions.checkNotNull(versionedPackage);
17548        Preconditions.checkNotNull(observer);
17549        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17550                PackageManager.VERSION_CODE_HIGHEST,
17551                Long.MAX_VALUE, "versionCode must be >= -1");
17552
17553        final String packageName = versionedPackage.getPackageName();
17554        final long versionCode = versionedPackage.getLongVersionCode();
17555        final String internalPackageName;
17556        synchronized (mPackages) {
17557            // Normalize package name to handle renamed packages and static libs
17558            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17559        }
17560
17561        final int uid = Binder.getCallingUid();
17562        if (!isOrphaned(internalPackageName)
17563                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17564            try {
17565                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17566                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17567                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17568                observer.onUserActionRequired(intent);
17569            } catch (RemoteException re) {
17570            }
17571            return;
17572        }
17573        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17574        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17575        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17576            mContext.enforceCallingOrSelfPermission(
17577                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17578                    "deletePackage for user " + userId);
17579        }
17580
17581        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17582            try {
17583                observer.onPackageDeleted(packageName,
17584                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17585            } catch (RemoteException re) {
17586            }
17587            return;
17588        }
17589
17590        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17591            try {
17592                observer.onPackageDeleted(packageName,
17593                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17594            } catch (RemoteException re) {
17595            }
17596            return;
17597        }
17598
17599        if (DEBUG_REMOVE) {
17600            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17601                    + " deleteAllUsers: " + deleteAllUsers + " version="
17602                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17603                    ? "VERSION_CODE_HIGHEST" : versionCode));
17604        }
17605        // Queue up an async operation since the package deletion may take a little while.
17606        mHandler.post(new Runnable() {
17607            public void run() {
17608                mHandler.removeCallbacks(this);
17609                int returnCode;
17610                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17611                boolean doDeletePackage = true;
17612                if (ps != null) {
17613                    final boolean targetIsInstantApp =
17614                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17615                    doDeletePackage = !targetIsInstantApp
17616                            || canViewInstantApps;
17617                }
17618                if (doDeletePackage) {
17619                    if (!deleteAllUsers) {
17620                        returnCode = deletePackageX(internalPackageName, versionCode,
17621                                userId, deleteFlags);
17622                    } else {
17623                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17624                                internalPackageName, users);
17625                        // If nobody is blocking uninstall, proceed with delete for all users
17626                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17627                            returnCode = deletePackageX(internalPackageName, versionCode,
17628                                    userId, deleteFlags);
17629                        } else {
17630                            // Otherwise uninstall individually for users with blockUninstalls=false
17631                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17632                            for (int userId : users) {
17633                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17634                                    returnCode = deletePackageX(internalPackageName, versionCode,
17635                                            userId, userFlags);
17636                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17637                                        Slog.w(TAG, "Package delete failed for user " + userId
17638                                                + ", returnCode " + returnCode);
17639                                    }
17640                                }
17641                            }
17642                            // The app has only been marked uninstalled for certain users.
17643                            // We still need to report that delete was blocked
17644                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17645                        }
17646                    }
17647                } else {
17648                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17649                }
17650                try {
17651                    observer.onPackageDeleted(packageName, returnCode, null);
17652                } catch (RemoteException e) {
17653                    Log.i(TAG, "Observer no longer exists.");
17654                } //end catch
17655            } //end run
17656        });
17657    }
17658
17659    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17660        if (pkg.staticSharedLibName != null) {
17661            return pkg.manifestPackageName;
17662        }
17663        return pkg.packageName;
17664    }
17665
17666    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17667        // Handle renamed packages
17668        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17669        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17670
17671        // Is this a static library?
17672        LongSparseArray<SharedLibraryEntry> versionedLib =
17673                mStaticLibsByDeclaringPackage.get(packageName);
17674        if (versionedLib == null || versionedLib.size() <= 0) {
17675            return packageName;
17676        }
17677
17678        // Figure out which lib versions the caller can see
17679        LongSparseLongArray versionsCallerCanSee = null;
17680        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17681        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17682                && callingAppId != Process.ROOT_UID) {
17683            versionsCallerCanSee = new LongSparseLongArray();
17684            String libName = versionedLib.valueAt(0).info.getName();
17685            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17686            if (uidPackages != null) {
17687                for (String uidPackage : uidPackages) {
17688                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17689                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17690                    if (libIdx >= 0) {
17691                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17692                        versionsCallerCanSee.append(libVersion, libVersion);
17693                    }
17694                }
17695            }
17696        }
17697
17698        // Caller can see nothing - done
17699        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17700            return packageName;
17701        }
17702
17703        // Find the version the caller can see and the app version code
17704        SharedLibraryEntry highestVersion = null;
17705        final int versionCount = versionedLib.size();
17706        for (int i = 0; i < versionCount; i++) {
17707            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17708            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17709                    libEntry.info.getLongVersion()) < 0) {
17710                continue;
17711            }
17712            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17713            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17714                if (libVersionCode == versionCode) {
17715                    return libEntry.apk;
17716                }
17717            } else if (highestVersion == null) {
17718                highestVersion = libEntry;
17719            } else if (libVersionCode  > highestVersion.info
17720                    .getDeclaringPackage().getLongVersionCode()) {
17721                highestVersion = libEntry;
17722            }
17723        }
17724
17725        if (highestVersion != null) {
17726            return highestVersion.apk;
17727        }
17728
17729        return packageName;
17730    }
17731
17732    boolean isCallerVerifier(int callingUid) {
17733        final int callingUserId = UserHandle.getUserId(callingUid);
17734        return mRequiredVerifierPackage != null &&
17735                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17736    }
17737
17738    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17739        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17740              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17741            return true;
17742        }
17743        final int callingUserId = UserHandle.getUserId(callingUid);
17744        // If the caller installed the pkgName, then allow it to silently uninstall.
17745        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17746            return true;
17747        }
17748
17749        // Allow package verifier to silently uninstall.
17750        if (mRequiredVerifierPackage != null &&
17751                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17752            return true;
17753        }
17754
17755        // Allow package uninstaller to silently uninstall.
17756        if (mRequiredUninstallerPackage != null &&
17757                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17758            return true;
17759        }
17760
17761        // Allow storage manager to silently uninstall.
17762        if (mStorageManagerPackage != null &&
17763                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17764            return true;
17765        }
17766
17767        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17768        // uninstall for device owner provisioning.
17769        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17770                == PERMISSION_GRANTED) {
17771            return true;
17772        }
17773
17774        return false;
17775    }
17776
17777    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17778        int[] result = EMPTY_INT_ARRAY;
17779        for (int userId : userIds) {
17780            if (getBlockUninstallForUser(packageName, userId)) {
17781                result = ArrayUtils.appendInt(result, userId);
17782            }
17783        }
17784        return result;
17785    }
17786
17787    @Override
17788    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17789        final int callingUid = Binder.getCallingUid();
17790        if (getInstantAppPackageName(callingUid) != null
17791                && !isCallerSameApp(packageName, callingUid)) {
17792            return false;
17793        }
17794        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17795    }
17796
17797    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17798        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17799                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17800        try {
17801            if (dpm != null) {
17802                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17803                        /* callingUserOnly =*/ false);
17804                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17805                        : deviceOwnerComponentName.getPackageName();
17806                // Does the package contains the device owner?
17807                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17808                // this check is probably not needed, since DO should be registered as a device
17809                // admin on some user too. (Original bug for this: b/17657954)
17810                if (packageName.equals(deviceOwnerPackageName)) {
17811                    return true;
17812                }
17813                // Does it contain a device admin for any user?
17814                int[] users;
17815                if (userId == UserHandle.USER_ALL) {
17816                    users = sUserManager.getUserIds();
17817                } else {
17818                    users = new int[]{userId};
17819                }
17820                for (int i = 0; i < users.length; ++i) {
17821                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17822                        return true;
17823                    }
17824                }
17825            }
17826        } catch (RemoteException e) {
17827        }
17828        return false;
17829    }
17830
17831    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17832        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17833    }
17834
17835    /**
17836     *  This method is an internal method that could be get invoked either
17837     *  to delete an installed package or to clean up a failed installation.
17838     *  After deleting an installed package, a broadcast is sent to notify any
17839     *  listeners that the package has been removed. For cleaning up a failed
17840     *  installation, the broadcast is not necessary since the package's
17841     *  installation wouldn't have sent the initial broadcast either
17842     *  The key steps in deleting a package are
17843     *  deleting the package information in internal structures like mPackages,
17844     *  deleting the packages base directories through installd
17845     *  updating mSettings to reflect current status
17846     *  persisting settings for later use
17847     *  sending a broadcast if necessary
17848     */
17849    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17850        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17851        final boolean res;
17852
17853        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17854                ? UserHandle.USER_ALL : userId;
17855
17856        if (isPackageDeviceAdmin(packageName, removeUser)) {
17857            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17858            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17859        }
17860
17861        PackageSetting uninstalledPs = null;
17862        PackageParser.Package pkg = null;
17863
17864        // for the uninstall-updates case and restricted profiles, remember the per-
17865        // user handle installed state
17866        int[] allUsers;
17867        synchronized (mPackages) {
17868            uninstalledPs = mSettings.mPackages.get(packageName);
17869            if (uninstalledPs == null) {
17870                Slog.w(TAG, "Not removing non-existent package " + packageName);
17871                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17872            }
17873
17874            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17875                    && uninstalledPs.versionCode != versionCode) {
17876                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17877                        + uninstalledPs.versionCode + " != " + versionCode);
17878                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17879            }
17880
17881            // Static shared libs can be declared by any package, so let us not
17882            // allow removing a package if it provides a lib others depend on.
17883            pkg = mPackages.get(packageName);
17884
17885            allUsers = sUserManager.getUserIds();
17886
17887            if (pkg != null && pkg.staticSharedLibName != null) {
17888                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17889                        pkg.staticSharedLibVersion);
17890                if (libEntry != null) {
17891                    for (int currUserId : allUsers) {
17892                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17893                            continue;
17894                        }
17895                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17896                                libEntry.info, 0, currUserId);
17897                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17898                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17899                                    + " hosting lib " + libEntry.info.getName() + " version "
17900                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17901                                    + " for user " + currUserId);
17902                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17903                        }
17904                    }
17905                }
17906            }
17907
17908            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17909        }
17910
17911        final int freezeUser;
17912        if (isUpdatedSystemApp(uninstalledPs)
17913                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17914            // We're downgrading a system app, which will apply to all users, so
17915            // freeze them all during the downgrade
17916            freezeUser = UserHandle.USER_ALL;
17917        } else {
17918            freezeUser = removeUser;
17919        }
17920
17921        synchronized (mInstallLock) {
17922            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17923            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17924                    deleteFlags, "deletePackageX")) {
17925                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17926                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17927            }
17928            synchronized (mPackages) {
17929                if (res) {
17930                    if (pkg != null) {
17931                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17932                    }
17933                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17934                    updateInstantAppInstallerLocked(packageName);
17935                }
17936            }
17937        }
17938
17939        if (res) {
17940            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17941            info.sendPackageRemovedBroadcasts(killApp);
17942            info.sendSystemPackageUpdatedBroadcasts();
17943            info.sendSystemPackageAppearedBroadcasts();
17944        }
17945        // Force a gc here.
17946        Runtime.getRuntime().gc();
17947        // Delete the resources here after sending the broadcast to let
17948        // other processes clean up before deleting resources.
17949        if (info.args != null) {
17950            synchronized (mInstallLock) {
17951                info.args.doPostDeleteLI(true);
17952            }
17953        }
17954
17955        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17956    }
17957
17958    static class PackageRemovedInfo {
17959        final PackageSender packageSender;
17960        String removedPackage;
17961        String installerPackageName;
17962        int uid = -1;
17963        int removedAppId = -1;
17964        int[] origUsers;
17965        int[] removedUsers = null;
17966        int[] broadcastUsers = null;
17967        int[] instantUserIds = null;
17968        SparseArray<Integer> installReasons;
17969        boolean isRemovedPackageSystemUpdate = false;
17970        boolean isUpdate;
17971        boolean dataRemoved;
17972        boolean removedForAllUsers;
17973        boolean isStaticSharedLib;
17974        // Clean up resources deleted packages.
17975        InstallArgs args = null;
17976        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17977        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17978
17979        PackageRemovedInfo(PackageSender packageSender) {
17980            this.packageSender = packageSender;
17981        }
17982
17983        void sendPackageRemovedBroadcasts(boolean killApp) {
17984            sendPackageRemovedBroadcastInternal(killApp);
17985            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17986            for (int i = 0; i < childCount; i++) {
17987                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17988                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17989            }
17990        }
17991
17992        void sendSystemPackageUpdatedBroadcasts() {
17993            if (isRemovedPackageSystemUpdate) {
17994                sendSystemPackageUpdatedBroadcastsInternal();
17995                final int childCount = (removedChildPackages != null)
17996                        ? removedChildPackages.size() : 0;
17997                for (int i = 0; i < childCount; i++) {
17998                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17999                    if (childInfo.isRemovedPackageSystemUpdate) {
18000                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18001                    }
18002                }
18003            }
18004        }
18005
18006        void sendSystemPackageAppearedBroadcasts() {
18007            final int packageCount = (appearedChildPackages != null)
18008                    ? appearedChildPackages.size() : 0;
18009            for (int i = 0; i < packageCount; i++) {
18010                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18011                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18012                    true /*sendBootCompleted*/, false /*startReceiver*/,
18013                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18014            }
18015        }
18016
18017        private void sendSystemPackageUpdatedBroadcastsInternal() {
18018            Bundle extras = new Bundle(2);
18019            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18020            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18021            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18022                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18023            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18024                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18025            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18026                null, null, 0, removedPackage, null, null, null);
18027            if (installerPackageName != null) {
18028                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18029                        removedPackage, extras, 0 /*flags*/,
18030                        installerPackageName, null, null, null);
18031                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18032                        removedPackage, extras, 0 /*flags*/,
18033                        installerPackageName, null, null, null);
18034            }
18035        }
18036
18037        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18038            // Don't send static shared library removal broadcasts as these
18039            // libs are visible only the the apps that depend on them an one
18040            // cannot remove the library if it has a dependency.
18041            if (isStaticSharedLib) {
18042                return;
18043            }
18044            Bundle extras = new Bundle(2);
18045            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18046            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18047            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18048            if (isUpdate || isRemovedPackageSystemUpdate) {
18049                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18050            }
18051            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18052            if (removedPackage != null) {
18053                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18054                    removedPackage, extras, 0, null /*targetPackage*/, null,
18055                    broadcastUsers, instantUserIds);
18056                if (installerPackageName != null) {
18057                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18058                            removedPackage, extras, 0 /*flags*/,
18059                            installerPackageName, null, broadcastUsers, instantUserIds);
18060                }
18061                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18062                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18063                        removedPackage, extras,
18064                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18065                        null, null, broadcastUsers, instantUserIds);
18066                    packageSender.notifyPackageRemoved(removedPackage);
18067                }
18068            }
18069            if (removedAppId >= 0) {
18070                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18071                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18072                    null, null, broadcastUsers, instantUserIds);
18073            }
18074        }
18075
18076        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18077            removedUsers = userIds;
18078            if (removedUsers == null) {
18079                broadcastUsers = null;
18080                return;
18081            }
18082
18083            broadcastUsers = EMPTY_INT_ARRAY;
18084            instantUserIds = EMPTY_INT_ARRAY;
18085            for (int i = userIds.length - 1; i >= 0; --i) {
18086                final int userId = userIds[i];
18087                if (deletedPackageSetting.getInstantApp(userId)) {
18088                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18089                } else {
18090                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18091                }
18092            }
18093        }
18094    }
18095
18096    /*
18097     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18098     * flag is not set, the data directory is removed as well.
18099     * make sure this flag is set for partially installed apps. If not its meaningless to
18100     * delete a partially installed application.
18101     */
18102    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18103            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18104        String packageName = ps.name;
18105        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18106        // Retrieve object to delete permissions for shared user later on
18107        final PackageParser.Package deletedPkg;
18108        final PackageSetting deletedPs;
18109        // reader
18110        synchronized (mPackages) {
18111            deletedPkg = mPackages.get(packageName);
18112            deletedPs = mSettings.mPackages.get(packageName);
18113            if (outInfo != null) {
18114                outInfo.removedPackage = packageName;
18115                outInfo.installerPackageName = ps.installerPackageName;
18116                outInfo.isStaticSharedLib = deletedPkg != null
18117                        && deletedPkg.staticSharedLibName != null;
18118                outInfo.populateUsers(deletedPs == null ? null
18119                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18120            }
18121        }
18122
18123        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18124
18125        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18126            final PackageParser.Package resolvedPkg;
18127            if (deletedPkg != null) {
18128                resolvedPkg = deletedPkg;
18129            } else {
18130                // We don't have a parsed package when it lives on an ejected
18131                // adopted storage device, so fake something together
18132                resolvedPkg = new PackageParser.Package(ps.name);
18133                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18134            }
18135            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18136                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18137            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18138            if (outInfo != null) {
18139                outInfo.dataRemoved = true;
18140            }
18141            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18142        }
18143
18144        int removedAppId = -1;
18145
18146        // writer
18147        synchronized (mPackages) {
18148            boolean installedStateChanged = false;
18149            if (deletedPs != null) {
18150                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18151                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18152                    clearDefaultBrowserIfNeeded(packageName);
18153                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18154                    removedAppId = mSettings.removePackageLPw(packageName);
18155                    if (outInfo != null) {
18156                        outInfo.removedAppId = removedAppId;
18157                    }
18158                    mPermissionManager.updatePermissions(
18159                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18160                    if (deletedPs.sharedUser != null) {
18161                        // Remove permissions associated with package. Since runtime
18162                        // permissions are per user we have to kill the removed package
18163                        // or packages running under the shared user of the removed
18164                        // package if revoking the permissions requested only by the removed
18165                        // package is successful and this causes a change in gids.
18166                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18167                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18168                                    userId);
18169                            if (userIdToKill == UserHandle.USER_ALL
18170                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18171                                // If gids changed for this user, kill all affected packages.
18172                                mHandler.post(new Runnable() {
18173                                    @Override
18174                                    public void run() {
18175                                        // This has to happen with no lock held.
18176                                        killApplication(deletedPs.name, deletedPs.appId,
18177                                                KILL_APP_REASON_GIDS_CHANGED);
18178                                    }
18179                                });
18180                                break;
18181                            }
18182                        }
18183                    }
18184                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18185                }
18186                // make sure to preserve per-user disabled state if this removal was just
18187                // a downgrade of a system app to the factory package
18188                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18189                    if (DEBUG_REMOVE) {
18190                        Slog.d(TAG, "Propagating install state across downgrade");
18191                    }
18192                    for (int userId : allUserHandles) {
18193                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18194                        if (DEBUG_REMOVE) {
18195                            Slog.d(TAG, "    user " + userId + " => " + installed);
18196                        }
18197                        if (installed != ps.getInstalled(userId)) {
18198                            installedStateChanged = true;
18199                        }
18200                        ps.setInstalled(installed, userId);
18201                    }
18202                }
18203            }
18204            // can downgrade to reader
18205            if (writeSettings) {
18206                // Save settings now
18207                mSettings.writeLPr();
18208            }
18209            if (installedStateChanged) {
18210                mSettings.writeKernelMappingLPr(ps);
18211            }
18212        }
18213        if (removedAppId != -1) {
18214            // A user ID was deleted here. Go through all users and remove it
18215            // from KeyStore.
18216            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18217        }
18218    }
18219
18220    static boolean locationIsPrivileged(String path) {
18221        try {
18222            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18223            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18224            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18225            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18226            return path.startsWith(privilegedAppDir.getCanonicalPath())
18227                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18228                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18229                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18230        } catch (IOException e) {
18231            Slog.e(TAG, "Unable to access code path " + path);
18232        }
18233        return false;
18234    }
18235
18236    static boolean locationIsOem(String path) {
18237        try {
18238            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18239        } catch (IOException e) {
18240            Slog.e(TAG, "Unable to access code path " + path);
18241        }
18242        return false;
18243    }
18244
18245    static boolean locationIsVendor(String path) {
18246        try {
18247            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18248                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18249        } catch (IOException e) {
18250            Slog.e(TAG, "Unable to access code path " + path);
18251        }
18252        return false;
18253    }
18254
18255    static boolean locationIsProduct(String path) {
18256        try {
18257            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18258        } catch (IOException e) {
18259            Slog.e(TAG, "Unable to access code path " + path);
18260        }
18261        return false;
18262    }
18263
18264    /*
18265     * Tries to delete system package.
18266     */
18267    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18268            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18269            boolean writeSettings) {
18270        if (deletedPs.parentPackageName != null) {
18271            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18272            return false;
18273        }
18274
18275        final boolean applyUserRestrictions
18276                = (allUserHandles != null) && (outInfo.origUsers != null);
18277        final PackageSetting disabledPs;
18278        // Confirm if the system package has been updated
18279        // An updated system app can be deleted. This will also have to restore
18280        // the system pkg from system partition
18281        // reader
18282        synchronized (mPackages) {
18283            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18284        }
18285
18286        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18287                + " disabledPs=" + disabledPs);
18288
18289        if (disabledPs == null) {
18290            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18291            return false;
18292        } else if (DEBUG_REMOVE) {
18293            Slog.d(TAG, "Deleting system pkg from data partition");
18294        }
18295
18296        if (DEBUG_REMOVE) {
18297            if (applyUserRestrictions) {
18298                Slog.d(TAG, "Remembering install states:");
18299                for (int userId : allUserHandles) {
18300                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18301                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18302                }
18303            }
18304        }
18305
18306        // Delete the updated package
18307        outInfo.isRemovedPackageSystemUpdate = true;
18308        if (outInfo.removedChildPackages != null) {
18309            final int childCount = (deletedPs.childPackageNames != null)
18310                    ? deletedPs.childPackageNames.size() : 0;
18311            for (int i = 0; i < childCount; i++) {
18312                String childPackageName = deletedPs.childPackageNames.get(i);
18313                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18314                        .contains(childPackageName)) {
18315                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18316                            childPackageName);
18317                    if (childInfo != null) {
18318                        childInfo.isRemovedPackageSystemUpdate = true;
18319                    }
18320                }
18321            }
18322        }
18323
18324        if (disabledPs.versionCode < deletedPs.versionCode) {
18325            // Delete data for downgrades
18326            flags &= ~PackageManager.DELETE_KEEP_DATA;
18327        } else {
18328            // Preserve data by setting flag
18329            flags |= PackageManager.DELETE_KEEP_DATA;
18330        }
18331
18332        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18333                outInfo, writeSettings, disabledPs.pkg);
18334        if (!ret) {
18335            return false;
18336        }
18337
18338        // writer
18339        synchronized (mPackages) {
18340            // NOTE: The system package always needs to be enabled; even if it's for
18341            // a compressed stub. If we don't, installing the system package fails
18342            // during scan [scanning checks the disabled packages]. We will reverse
18343            // this later, after we've "installed" the stub.
18344            // Reinstate the old system package
18345            enableSystemPackageLPw(disabledPs.pkg);
18346            // Remove any native libraries from the upgraded package.
18347            removeNativeBinariesLI(deletedPs);
18348        }
18349
18350        // Install the system package
18351        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18352        try {
18353            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18354                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18355        } catch (PackageManagerException e) {
18356            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18357                    + e.getMessage());
18358            return false;
18359        } finally {
18360            if (disabledPs.pkg.isStub) {
18361                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18362            }
18363        }
18364        return true;
18365    }
18366
18367    /**
18368     * Installs a package that's already on the system partition.
18369     */
18370    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18371            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18372            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18373                    throws PackageManagerException {
18374        @ParseFlags int parseFlags =
18375                mDefParseFlags
18376                | PackageParser.PARSE_MUST_BE_APK
18377                | PackageParser.PARSE_IS_SYSTEM_DIR;
18378        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18379        if (isPrivileged || locationIsPrivileged(codePathString)) {
18380            scanFlags |= SCAN_AS_PRIVILEGED;
18381        }
18382        if (locationIsOem(codePathString)) {
18383            scanFlags |= SCAN_AS_OEM;
18384        }
18385        if (locationIsVendor(codePathString)) {
18386            scanFlags |= SCAN_AS_VENDOR;
18387        }
18388        if (locationIsProduct(codePathString)) {
18389            scanFlags |= SCAN_AS_PRODUCT;
18390        }
18391
18392        final File codePath = new File(codePathString);
18393        final PackageParser.Package pkg =
18394                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18395
18396        try {
18397            // update shared libraries for the newly re-installed system package
18398            updateSharedLibrariesLPr(pkg, null);
18399        } catch (PackageManagerException e) {
18400            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18401        }
18402
18403        prepareAppDataAfterInstallLIF(pkg);
18404
18405        // writer
18406        synchronized (mPackages) {
18407            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18408
18409            // Propagate the permissions state as we do not want to drop on the floor
18410            // runtime permissions. The update permissions method below will take
18411            // care of removing obsolete permissions and grant install permissions.
18412            if (origPermissionState != null) {
18413                ps.getPermissionsState().copyFrom(origPermissionState);
18414            }
18415            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18416                    mPermissionCallback);
18417
18418            final boolean applyUserRestrictions
18419                    = (allUserHandles != null) && (origUserHandles != null);
18420            if (applyUserRestrictions) {
18421                boolean installedStateChanged = false;
18422                if (DEBUG_REMOVE) {
18423                    Slog.d(TAG, "Propagating install state across reinstall");
18424                }
18425                for (int userId : allUserHandles) {
18426                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18427                    if (DEBUG_REMOVE) {
18428                        Slog.d(TAG, "    user " + userId + " => " + installed);
18429                    }
18430                    if (installed != ps.getInstalled(userId)) {
18431                        installedStateChanged = true;
18432                    }
18433                    ps.setInstalled(installed, userId);
18434
18435                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18436                }
18437                // Regardless of writeSettings we need to ensure that this restriction
18438                // state propagation is persisted
18439                mSettings.writeAllUsersPackageRestrictionsLPr();
18440                if (installedStateChanged) {
18441                    mSettings.writeKernelMappingLPr(ps);
18442                }
18443            }
18444            // can downgrade to reader here
18445            if (writeSettings) {
18446                mSettings.writeLPr();
18447            }
18448        }
18449        return pkg;
18450    }
18451
18452    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18453            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18454            PackageRemovedInfo outInfo, boolean writeSettings,
18455            PackageParser.Package replacingPackage) {
18456        synchronized (mPackages) {
18457            if (outInfo != null) {
18458                outInfo.uid = ps.appId;
18459            }
18460
18461            if (outInfo != null && outInfo.removedChildPackages != null) {
18462                final int childCount = (ps.childPackageNames != null)
18463                        ? ps.childPackageNames.size() : 0;
18464                for (int i = 0; i < childCount; i++) {
18465                    String childPackageName = ps.childPackageNames.get(i);
18466                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18467                    if (childPs == null) {
18468                        return false;
18469                    }
18470                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18471                            childPackageName);
18472                    if (childInfo != null) {
18473                        childInfo.uid = childPs.appId;
18474                    }
18475                }
18476            }
18477        }
18478
18479        // Delete package data from internal structures and also remove data if flag is set
18480        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18481
18482        // Delete the child packages data
18483        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18484        for (int i = 0; i < childCount; i++) {
18485            PackageSetting childPs;
18486            synchronized (mPackages) {
18487                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18488            }
18489            if (childPs != null) {
18490                PackageRemovedInfo childOutInfo = (outInfo != null
18491                        && outInfo.removedChildPackages != null)
18492                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18493                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18494                        && (replacingPackage != null
18495                        && !replacingPackage.hasChildPackage(childPs.name))
18496                        ? flags & ~DELETE_KEEP_DATA : flags;
18497                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18498                        deleteFlags, writeSettings);
18499            }
18500        }
18501
18502        // Delete application code and resources only for parent packages
18503        if (ps.parentPackageName == null) {
18504            if (deleteCodeAndResources && (outInfo != null)) {
18505                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18506                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18507                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18508            }
18509        }
18510
18511        return true;
18512    }
18513
18514    @Override
18515    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18516            int userId) {
18517        mContext.enforceCallingOrSelfPermission(
18518                android.Manifest.permission.DELETE_PACKAGES, null);
18519        synchronized (mPackages) {
18520            // Cannot block uninstall of static shared libs as they are
18521            // considered a part of the using app (emulating static linking).
18522            // Also static libs are installed always on internal storage.
18523            PackageParser.Package pkg = mPackages.get(packageName);
18524            if (pkg != null && pkg.staticSharedLibName != null) {
18525                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18526                        + " providing static shared library: " + pkg.staticSharedLibName);
18527                return false;
18528            }
18529            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18530            mSettings.writePackageRestrictionsLPr(userId);
18531        }
18532        return true;
18533    }
18534
18535    @Override
18536    public boolean getBlockUninstallForUser(String packageName, int userId) {
18537        synchronized (mPackages) {
18538            final PackageSetting ps = mSettings.mPackages.get(packageName);
18539            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18540                return false;
18541            }
18542            return mSettings.getBlockUninstallLPr(userId, packageName);
18543        }
18544    }
18545
18546    @Override
18547    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18548        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18549        synchronized (mPackages) {
18550            PackageSetting ps = mSettings.mPackages.get(packageName);
18551            if (ps == null) {
18552                Log.w(TAG, "Package doesn't exist: " + packageName);
18553                return false;
18554            }
18555            if (systemUserApp) {
18556                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18557            } else {
18558                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18559            }
18560            mSettings.writeLPr();
18561        }
18562        return true;
18563    }
18564
18565    /*
18566     * This method handles package deletion in general
18567     */
18568    private boolean deletePackageLIF(String packageName, UserHandle user,
18569            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18570            PackageRemovedInfo outInfo, boolean writeSettings,
18571            PackageParser.Package replacingPackage) {
18572        if (packageName == null) {
18573            Slog.w(TAG, "Attempt to delete null packageName.");
18574            return false;
18575        }
18576
18577        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18578
18579        PackageSetting ps;
18580        synchronized (mPackages) {
18581            ps = mSettings.mPackages.get(packageName);
18582            if (ps == null) {
18583                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18584                return false;
18585            }
18586
18587            if (ps.parentPackageName != null && (!isSystemApp(ps)
18588                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18589                if (DEBUG_REMOVE) {
18590                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18591                            + ((user == null) ? UserHandle.USER_ALL : user));
18592                }
18593                final int removedUserId = (user != null) ? user.getIdentifier()
18594                        : UserHandle.USER_ALL;
18595                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18596                    return false;
18597                }
18598                markPackageUninstalledForUserLPw(ps, user);
18599                scheduleWritePackageRestrictionsLocked(user);
18600                return true;
18601            }
18602        }
18603
18604        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18605                && user.getIdentifier() != UserHandle.USER_ALL)) {
18606            // The caller is asking that the package only be deleted for a single
18607            // user.  To do this, we just mark its uninstalled state and delete
18608            // its data. If this is a system app, we only allow this to happen if
18609            // they have set the special DELETE_SYSTEM_APP which requests different
18610            // semantics than normal for uninstalling system apps.
18611            markPackageUninstalledForUserLPw(ps, user);
18612
18613            if (!isSystemApp(ps)) {
18614                // Do not uninstall the APK if an app should be cached
18615                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18616                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18617                    // Other user still have this package installed, so all
18618                    // we need to do is clear this user's data and save that
18619                    // it is uninstalled.
18620                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18621                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18622                        return false;
18623                    }
18624                    scheduleWritePackageRestrictionsLocked(user);
18625                    return true;
18626                } else {
18627                    // We need to set it back to 'installed' so the uninstall
18628                    // broadcasts will be sent correctly.
18629                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18630                    ps.setInstalled(true, user.getIdentifier());
18631                    mSettings.writeKernelMappingLPr(ps);
18632                }
18633            } else {
18634                // This is a system app, so we assume that the
18635                // other users still have this package installed, so all
18636                // we need to do is clear this user's data and save that
18637                // it is uninstalled.
18638                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18639                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18640                    return false;
18641                }
18642                scheduleWritePackageRestrictionsLocked(user);
18643                return true;
18644            }
18645        }
18646
18647        // If we are deleting a composite package for all users, keep track
18648        // of result for each child.
18649        if (ps.childPackageNames != null && outInfo != null) {
18650            synchronized (mPackages) {
18651                final int childCount = ps.childPackageNames.size();
18652                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18653                for (int i = 0; i < childCount; i++) {
18654                    String childPackageName = ps.childPackageNames.get(i);
18655                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18656                    childInfo.removedPackage = childPackageName;
18657                    childInfo.installerPackageName = ps.installerPackageName;
18658                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18659                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18660                    if (childPs != null) {
18661                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18662                    }
18663                }
18664            }
18665        }
18666
18667        boolean ret = false;
18668        if (isSystemApp(ps)) {
18669            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18670            // When an updated system application is deleted we delete the existing resources
18671            // as well and fall back to existing code in system partition
18672            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18673        } else {
18674            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18675            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18676                    outInfo, writeSettings, replacingPackage);
18677        }
18678
18679        // Take a note whether we deleted the package for all users
18680        if (outInfo != null) {
18681            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18682            if (outInfo.removedChildPackages != null) {
18683                synchronized (mPackages) {
18684                    final int childCount = outInfo.removedChildPackages.size();
18685                    for (int i = 0; i < childCount; i++) {
18686                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18687                        if (childInfo != null) {
18688                            childInfo.removedForAllUsers = mPackages.get(
18689                                    childInfo.removedPackage) == null;
18690                        }
18691                    }
18692                }
18693            }
18694            // If we uninstalled an update to a system app there may be some
18695            // child packages that appeared as they are declared in the system
18696            // app but were not declared in the update.
18697            if (isSystemApp(ps)) {
18698                synchronized (mPackages) {
18699                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18700                    final int childCount = (updatedPs.childPackageNames != null)
18701                            ? updatedPs.childPackageNames.size() : 0;
18702                    for (int i = 0; i < childCount; i++) {
18703                        String childPackageName = updatedPs.childPackageNames.get(i);
18704                        if (outInfo.removedChildPackages == null
18705                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18706                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18707                            if (childPs == null) {
18708                                continue;
18709                            }
18710                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18711                            installRes.name = childPackageName;
18712                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18713                            installRes.pkg = mPackages.get(childPackageName);
18714                            installRes.uid = childPs.pkg.applicationInfo.uid;
18715                            if (outInfo.appearedChildPackages == null) {
18716                                outInfo.appearedChildPackages = new ArrayMap<>();
18717                            }
18718                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18719                        }
18720                    }
18721                }
18722            }
18723        }
18724
18725        return ret;
18726    }
18727
18728    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18729        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18730                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18731        for (int nextUserId : userIds) {
18732            if (DEBUG_REMOVE) {
18733                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18734            }
18735            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18736                    false /*installed*/,
18737                    true /*stopped*/,
18738                    true /*notLaunched*/,
18739                    false /*hidden*/,
18740                    false /*suspended*/,
18741                    false /*instantApp*/,
18742                    false /*virtualPreload*/,
18743                    null /*lastDisableAppCaller*/,
18744                    null /*enabledComponents*/,
18745                    null /*disabledComponents*/,
18746                    ps.readUserState(nextUserId).domainVerificationStatus,
18747                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18748                    null /*harmfulAppWarning*/);
18749        }
18750        mSettings.writeKernelMappingLPr(ps);
18751    }
18752
18753    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18754            PackageRemovedInfo outInfo) {
18755        final PackageParser.Package pkg;
18756        synchronized (mPackages) {
18757            pkg = mPackages.get(ps.name);
18758        }
18759
18760        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18761                : new int[] {userId};
18762        for (int nextUserId : userIds) {
18763            if (DEBUG_REMOVE) {
18764                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18765                        + nextUserId);
18766            }
18767
18768            destroyAppDataLIF(pkg, userId,
18769                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18770            destroyAppProfilesLIF(pkg, userId);
18771            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18772            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18773            schedulePackageCleaning(ps.name, nextUserId, false);
18774            synchronized (mPackages) {
18775                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18776                    scheduleWritePackageRestrictionsLocked(nextUserId);
18777                }
18778                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18779            }
18780        }
18781
18782        if (outInfo != null) {
18783            outInfo.removedPackage = ps.name;
18784            outInfo.installerPackageName = ps.installerPackageName;
18785            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18786            outInfo.removedAppId = ps.appId;
18787            outInfo.removedUsers = userIds;
18788            outInfo.broadcastUsers = userIds;
18789        }
18790
18791        return true;
18792    }
18793
18794    private static final class ClearStorageConnection implements ServiceConnection {
18795        IMediaContainerService mContainerService;
18796
18797        @Override
18798        public void onServiceConnected(ComponentName name, IBinder service) {
18799            synchronized (this) {
18800                mContainerService = IMediaContainerService.Stub
18801                        .asInterface(Binder.allowBlocking(service));
18802                notifyAll();
18803            }
18804        }
18805
18806        @Override
18807        public void onServiceDisconnected(ComponentName name) {
18808        }
18809    }
18810
18811    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18812        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18813
18814        final boolean mounted;
18815        if (Environment.isExternalStorageEmulated()) {
18816            mounted = true;
18817        } else {
18818            final String status = Environment.getExternalStorageState();
18819
18820            mounted = status.equals(Environment.MEDIA_MOUNTED)
18821                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18822        }
18823
18824        if (!mounted) {
18825            return;
18826        }
18827
18828        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18829        int[] users;
18830        if (userId == UserHandle.USER_ALL) {
18831            users = sUserManager.getUserIds();
18832        } else {
18833            users = new int[] { userId };
18834        }
18835        final ClearStorageConnection conn = new ClearStorageConnection();
18836        if (mContext.bindServiceAsUser(
18837                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18838            try {
18839                for (int curUser : users) {
18840                    long timeout = SystemClock.uptimeMillis() + 5000;
18841                    synchronized (conn) {
18842                        long now;
18843                        while (conn.mContainerService == null &&
18844                                (now = SystemClock.uptimeMillis()) < timeout) {
18845                            try {
18846                                conn.wait(timeout - now);
18847                            } catch (InterruptedException e) {
18848                            }
18849                        }
18850                    }
18851                    if (conn.mContainerService == null) {
18852                        return;
18853                    }
18854
18855                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18856                    clearDirectory(conn.mContainerService,
18857                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18858                    if (allData) {
18859                        clearDirectory(conn.mContainerService,
18860                                userEnv.buildExternalStorageAppDataDirs(packageName));
18861                        clearDirectory(conn.mContainerService,
18862                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18863                    }
18864                }
18865            } finally {
18866                mContext.unbindService(conn);
18867            }
18868        }
18869    }
18870
18871    @Override
18872    public void clearApplicationProfileData(String packageName) {
18873        enforceSystemOrRoot("Only the system can clear all profile data");
18874
18875        final PackageParser.Package pkg;
18876        synchronized (mPackages) {
18877            pkg = mPackages.get(packageName);
18878        }
18879
18880        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18881            synchronized (mInstallLock) {
18882                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18883            }
18884        }
18885    }
18886
18887    @Override
18888    public void clearApplicationUserData(final String packageName,
18889            final IPackageDataObserver observer, final int userId) {
18890        mContext.enforceCallingOrSelfPermission(
18891                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18892
18893        final int callingUid = Binder.getCallingUid();
18894        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18895                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18896
18897        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18898        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18899        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18900            throw new SecurityException("Cannot clear data for a protected package: "
18901                    + packageName);
18902        }
18903        // Queue up an async operation since the package deletion may take a little while.
18904        mHandler.post(new Runnable() {
18905            public void run() {
18906                mHandler.removeCallbacks(this);
18907                final boolean succeeded;
18908                if (!filterApp) {
18909                    try (PackageFreezer freezer = freezePackage(packageName,
18910                            "clearApplicationUserData")) {
18911                        synchronized (mInstallLock) {
18912                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18913                        }
18914                        clearExternalStorageDataSync(packageName, userId, true);
18915                        synchronized (mPackages) {
18916                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18917                                    packageName, userId);
18918                        }
18919                    }
18920                    if (succeeded) {
18921                        // invoke DeviceStorageMonitor's update method to clear any notifications
18922                        DeviceStorageMonitorInternal dsm = LocalServices
18923                                .getService(DeviceStorageMonitorInternal.class);
18924                        if (dsm != null) {
18925                            dsm.checkMemory();
18926                        }
18927                    }
18928                } else {
18929                    succeeded = false;
18930                }
18931                if (observer != null) {
18932                    try {
18933                        observer.onRemoveCompleted(packageName, succeeded);
18934                    } catch (RemoteException e) {
18935                        Log.i(TAG, "Observer no longer exists.");
18936                    }
18937                } //end if observer
18938            } //end run
18939        });
18940    }
18941
18942    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18943        if (packageName == null) {
18944            Slog.w(TAG, "Attempt to delete null packageName.");
18945            return false;
18946        }
18947
18948        // Try finding details about the requested package
18949        PackageParser.Package pkg;
18950        synchronized (mPackages) {
18951            pkg = mPackages.get(packageName);
18952            if (pkg == null) {
18953                final PackageSetting ps = mSettings.mPackages.get(packageName);
18954                if (ps != null) {
18955                    pkg = ps.pkg;
18956                }
18957            }
18958
18959            if (pkg == null) {
18960                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18961                return false;
18962            }
18963
18964            PackageSetting ps = (PackageSetting) pkg.mExtras;
18965            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18966        }
18967
18968        clearAppDataLIF(pkg, userId,
18969                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18970
18971        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18972        removeKeystoreDataIfNeeded(userId, appId);
18973
18974        UserManagerInternal umInternal = getUserManagerInternal();
18975        final int flags;
18976        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18977            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18978        } else if (umInternal.isUserRunning(userId)) {
18979            flags = StorageManager.FLAG_STORAGE_DE;
18980        } else {
18981            flags = 0;
18982        }
18983        prepareAppDataContentsLIF(pkg, userId, flags);
18984
18985        return true;
18986    }
18987
18988    /**
18989     * Reverts user permission state changes (permissions and flags) in
18990     * all packages for a given user.
18991     *
18992     * @param userId The device user for which to do a reset.
18993     */
18994    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18995        final int packageCount = mPackages.size();
18996        for (int i = 0; i < packageCount; i++) {
18997            PackageParser.Package pkg = mPackages.valueAt(i);
18998            PackageSetting ps = (PackageSetting) pkg.mExtras;
18999            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19000        }
19001    }
19002
19003    private void resetNetworkPolicies(int userId) {
19004        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19005    }
19006
19007    /**
19008     * Reverts user permission state changes (permissions and flags).
19009     *
19010     * @param ps The package for which to reset.
19011     * @param userId The device user for which to do a reset.
19012     */
19013    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19014            final PackageSetting ps, final int userId) {
19015        if (ps.pkg == null) {
19016            return;
19017        }
19018
19019        // These are flags that can change base on user actions.
19020        final int userSettableMask = FLAG_PERMISSION_USER_SET
19021                | FLAG_PERMISSION_USER_FIXED
19022                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19023                | FLAG_PERMISSION_REVIEW_REQUIRED;
19024
19025        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19026                | FLAG_PERMISSION_POLICY_FIXED;
19027
19028        boolean writeInstallPermissions = false;
19029        boolean writeRuntimePermissions = false;
19030
19031        final int permissionCount = ps.pkg.requestedPermissions.size();
19032        for (int i = 0; i < permissionCount; i++) {
19033            final String permName = ps.pkg.requestedPermissions.get(i);
19034            final BasePermission bp =
19035                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19036            if (bp == null) {
19037                continue;
19038            }
19039
19040            // If shared user we just reset the state to which only this app contributed.
19041            if (ps.sharedUser != null) {
19042                boolean used = false;
19043                final int packageCount = ps.sharedUser.packages.size();
19044                for (int j = 0; j < packageCount; j++) {
19045                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19046                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19047                            && pkg.pkg.requestedPermissions.contains(permName)) {
19048                        used = true;
19049                        break;
19050                    }
19051                }
19052                if (used) {
19053                    continue;
19054                }
19055            }
19056
19057            final PermissionsState permissionsState = ps.getPermissionsState();
19058
19059            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19060
19061            // Always clear the user settable flags.
19062            final boolean hasInstallState =
19063                    permissionsState.getInstallPermissionState(permName) != null;
19064            // If permission review is enabled and this is a legacy app, mark the
19065            // permission as requiring a review as this is the initial state.
19066            int flags = 0;
19067            if (mSettings.mPermissions.mPermissionReviewRequired
19068                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19069                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19070            }
19071            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19072                if (hasInstallState) {
19073                    writeInstallPermissions = true;
19074                } else {
19075                    writeRuntimePermissions = true;
19076                }
19077            }
19078
19079            // Below is only runtime permission handling.
19080            if (!bp.isRuntime()) {
19081                continue;
19082            }
19083
19084            // Never clobber system or policy.
19085            if ((oldFlags & policyOrSystemFlags) != 0) {
19086                continue;
19087            }
19088
19089            // If this permission was granted by default, make sure it is.
19090            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19091                if (permissionsState.grantRuntimePermission(bp, userId)
19092                        != PERMISSION_OPERATION_FAILURE) {
19093                    writeRuntimePermissions = true;
19094                }
19095            // If permission review is enabled the permissions for a legacy apps
19096            // are represented as constantly granted runtime ones, so don't revoke.
19097            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19098                // Otherwise, reset the permission.
19099                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19100                switch (revokeResult) {
19101                    case PERMISSION_OPERATION_SUCCESS:
19102                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19103                        writeRuntimePermissions = true;
19104                        final int appId = ps.appId;
19105                        mHandler.post(new Runnable() {
19106                            @Override
19107                            public void run() {
19108                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19109                            }
19110                        });
19111                    } break;
19112                }
19113            }
19114        }
19115
19116        // Synchronously write as we are taking permissions away.
19117        if (writeRuntimePermissions) {
19118            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19119        }
19120
19121        // Synchronously write as we are taking permissions away.
19122        if (writeInstallPermissions) {
19123            mSettings.writeLPr();
19124        }
19125    }
19126
19127    /**
19128     * Remove entries from the keystore daemon. Will only remove it if the
19129     * {@code appId} is valid.
19130     */
19131    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19132        if (appId < 0) {
19133            return;
19134        }
19135
19136        final KeyStore keyStore = KeyStore.getInstance();
19137        if (keyStore != null) {
19138            if (userId == UserHandle.USER_ALL) {
19139                for (final int individual : sUserManager.getUserIds()) {
19140                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19141                }
19142            } else {
19143                keyStore.clearUid(UserHandle.getUid(userId, appId));
19144            }
19145        } else {
19146            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19147        }
19148    }
19149
19150    @Override
19151    public void deleteApplicationCacheFiles(final String packageName,
19152            final IPackageDataObserver observer) {
19153        final int userId = UserHandle.getCallingUserId();
19154        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19155    }
19156
19157    @Override
19158    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19159            final IPackageDataObserver observer) {
19160        final int callingUid = Binder.getCallingUid();
19161        if (mContext.checkCallingOrSelfPermission(
19162                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19163                != PackageManager.PERMISSION_GRANTED) {
19164            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19165            if (mContext.checkCallingOrSelfPermission(
19166                    android.Manifest.permission.DELETE_CACHE_FILES)
19167                    == PackageManager.PERMISSION_GRANTED) {
19168                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19169                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19170                        ", silently ignoring");
19171                return;
19172            }
19173            mContext.enforceCallingOrSelfPermission(
19174                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19175        }
19176        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19177                /* requireFullPermission= */ true, /* checkShell= */ false,
19178                "delete application cache files");
19179        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19180                android.Manifest.permission.ACCESS_INSTANT_APPS);
19181
19182        final PackageParser.Package pkg;
19183        synchronized (mPackages) {
19184            pkg = mPackages.get(packageName);
19185        }
19186
19187        // Queue up an async operation since the package deletion may take a little while.
19188        mHandler.post(new Runnable() {
19189            public void run() {
19190                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19191                boolean doClearData = true;
19192                if (ps != null) {
19193                    final boolean targetIsInstantApp =
19194                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19195                    doClearData = !targetIsInstantApp
19196                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19197                }
19198                if (doClearData) {
19199                    synchronized (mInstallLock) {
19200                        final int flags = StorageManager.FLAG_STORAGE_DE
19201                                | StorageManager.FLAG_STORAGE_CE;
19202                        // We're only clearing cache files, so we don't care if the
19203                        // app is unfrozen and still able to run
19204                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19205                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19206                    }
19207                    clearExternalStorageDataSync(packageName, userId, false);
19208                }
19209                if (observer != null) {
19210                    try {
19211                        observer.onRemoveCompleted(packageName, true);
19212                    } catch (RemoteException e) {
19213                        Log.i(TAG, "Observer no longer exists.");
19214                    }
19215                }
19216            }
19217        });
19218    }
19219
19220    @Override
19221    public void getPackageSizeInfo(final String packageName, int userHandle,
19222            final IPackageStatsObserver observer) {
19223        throw new UnsupportedOperationException(
19224                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19225    }
19226
19227    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19228        final PackageSetting ps;
19229        synchronized (mPackages) {
19230            ps = mSettings.mPackages.get(packageName);
19231            if (ps == null) {
19232                Slog.w(TAG, "Failed to find settings for " + packageName);
19233                return false;
19234            }
19235        }
19236
19237        final String[] packageNames = { packageName };
19238        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19239        final String[] codePaths = { ps.codePathString };
19240
19241        try {
19242            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19243                    ps.appId, ceDataInodes, codePaths, stats);
19244
19245            // For now, ignore code size of packages on system partition
19246            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19247                stats.codeSize = 0;
19248            }
19249
19250            // External clients expect these to be tracked separately
19251            stats.dataSize -= stats.cacheSize;
19252
19253        } catch (InstallerException e) {
19254            Slog.w(TAG, String.valueOf(e));
19255            return false;
19256        }
19257
19258        return true;
19259    }
19260
19261    private int getUidTargetSdkVersionLockedLPr(int uid) {
19262        Object obj = mSettings.getUserIdLPr(uid);
19263        if (obj instanceof SharedUserSetting) {
19264            final SharedUserSetting sus = (SharedUserSetting) obj;
19265            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19266            final Iterator<PackageSetting> it = sus.packages.iterator();
19267            while (it.hasNext()) {
19268                final PackageSetting ps = it.next();
19269                if (ps.pkg != null) {
19270                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19271                    if (v < vers) vers = v;
19272                }
19273            }
19274            return vers;
19275        } else if (obj instanceof PackageSetting) {
19276            final PackageSetting ps = (PackageSetting) obj;
19277            if (ps.pkg != null) {
19278                return ps.pkg.applicationInfo.targetSdkVersion;
19279            }
19280        }
19281        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19282    }
19283
19284    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19285        final PackageParser.Package p = mPackages.get(packageName);
19286        if (p != null) {
19287            return p.applicationInfo.targetSdkVersion;
19288        }
19289        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19290    }
19291
19292    @Override
19293    public void addPreferredActivity(IntentFilter filter, int match,
19294            ComponentName[] set, ComponentName activity, int userId) {
19295        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19296                "Adding preferred");
19297    }
19298
19299    private void addPreferredActivityInternal(IntentFilter filter, int match,
19300            ComponentName[] set, ComponentName activity, boolean always, int userId,
19301            String opname) {
19302        // writer
19303        int callingUid = Binder.getCallingUid();
19304        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19305                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19306        if (filter.countActions() == 0) {
19307            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19308            return;
19309        }
19310        synchronized (mPackages) {
19311            if (mContext.checkCallingOrSelfPermission(
19312                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19313                    != PackageManager.PERMISSION_GRANTED) {
19314                if (getUidTargetSdkVersionLockedLPr(callingUid)
19315                        < Build.VERSION_CODES.FROYO) {
19316                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19317                            + callingUid);
19318                    return;
19319                }
19320                mContext.enforceCallingOrSelfPermission(
19321                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19322            }
19323
19324            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19325            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19326                    + userId + ":");
19327            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19328            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19329            scheduleWritePackageRestrictionsLocked(userId);
19330            postPreferredActivityChangedBroadcast(userId);
19331        }
19332    }
19333
19334    private void postPreferredActivityChangedBroadcast(int userId) {
19335        mHandler.post(() -> {
19336            final IActivityManager am = ActivityManager.getService();
19337            if (am == null) {
19338                return;
19339            }
19340
19341            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19342            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19343            try {
19344                am.broadcastIntent(null, intent, null, null,
19345                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19346                        null, false, false, userId);
19347            } catch (RemoteException e) {
19348            }
19349        });
19350    }
19351
19352    @Override
19353    public void replacePreferredActivity(IntentFilter filter, int match,
19354            ComponentName[] set, ComponentName activity, int userId) {
19355        if (filter.countActions() != 1) {
19356            throw new IllegalArgumentException(
19357                    "replacePreferredActivity expects filter to have only 1 action.");
19358        }
19359        if (filter.countDataAuthorities() != 0
19360                || filter.countDataPaths() != 0
19361                || filter.countDataSchemes() > 1
19362                || filter.countDataTypes() != 0) {
19363            throw new IllegalArgumentException(
19364                    "replacePreferredActivity expects filter to have no data authorities, " +
19365                    "paths, or types; and at most one scheme.");
19366        }
19367
19368        final int callingUid = Binder.getCallingUid();
19369        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19370                true /* requireFullPermission */, false /* checkShell */,
19371                "replace preferred activity");
19372        synchronized (mPackages) {
19373            if (mContext.checkCallingOrSelfPermission(
19374                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19375                    != PackageManager.PERMISSION_GRANTED) {
19376                if (getUidTargetSdkVersionLockedLPr(callingUid)
19377                        < Build.VERSION_CODES.FROYO) {
19378                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19379                            + Binder.getCallingUid());
19380                    return;
19381                }
19382                mContext.enforceCallingOrSelfPermission(
19383                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19384            }
19385
19386            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19387            if (pir != null) {
19388                // Get all of the existing entries that exactly match this filter.
19389                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19390                if (existing != null && existing.size() == 1) {
19391                    PreferredActivity cur = existing.get(0);
19392                    if (DEBUG_PREFERRED) {
19393                        Slog.i(TAG, "Checking replace of preferred:");
19394                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19395                        if (!cur.mPref.mAlways) {
19396                            Slog.i(TAG, "  -- CUR; not mAlways!");
19397                        } else {
19398                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19399                            Slog.i(TAG, "  -- CUR: mSet="
19400                                    + Arrays.toString(cur.mPref.mSetComponents));
19401                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19402                            Slog.i(TAG, "  -- NEW: mMatch="
19403                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19404                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19405                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19406                        }
19407                    }
19408                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19409                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19410                            && cur.mPref.sameSet(set)) {
19411                        // Setting the preferred activity to what it happens to be already
19412                        if (DEBUG_PREFERRED) {
19413                            Slog.i(TAG, "Replacing with same preferred activity "
19414                                    + cur.mPref.mShortComponent + " for user "
19415                                    + userId + ":");
19416                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19417                        }
19418                        return;
19419                    }
19420                }
19421
19422                if (existing != null) {
19423                    if (DEBUG_PREFERRED) {
19424                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19425                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19426                    }
19427                    for (int i = 0; i < existing.size(); i++) {
19428                        PreferredActivity pa = existing.get(i);
19429                        if (DEBUG_PREFERRED) {
19430                            Slog.i(TAG, "Removing existing preferred activity "
19431                                    + pa.mPref.mComponent + ":");
19432                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19433                        }
19434                        pir.removeFilter(pa);
19435                    }
19436                }
19437            }
19438            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19439                    "Replacing preferred");
19440        }
19441    }
19442
19443    @Override
19444    public void clearPackagePreferredActivities(String packageName) {
19445        final int callingUid = Binder.getCallingUid();
19446        if (getInstantAppPackageName(callingUid) != null) {
19447            return;
19448        }
19449        // writer
19450        synchronized (mPackages) {
19451            PackageParser.Package pkg = mPackages.get(packageName);
19452            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19453                if (mContext.checkCallingOrSelfPermission(
19454                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19455                        != PackageManager.PERMISSION_GRANTED) {
19456                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19457                            < Build.VERSION_CODES.FROYO) {
19458                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19459                                + callingUid);
19460                        return;
19461                    }
19462                    mContext.enforceCallingOrSelfPermission(
19463                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19464                }
19465            }
19466            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19467            if (ps != null
19468                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19469                return;
19470            }
19471            int user = UserHandle.getCallingUserId();
19472            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19473                scheduleWritePackageRestrictionsLocked(user);
19474            }
19475        }
19476    }
19477
19478    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19479    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19480        ArrayList<PreferredActivity> removed = null;
19481        boolean changed = false;
19482        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19483            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19484            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19485            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19486                continue;
19487            }
19488            Iterator<PreferredActivity> it = pir.filterIterator();
19489            while (it.hasNext()) {
19490                PreferredActivity pa = it.next();
19491                // Mark entry for removal only if it matches the package name
19492                // and the entry is of type "always".
19493                if (packageName == null ||
19494                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19495                                && pa.mPref.mAlways)) {
19496                    if (removed == null) {
19497                        removed = new ArrayList<PreferredActivity>();
19498                    }
19499                    removed.add(pa);
19500                }
19501            }
19502            if (removed != null) {
19503                for (int j=0; j<removed.size(); j++) {
19504                    PreferredActivity pa = removed.get(j);
19505                    pir.removeFilter(pa);
19506                }
19507                changed = true;
19508            }
19509        }
19510        if (changed) {
19511            postPreferredActivityChangedBroadcast(userId);
19512        }
19513        return changed;
19514    }
19515
19516    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19517    private void clearIntentFilterVerificationsLPw(int userId) {
19518        final int packageCount = mPackages.size();
19519        for (int i = 0; i < packageCount; i++) {
19520            PackageParser.Package pkg = mPackages.valueAt(i);
19521            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19522        }
19523    }
19524
19525    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19526    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19527        if (userId == UserHandle.USER_ALL) {
19528            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19529                    sUserManager.getUserIds())) {
19530                for (int oneUserId : sUserManager.getUserIds()) {
19531                    scheduleWritePackageRestrictionsLocked(oneUserId);
19532                }
19533            }
19534        } else {
19535            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19536                scheduleWritePackageRestrictionsLocked(userId);
19537            }
19538        }
19539    }
19540
19541    /** Clears state for all users, and touches intent filter verification policy */
19542    void clearDefaultBrowserIfNeeded(String packageName) {
19543        for (int oneUserId : sUserManager.getUserIds()) {
19544            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19545        }
19546    }
19547
19548    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19549        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19550        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19551            if (packageName.equals(defaultBrowserPackageName)) {
19552                setDefaultBrowserPackageName(null, userId);
19553            }
19554        }
19555    }
19556
19557    @Override
19558    public void resetApplicationPreferences(int userId) {
19559        mContext.enforceCallingOrSelfPermission(
19560                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19561        final long identity = Binder.clearCallingIdentity();
19562        // writer
19563        try {
19564            synchronized (mPackages) {
19565                clearPackagePreferredActivitiesLPw(null, userId);
19566                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19567                // TODO: We have to reset the default SMS and Phone. This requires
19568                // significant refactoring to keep all default apps in the package
19569                // manager (cleaner but more work) or have the services provide
19570                // callbacks to the package manager to request a default app reset.
19571                applyFactoryDefaultBrowserLPw(userId);
19572                clearIntentFilterVerificationsLPw(userId);
19573                primeDomainVerificationsLPw(userId);
19574                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19575                scheduleWritePackageRestrictionsLocked(userId);
19576            }
19577            resetNetworkPolicies(userId);
19578        } finally {
19579            Binder.restoreCallingIdentity(identity);
19580        }
19581    }
19582
19583    @Override
19584    public int getPreferredActivities(List<IntentFilter> outFilters,
19585            List<ComponentName> outActivities, String packageName) {
19586        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19587            return 0;
19588        }
19589        int num = 0;
19590        final int userId = UserHandle.getCallingUserId();
19591        // reader
19592        synchronized (mPackages) {
19593            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19594            if (pir != null) {
19595                final Iterator<PreferredActivity> it = pir.filterIterator();
19596                while (it.hasNext()) {
19597                    final PreferredActivity pa = it.next();
19598                    if (packageName == null
19599                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19600                                    && pa.mPref.mAlways)) {
19601                        if (outFilters != null) {
19602                            outFilters.add(new IntentFilter(pa));
19603                        }
19604                        if (outActivities != null) {
19605                            outActivities.add(pa.mPref.mComponent);
19606                        }
19607                    }
19608                }
19609            }
19610        }
19611
19612        return num;
19613    }
19614
19615    @Override
19616    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19617            int userId) {
19618        int callingUid = Binder.getCallingUid();
19619        if (callingUid != Process.SYSTEM_UID) {
19620            throw new SecurityException(
19621                    "addPersistentPreferredActivity can only be run by the system");
19622        }
19623        if (filter.countActions() == 0) {
19624            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19625            return;
19626        }
19627        synchronized (mPackages) {
19628            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19629                    ":");
19630            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19631            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19632                    new PersistentPreferredActivity(filter, activity));
19633            scheduleWritePackageRestrictionsLocked(userId);
19634            postPreferredActivityChangedBroadcast(userId);
19635        }
19636    }
19637
19638    @Override
19639    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19640        int callingUid = Binder.getCallingUid();
19641        if (callingUid != Process.SYSTEM_UID) {
19642            throw new SecurityException(
19643                    "clearPackagePersistentPreferredActivities can only be run by the system");
19644        }
19645        ArrayList<PersistentPreferredActivity> removed = null;
19646        boolean changed = false;
19647        synchronized (mPackages) {
19648            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19649                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19650                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19651                        .valueAt(i);
19652                if (userId != thisUserId) {
19653                    continue;
19654                }
19655                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19656                while (it.hasNext()) {
19657                    PersistentPreferredActivity ppa = it.next();
19658                    // Mark entry for removal only if it matches the package name.
19659                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19660                        if (removed == null) {
19661                            removed = new ArrayList<PersistentPreferredActivity>();
19662                        }
19663                        removed.add(ppa);
19664                    }
19665                }
19666                if (removed != null) {
19667                    for (int j=0; j<removed.size(); j++) {
19668                        PersistentPreferredActivity ppa = removed.get(j);
19669                        ppir.removeFilter(ppa);
19670                    }
19671                    changed = true;
19672                }
19673            }
19674
19675            if (changed) {
19676                scheduleWritePackageRestrictionsLocked(userId);
19677                postPreferredActivityChangedBroadcast(userId);
19678            }
19679        }
19680    }
19681
19682    /**
19683     * Common machinery for picking apart a restored XML blob and passing
19684     * it to a caller-supplied functor to be applied to the running system.
19685     */
19686    private void restoreFromXml(XmlPullParser parser, int userId,
19687            String expectedStartTag, BlobXmlRestorer functor)
19688            throws IOException, XmlPullParserException {
19689        int type;
19690        while ((type = parser.next()) != XmlPullParser.START_TAG
19691                && type != XmlPullParser.END_DOCUMENT) {
19692        }
19693        if (type != XmlPullParser.START_TAG) {
19694            // oops didn't find a start tag?!
19695            if (DEBUG_BACKUP) {
19696                Slog.e(TAG, "Didn't find start tag during restore");
19697            }
19698            return;
19699        }
19700Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19701        // this is supposed to be TAG_PREFERRED_BACKUP
19702        if (!expectedStartTag.equals(parser.getName())) {
19703            if (DEBUG_BACKUP) {
19704                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19705            }
19706            return;
19707        }
19708
19709        // skip interfering stuff, then we're aligned with the backing implementation
19710        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19711Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19712        functor.apply(parser, userId);
19713    }
19714
19715    private interface BlobXmlRestorer {
19716        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19717    }
19718
19719    /**
19720     * Non-Binder method, support for the backup/restore mechanism: write the
19721     * full set of preferred activities in its canonical XML format.  Returns the
19722     * XML output as a byte array, or null if there is none.
19723     */
19724    @Override
19725    public byte[] getPreferredActivityBackup(int userId) {
19726        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19727            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19728        }
19729
19730        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19731        try {
19732            final XmlSerializer serializer = new FastXmlSerializer();
19733            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19734            serializer.startDocument(null, true);
19735            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19736
19737            synchronized (mPackages) {
19738                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19739            }
19740
19741            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19742            serializer.endDocument();
19743            serializer.flush();
19744        } catch (Exception e) {
19745            if (DEBUG_BACKUP) {
19746                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19747            }
19748            return null;
19749        }
19750
19751        return dataStream.toByteArray();
19752    }
19753
19754    @Override
19755    public void restorePreferredActivities(byte[] backup, int userId) {
19756        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19757            throw new SecurityException("Only the system may call restorePreferredActivities()");
19758        }
19759
19760        try {
19761            final XmlPullParser parser = Xml.newPullParser();
19762            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19763            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19764                    new BlobXmlRestorer() {
19765                        @Override
19766                        public void apply(XmlPullParser parser, int userId)
19767                                throws XmlPullParserException, IOException {
19768                            synchronized (mPackages) {
19769                                mSettings.readPreferredActivitiesLPw(parser, userId);
19770                            }
19771                        }
19772                    } );
19773        } catch (Exception e) {
19774            if (DEBUG_BACKUP) {
19775                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19776            }
19777        }
19778    }
19779
19780    /**
19781     * Non-Binder method, support for the backup/restore mechanism: write the
19782     * default browser (etc) settings in its canonical XML format.  Returns the default
19783     * browser XML representation as a byte array, or null if there is none.
19784     */
19785    @Override
19786    public byte[] getDefaultAppsBackup(int userId) {
19787        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19788            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19789        }
19790
19791        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19792        try {
19793            final XmlSerializer serializer = new FastXmlSerializer();
19794            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19795            serializer.startDocument(null, true);
19796            serializer.startTag(null, TAG_DEFAULT_APPS);
19797
19798            synchronized (mPackages) {
19799                mSettings.writeDefaultAppsLPr(serializer, userId);
19800            }
19801
19802            serializer.endTag(null, TAG_DEFAULT_APPS);
19803            serializer.endDocument();
19804            serializer.flush();
19805        } catch (Exception e) {
19806            if (DEBUG_BACKUP) {
19807                Slog.e(TAG, "Unable to write default apps for backup", e);
19808            }
19809            return null;
19810        }
19811
19812        return dataStream.toByteArray();
19813    }
19814
19815    @Override
19816    public void restoreDefaultApps(byte[] backup, int userId) {
19817        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19818            throw new SecurityException("Only the system may call restoreDefaultApps()");
19819        }
19820
19821        try {
19822            final XmlPullParser parser = Xml.newPullParser();
19823            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19824            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19825                    new BlobXmlRestorer() {
19826                        @Override
19827                        public void apply(XmlPullParser parser, int userId)
19828                                throws XmlPullParserException, IOException {
19829                            synchronized (mPackages) {
19830                                mSettings.readDefaultAppsLPw(parser, userId);
19831                            }
19832                        }
19833                    } );
19834        } catch (Exception e) {
19835            if (DEBUG_BACKUP) {
19836                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19837            }
19838        }
19839    }
19840
19841    @Override
19842    public byte[] getIntentFilterVerificationBackup(int userId) {
19843        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19844            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19845        }
19846
19847        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19848        try {
19849            final XmlSerializer serializer = new FastXmlSerializer();
19850            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19851            serializer.startDocument(null, true);
19852            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19853
19854            synchronized (mPackages) {
19855                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19856            }
19857
19858            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19859            serializer.endDocument();
19860            serializer.flush();
19861        } catch (Exception e) {
19862            if (DEBUG_BACKUP) {
19863                Slog.e(TAG, "Unable to write default apps for backup", e);
19864            }
19865            return null;
19866        }
19867
19868        return dataStream.toByteArray();
19869    }
19870
19871    @Override
19872    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19873        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19874            throw new SecurityException("Only the system may call restorePreferredActivities()");
19875        }
19876
19877        try {
19878            final XmlPullParser parser = Xml.newPullParser();
19879            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19880            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19881                    new BlobXmlRestorer() {
19882                        @Override
19883                        public void apply(XmlPullParser parser, int userId)
19884                                throws XmlPullParserException, IOException {
19885                            synchronized (mPackages) {
19886                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19887                                mSettings.writeLPr();
19888                            }
19889                        }
19890                    } );
19891        } catch (Exception e) {
19892            if (DEBUG_BACKUP) {
19893                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19894            }
19895        }
19896    }
19897
19898    @Override
19899    public byte[] getPermissionGrantBackup(int userId) {
19900        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19901            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19902        }
19903
19904        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19905        try {
19906            final XmlSerializer serializer = new FastXmlSerializer();
19907            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19908            serializer.startDocument(null, true);
19909            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19910
19911            synchronized (mPackages) {
19912                serializeRuntimePermissionGrantsLPr(serializer, userId);
19913            }
19914
19915            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19916            serializer.endDocument();
19917            serializer.flush();
19918        } catch (Exception e) {
19919            if (DEBUG_BACKUP) {
19920                Slog.e(TAG, "Unable to write default apps for backup", e);
19921            }
19922            return null;
19923        }
19924
19925        return dataStream.toByteArray();
19926    }
19927
19928    @Override
19929    public void restorePermissionGrants(byte[] backup, int userId) {
19930        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19931            throw new SecurityException("Only the system may call restorePermissionGrants()");
19932        }
19933
19934        try {
19935            final XmlPullParser parser = Xml.newPullParser();
19936            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19937            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19938                    new BlobXmlRestorer() {
19939                        @Override
19940                        public void apply(XmlPullParser parser, int userId)
19941                                throws XmlPullParserException, IOException {
19942                            synchronized (mPackages) {
19943                                processRestoredPermissionGrantsLPr(parser, userId);
19944                            }
19945                        }
19946                    } );
19947        } catch (Exception e) {
19948            if (DEBUG_BACKUP) {
19949                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19950            }
19951        }
19952    }
19953
19954    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19955            throws IOException {
19956        serializer.startTag(null, TAG_ALL_GRANTS);
19957
19958        final int N = mSettings.mPackages.size();
19959        for (int i = 0; i < N; i++) {
19960            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19961            boolean pkgGrantsKnown = false;
19962
19963            PermissionsState packagePerms = ps.getPermissionsState();
19964
19965            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19966                final int grantFlags = state.getFlags();
19967                // only look at grants that are not system/policy fixed
19968                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19969                    final boolean isGranted = state.isGranted();
19970                    // And only back up the user-twiddled state bits
19971                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19972                        final String packageName = mSettings.mPackages.keyAt(i);
19973                        if (!pkgGrantsKnown) {
19974                            serializer.startTag(null, TAG_GRANT);
19975                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19976                            pkgGrantsKnown = true;
19977                        }
19978
19979                        final boolean userSet =
19980                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19981                        final boolean userFixed =
19982                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19983                        final boolean revoke =
19984                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19985
19986                        serializer.startTag(null, TAG_PERMISSION);
19987                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19988                        if (isGranted) {
19989                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19990                        }
19991                        if (userSet) {
19992                            serializer.attribute(null, ATTR_USER_SET, "true");
19993                        }
19994                        if (userFixed) {
19995                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19996                        }
19997                        if (revoke) {
19998                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19999                        }
20000                        serializer.endTag(null, TAG_PERMISSION);
20001                    }
20002                }
20003            }
20004
20005            if (pkgGrantsKnown) {
20006                serializer.endTag(null, TAG_GRANT);
20007            }
20008        }
20009
20010        serializer.endTag(null, TAG_ALL_GRANTS);
20011    }
20012
20013    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20014            throws XmlPullParserException, IOException {
20015        String pkgName = null;
20016        int outerDepth = parser.getDepth();
20017        int type;
20018        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20019                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20020            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20021                continue;
20022            }
20023
20024            final String tagName = parser.getName();
20025            if (tagName.equals(TAG_GRANT)) {
20026                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20027                if (DEBUG_BACKUP) {
20028                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20029                }
20030            } else if (tagName.equals(TAG_PERMISSION)) {
20031
20032                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20033                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20034
20035                int newFlagSet = 0;
20036                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20037                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20038                }
20039                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20040                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20041                }
20042                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20043                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20044                }
20045                if (DEBUG_BACKUP) {
20046                    Slog.v(TAG, "  + Restoring grant:"
20047                            + " pkg=" + pkgName
20048                            + " perm=" + permName
20049                            + " granted=" + isGranted
20050                            + " bits=0x" + Integer.toHexString(newFlagSet));
20051                }
20052                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20053                if (ps != null) {
20054                    // Already installed so we apply the grant immediately
20055                    if (DEBUG_BACKUP) {
20056                        Slog.v(TAG, "        + already installed; applying");
20057                    }
20058                    PermissionsState perms = ps.getPermissionsState();
20059                    BasePermission bp =
20060                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20061                    if (bp != null) {
20062                        if (isGranted) {
20063                            perms.grantRuntimePermission(bp, userId);
20064                        }
20065                        if (newFlagSet != 0) {
20066                            perms.updatePermissionFlags(
20067                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20068                        }
20069                    }
20070                } else {
20071                    // Need to wait for post-restore install to apply the grant
20072                    if (DEBUG_BACKUP) {
20073                        Slog.v(TAG, "        - not yet installed; saving for later");
20074                    }
20075                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20076                            isGranted, newFlagSet, userId);
20077                }
20078            } else {
20079                PackageManagerService.reportSettingsProblem(Log.WARN,
20080                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20081                XmlUtils.skipCurrentTag(parser);
20082            }
20083        }
20084
20085        scheduleWriteSettingsLocked();
20086        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20087    }
20088
20089    @Override
20090    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20091            int sourceUserId, int targetUserId, int flags) {
20092        mContext.enforceCallingOrSelfPermission(
20093                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20094        int callingUid = Binder.getCallingUid();
20095        enforceOwnerRights(ownerPackage, callingUid);
20096        PackageManagerServiceUtils.enforceShellRestriction(
20097                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20098        if (intentFilter.countActions() == 0) {
20099            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20100            return;
20101        }
20102        synchronized (mPackages) {
20103            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20104                    ownerPackage, targetUserId, flags);
20105            CrossProfileIntentResolver resolver =
20106                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20107            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20108            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20109            if (existing != null) {
20110                int size = existing.size();
20111                for (int i = 0; i < size; i++) {
20112                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20113                        return;
20114                    }
20115                }
20116            }
20117            resolver.addFilter(newFilter);
20118            scheduleWritePackageRestrictionsLocked(sourceUserId);
20119        }
20120    }
20121
20122    @Override
20123    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20124        mContext.enforceCallingOrSelfPermission(
20125                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20126        final int callingUid = Binder.getCallingUid();
20127        enforceOwnerRights(ownerPackage, callingUid);
20128        PackageManagerServiceUtils.enforceShellRestriction(
20129                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20130        synchronized (mPackages) {
20131            CrossProfileIntentResolver resolver =
20132                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20133            ArraySet<CrossProfileIntentFilter> set =
20134                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20135            for (CrossProfileIntentFilter filter : set) {
20136                if (filter.getOwnerPackage().equals(ownerPackage)) {
20137                    resolver.removeFilter(filter);
20138                }
20139            }
20140            scheduleWritePackageRestrictionsLocked(sourceUserId);
20141        }
20142    }
20143
20144    // Enforcing that callingUid is owning pkg on userId
20145    private void enforceOwnerRights(String pkg, int callingUid) {
20146        // The system owns everything.
20147        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20148            return;
20149        }
20150        final int callingUserId = UserHandle.getUserId(callingUid);
20151        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20152        if (pi == null) {
20153            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20154                    + callingUserId);
20155        }
20156        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20157            throw new SecurityException("Calling uid " + callingUid
20158                    + " does not own package " + pkg);
20159        }
20160    }
20161
20162    @Override
20163    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20164        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20165            return null;
20166        }
20167        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20168    }
20169
20170    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20171        UserManagerService ums = UserManagerService.getInstance();
20172        if (ums != null) {
20173            final UserInfo parent = ums.getProfileParent(userId);
20174            final int launcherUid = (parent != null) ? parent.id : userId;
20175            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20176            if (launcherComponent != null) {
20177                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20178                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20179                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20180                        .setPackage(launcherComponent.getPackageName());
20181                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20182            }
20183        }
20184    }
20185
20186    /**
20187     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20188     * then reports the most likely home activity or null if there are more than one.
20189     */
20190    private ComponentName getDefaultHomeActivity(int userId) {
20191        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20192        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20193        if (cn != null) {
20194            return cn;
20195        }
20196
20197        // Find the launcher with the highest priority and return that component if there are no
20198        // other home activity with the same priority.
20199        int lastPriority = Integer.MIN_VALUE;
20200        ComponentName lastComponent = null;
20201        final int size = allHomeCandidates.size();
20202        for (int i = 0; i < size; i++) {
20203            final ResolveInfo ri = allHomeCandidates.get(i);
20204            if (ri.priority > lastPriority) {
20205                lastComponent = ri.activityInfo.getComponentName();
20206                lastPriority = ri.priority;
20207            } else if (ri.priority == lastPriority) {
20208                // Two components found with same priority.
20209                lastComponent = null;
20210            }
20211        }
20212        return lastComponent;
20213    }
20214
20215    private Intent getHomeIntent() {
20216        Intent intent = new Intent(Intent.ACTION_MAIN);
20217        intent.addCategory(Intent.CATEGORY_HOME);
20218        intent.addCategory(Intent.CATEGORY_DEFAULT);
20219        return intent;
20220    }
20221
20222    private IntentFilter getHomeFilter() {
20223        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20224        filter.addCategory(Intent.CATEGORY_HOME);
20225        filter.addCategory(Intent.CATEGORY_DEFAULT);
20226        return filter;
20227    }
20228
20229    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20230            int userId) {
20231        Intent intent  = getHomeIntent();
20232        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20233                PackageManager.GET_META_DATA, userId);
20234        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20235                true, false, false, userId);
20236
20237        allHomeCandidates.clear();
20238        if (list != null) {
20239            for (ResolveInfo ri : list) {
20240                allHomeCandidates.add(ri);
20241            }
20242        }
20243        return (preferred == null || preferred.activityInfo == null)
20244                ? null
20245                : new ComponentName(preferred.activityInfo.packageName,
20246                        preferred.activityInfo.name);
20247    }
20248
20249    @Override
20250    public void setHomeActivity(ComponentName comp, int userId) {
20251        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20252            return;
20253        }
20254        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20255        getHomeActivitiesAsUser(homeActivities, userId);
20256
20257        boolean found = false;
20258
20259        final int size = homeActivities.size();
20260        final ComponentName[] set = new ComponentName[size];
20261        for (int i = 0; i < size; i++) {
20262            final ResolveInfo candidate = homeActivities.get(i);
20263            final ActivityInfo info = candidate.activityInfo;
20264            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20265            set[i] = activityName;
20266            if (!found && activityName.equals(comp)) {
20267                found = true;
20268            }
20269        }
20270        if (!found) {
20271            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20272                    + userId);
20273        }
20274        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20275                set, comp, userId);
20276    }
20277
20278    private @Nullable String getSetupWizardPackageName() {
20279        final Intent intent = new Intent(Intent.ACTION_MAIN);
20280        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20281
20282        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20283                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20284                        | MATCH_DISABLED_COMPONENTS,
20285                UserHandle.myUserId());
20286        if (matches.size() == 1) {
20287            return matches.get(0).getComponentInfo().packageName;
20288        } else {
20289            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20290                    + ": matches=" + matches);
20291            return null;
20292        }
20293    }
20294
20295    private @Nullable String getStorageManagerPackageName() {
20296        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20297
20298        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20299                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20300                        | MATCH_DISABLED_COMPONENTS,
20301                UserHandle.myUserId());
20302        if (matches.size() == 1) {
20303            return matches.get(0).getComponentInfo().packageName;
20304        } else {
20305            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20306                    + matches.size() + ": matches=" + matches);
20307            return null;
20308        }
20309    }
20310
20311    @Override
20312    public String getSystemTextClassifierPackageName() {
20313        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20314    }
20315
20316    @Override
20317    public void setApplicationEnabledSetting(String appPackageName,
20318            int newState, int flags, int userId, String callingPackage) {
20319        if (!sUserManager.exists(userId)) return;
20320        if (callingPackage == null) {
20321            callingPackage = Integer.toString(Binder.getCallingUid());
20322        }
20323        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20324    }
20325
20326    @Override
20327    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20328        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20329        synchronized (mPackages) {
20330            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20331            if (pkgSetting != null) {
20332                pkgSetting.setUpdateAvailable(updateAvailable);
20333            }
20334        }
20335    }
20336
20337    @Override
20338    public void setComponentEnabledSetting(ComponentName componentName,
20339            int newState, int flags, int userId) {
20340        if (!sUserManager.exists(userId)) return;
20341        setEnabledSetting(componentName.getPackageName(),
20342                componentName.getClassName(), newState, flags, userId, null);
20343    }
20344
20345    private void setEnabledSetting(final String packageName, String className, int newState,
20346            final int flags, int userId, String callingPackage) {
20347        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20348              || newState == COMPONENT_ENABLED_STATE_ENABLED
20349              || newState == COMPONENT_ENABLED_STATE_DISABLED
20350              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20351              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20352            throw new IllegalArgumentException("Invalid new component state: "
20353                    + newState);
20354        }
20355        PackageSetting pkgSetting;
20356        final int callingUid = Binder.getCallingUid();
20357        final int permission;
20358        if (callingUid == Process.SYSTEM_UID) {
20359            permission = PackageManager.PERMISSION_GRANTED;
20360        } else {
20361            permission = mContext.checkCallingOrSelfPermission(
20362                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20363        }
20364        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20365                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20366        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20367        boolean sendNow = false;
20368        boolean isApp = (className == null);
20369        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20370        String componentName = isApp ? packageName : className;
20371        int packageUid = -1;
20372        ArrayList<String> components;
20373
20374        // reader
20375        synchronized (mPackages) {
20376            pkgSetting = mSettings.mPackages.get(packageName);
20377            if (pkgSetting == null) {
20378                if (!isCallerInstantApp) {
20379                    if (className == null) {
20380                        throw new IllegalArgumentException("Unknown package: " + packageName);
20381                    }
20382                    throw new IllegalArgumentException(
20383                            "Unknown component: " + packageName + "/" + className);
20384                } else {
20385                    // throw SecurityException to prevent leaking package information
20386                    throw new SecurityException(
20387                            "Attempt to change component state; "
20388                            + "pid=" + Binder.getCallingPid()
20389                            + ", uid=" + callingUid
20390                            + (className == null
20391                                    ? ", package=" + packageName
20392                                    : ", component=" + packageName + "/" + className));
20393                }
20394            }
20395        }
20396
20397        // Limit who can change which apps
20398        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20399            // Don't allow apps that don't have permission to modify other apps
20400            if (!allowedByPermission
20401                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20402                throw new SecurityException(
20403                        "Attempt to change component state; "
20404                        + "pid=" + Binder.getCallingPid()
20405                        + ", uid=" + callingUid
20406                        + (className == null
20407                                ? ", package=" + packageName
20408                                : ", component=" + packageName + "/" + className));
20409            }
20410            // Don't allow changing protected packages.
20411            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20412                throw new SecurityException("Cannot disable a protected package: " + packageName);
20413            }
20414        }
20415
20416        synchronized (mPackages) {
20417            if (callingUid == Process.SHELL_UID
20418                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20419                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20420                // unless it is a test package.
20421                int oldState = pkgSetting.getEnabled(userId);
20422                if (className == null
20423                        &&
20424                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20425                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20426                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20427                        &&
20428                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20429                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20430                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20431                    // ok
20432                } else {
20433                    throw new SecurityException(
20434                            "Shell cannot change component state for " + packageName + "/"
20435                                    + className + " to " + newState);
20436                }
20437            }
20438        }
20439        if (className == null) {
20440            // We're dealing with an application/package level state change
20441            synchronized (mPackages) {
20442                if (pkgSetting.getEnabled(userId) == newState) {
20443                    // Nothing to do
20444                    return;
20445                }
20446            }
20447            // If we're enabling a system stub, there's a little more work to do.
20448            // Prior to enabling the package, we need to decompress the APK(s) to the
20449            // data partition and then replace the version on the system partition.
20450            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20451            final boolean isSystemStub = deletedPkg.isStub
20452                    && deletedPkg.isSystem();
20453            if (isSystemStub
20454                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20455                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20456                final File codePath = decompressPackage(deletedPkg);
20457                if (codePath == null) {
20458                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20459                    return;
20460                }
20461                // TODO remove direct parsing of the package object during internal cleanup
20462                // of scan package
20463                // We need to call parse directly here for no other reason than we need
20464                // the new package in order to disable the old one [we use the information
20465                // for some internal optimization to optionally create a new package setting
20466                // object on replace]. However, we can't get the package from the scan
20467                // because the scan modifies live structures and we need to remove the
20468                // old [system] package from the system before a scan can be attempted.
20469                // Once scan is indempotent we can remove this parse and use the package
20470                // object we scanned, prior to adding it to package settings.
20471                final PackageParser pp = new PackageParser();
20472                pp.setSeparateProcesses(mSeparateProcesses);
20473                pp.setDisplayMetrics(mMetrics);
20474                pp.setCallback(mPackageParserCallback);
20475                final PackageParser.Package tmpPkg;
20476                try {
20477                    final @ParseFlags int parseFlags = mDefParseFlags
20478                            | PackageParser.PARSE_MUST_BE_APK
20479                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20480                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20481                } catch (PackageParserException e) {
20482                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20483                    return;
20484                }
20485                synchronized (mInstallLock) {
20486                    // Disable the stub and remove any package entries
20487                    removePackageLI(deletedPkg, true);
20488                    synchronized (mPackages) {
20489                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20490                    }
20491                    final PackageParser.Package pkg;
20492                    try (PackageFreezer freezer =
20493                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20494                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20495                                | PackageParser.PARSE_ENFORCE_CODE;
20496                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20497                                0 /*currentTime*/, null /*user*/);
20498                        prepareAppDataAfterInstallLIF(pkg);
20499                        synchronized (mPackages) {
20500                            try {
20501                                updateSharedLibrariesLPr(pkg, null);
20502                            } catch (PackageManagerException e) {
20503                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20504                            }
20505                            mPermissionManager.updatePermissions(
20506                                    pkg.packageName, pkg, true, mPackages.values(),
20507                                    mPermissionCallback);
20508                            mSettings.writeLPr();
20509                        }
20510                    } catch (PackageManagerException e) {
20511                        // Whoops! Something went wrong; try to roll back to the stub
20512                        Slog.w(TAG, "Failed to install compressed system package:"
20513                                + pkgSetting.name, e);
20514                        // Remove the failed install
20515                        removeCodePathLI(codePath);
20516
20517                        // Install the system package
20518                        try (PackageFreezer freezer =
20519                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20520                            synchronized (mPackages) {
20521                                // NOTE: The system package always needs to be enabled; even
20522                                // if it's for a compressed stub. If we don't, installing the
20523                                // system package fails during scan [scanning checks the disabled
20524                                // packages]. We will reverse this later, after we've "installed"
20525                                // the stub.
20526                                // This leaves us in a fragile state; the stub should never be
20527                                // enabled, so, cross your fingers and hope nothing goes wrong
20528                                // until we can disable the package later.
20529                                enableSystemPackageLPw(deletedPkg);
20530                            }
20531                            installPackageFromSystemLIF(deletedPkg.codePath,
20532                                    false /*isPrivileged*/, null /*allUserHandles*/,
20533                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20534                                    true /*writeSettings*/);
20535                        } catch (PackageManagerException pme) {
20536                            Slog.w(TAG, "Failed to restore system package:"
20537                                    + deletedPkg.packageName, pme);
20538                        } finally {
20539                            synchronized (mPackages) {
20540                                mSettings.disableSystemPackageLPw(
20541                                        deletedPkg.packageName, true /*replaced*/);
20542                                mSettings.writeLPr();
20543                            }
20544                        }
20545                        return;
20546                    }
20547                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20548                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20549                    mDexManager.notifyPackageUpdated(pkg.packageName,
20550                            pkg.baseCodePath, pkg.splitCodePaths);
20551                }
20552            }
20553            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20554                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20555                // Don't care about who enables an app.
20556                callingPackage = null;
20557            }
20558            synchronized (mPackages) {
20559                pkgSetting.setEnabled(newState, userId, callingPackage);
20560            }
20561        } else {
20562            synchronized (mPackages) {
20563                // We're dealing with a component level state change
20564                // First, verify that this is a valid class name.
20565                PackageParser.Package pkg = pkgSetting.pkg;
20566                if (pkg == null || !pkg.hasComponentClassName(className)) {
20567                    if (pkg != null &&
20568                            pkg.applicationInfo.targetSdkVersion >=
20569                                    Build.VERSION_CODES.JELLY_BEAN) {
20570                        throw new IllegalArgumentException("Component class " + className
20571                                + " does not exist in " + packageName);
20572                    } else {
20573                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20574                                + className + " does not exist in " + packageName);
20575                    }
20576                }
20577                switch (newState) {
20578                    case COMPONENT_ENABLED_STATE_ENABLED:
20579                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20580                            return;
20581                        }
20582                        break;
20583                    case COMPONENT_ENABLED_STATE_DISABLED:
20584                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20585                            return;
20586                        }
20587                        break;
20588                    case COMPONENT_ENABLED_STATE_DEFAULT:
20589                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20590                            return;
20591                        }
20592                        break;
20593                    default:
20594                        Slog.e(TAG, "Invalid new component state: " + newState);
20595                        return;
20596                }
20597            }
20598        }
20599        synchronized (mPackages) {
20600            scheduleWritePackageRestrictionsLocked(userId);
20601            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20602            final long callingId = Binder.clearCallingIdentity();
20603            try {
20604                updateInstantAppInstallerLocked(packageName);
20605            } finally {
20606                Binder.restoreCallingIdentity(callingId);
20607            }
20608            components = mPendingBroadcasts.get(userId, packageName);
20609            final boolean newPackage = components == null;
20610            if (newPackage) {
20611                components = new ArrayList<String>();
20612            }
20613            if (!components.contains(componentName)) {
20614                components.add(componentName);
20615            }
20616            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20617                sendNow = true;
20618                // Purge entry from pending broadcast list if another one exists already
20619                // since we are sending one right away.
20620                mPendingBroadcasts.remove(userId, packageName);
20621            } else {
20622                if (newPackage) {
20623                    mPendingBroadcasts.put(userId, packageName, components);
20624                }
20625                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20626                    // Schedule a message
20627                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20628                }
20629            }
20630        }
20631
20632        long callingId = Binder.clearCallingIdentity();
20633        try {
20634            if (sendNow) {
20635                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20636                sendPackageChangedBroadcast(packageName,
20637                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20638            }
20639        } finally {
20640            Binder.restoreCallingIdentity(callingId);
20641        }
20642    }
20643
20644    @Override
20645    public void flushPackageRestrictionsAsUser(int userId) {
20646        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20647            return;
20648        }
20649        if (!sUserManager.exists(userId)) {
20650            return;
20651        }
20652        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20653                false /* checkShell */, "flushPackageRestrictions");
20654        synchronized (mPackages) {
20655            mSettings.writePackageRestrictionsLPr(userId);
20656            mDirtyUsers.remove(userId);
20657            if (mDirtyUsers.isEmpty()) {
20658                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20659            }
20660        }
20661    }
20662
20663    private void sendPackageChangedBroadcast(String packageName,
20664            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20665        if (DEBUG_INSTALL)
20666            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20667                    + componentNames);
20668        Bundle extras = new Bundle(4);
20669        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20670        String nameList[] = new String[componentNames.size()];
20671        componentNames.toArray(nameList);
20672        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20673        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20674        extras.putInt(Intent.EXTRA_UID, packageUid);
20675        // If this is not reporting a change of the overall package, then only send it
20676        // to registered receivers.  We don't want to launch a swath of apps for every
20677        // little component state change.
20678        final int flags = !componentNames.contains(packageName)
20679                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20680        final int userId = UserHandle.getUserId(packageUid);
20681        final boolean isInstantApp = isInstantApp(packageName, userId);
20682        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20683        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20684        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20685                userIds, instantUserIds);
20686    }
20687
20688    @Override
20689    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20690        if (!sUserManager.exists(userId)) return;
20691        final int callingUid = Binder.getCallingUid();
20692        if (getInstantAppPackageName(callingUid) != null) {
20693            return;
20694        }
20695        final int permission = mContext.checkCallingOrSelfPermission(
20696                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20697        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20698        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20699                true /* requireFullPermission */, true /* checkShell */, "stop package");
20700        // writer
20701        synchronized (mPackages) {
20702            final PackageSetting ps = mSettings.mPackages.get(packageName);
20703            if (!filterAppAccessLPr(ps, callingUid, userId)
20704                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20705                            allowedByPermission, callingUid, userId)) {
20706                scheduleWritePackageRestrictionsLocked(userId);
20707            }
20708        }
20709    }
20710
20711    @Override
20712    public String getInstallerPackageName(String packageName) {
20713        final int callingUid = Binder.getCallingUid();
20714        synchronized (mPackages) {
20715            final PackageSetting ps = mSettings.mPackages.get(packageName);
20716            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20717                return null;
20718            }
20719            return mSettings.getInstallerPackageNameLPr(packageName);
20720        }
20721    }
20722
20723    public boolean isOrphaned(String packageName) {
20724        // reader
20725        synchronized (mPackages) {
20726            return mSettings.isOrphaned(packageName);
20727        }
20728    }
20729
20730    @Override
20731    public int getApplicationEnabledSetting(String packageName, int userId) {
20732        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20733        int callingUid = Binder.getCallingUid();
20734        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20735                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20736        // reader
20737        synchronized (mPackages) {
20738            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20739                return COMPONENT_ENABLED_STATE_DISABLED;
20740            }
20741            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20742        }
20743    }
20744
20745    @Override
20746    public int getComponentEnabledSetting(ComponentName component, int userId) {
20747        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20748        int callingUid = Binder.getCallingUid();
20749        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20750                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20751        synchronized (mPackages) {
20752            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20753                    component, TYPE_UNKNOWN, userId)) {
20754                return COMPONENT_ENABLED_STATE_DISABLED;
20755            }
20756            return mSettings.getComponentEnabledSettingLPr(component, userId);
20757        }
20758    }
20759
20760    @Override
20761    public void enterSafeMode() {
20762        enforceSystemOrRoot("Only the system can request entering safe mode");
20763
20764        if (!mSystemReady) {
20765            mSafeMode = true;
20766        }
20767    }
20768
20769    @Override
20770    public void systemReady() {
20771        enforceSystemOrRoot("Only the system can claim the system is ready");
20772
20773        mSystemReady = true;
20774        final ContentResolver resolver = mContext.getContentResolver();
20775        ContentObserver co = new ContentObserver(mHandler) {
20776            @Override
20777            public void onChange(boolean selfChange) {
20778                mWebInstantAppsDisabled =
20779                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20780                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20781            }
20782        };
20783        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20784                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20785                false, co, UserHandle.USER_SYSTEM);
20786        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20787                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20788        co.onChange(true);
20789
20790        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20791        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20792        // it is done.
20793        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20794            @Override
20795            public void onChange(boolean selfChange) {
20796                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20797                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20798                        oobEnabled == 1 ? "true" : "false");
20799            }
20800        };
20801        mContext.getContentResolver().registerContentObserver(
20802                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20803                UserHandle.USER_SYSTEM);
20804        // At boot, restore the value from the setting, which persists across reboot.
20805        privAppOobObserver.onChange(true);
20806
20807        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20808        // disabled after already being started.
20809        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20810                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20811
20812        // Read the compatibilty setting when the system is ready.
20813        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20814                mContext.getContentResolver(),
20815                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20816        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20817        if (DEBUG_SETTINGS) {
20818            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20819        }
20820
20821        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20822
20823        synchronized (mPackages) {
20824            // Verify that all of the preferred activity components actually
20825            // exist.  It is possible for applications to be updated and at
20826            // that point remove a previously declared activity component that
20827            // had been set as a preferred activity.  We try to clean this up
20828            // the next time we encounter that preferred activity, but it is
20829            // possible for the user flow to never be able to return to that
20830            // situation so here we do a sanity check to make sure we haven't
20831            // left any junk around.
20832            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20833            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20834                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20835                removed.clear();
20836                for (PreferredActivity pa : pir.filterSet()) {
20837                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20838                        removed.add(pa);
20839                    }
20840                }
20841                if (removed.size() > 0) {
20842                    for (int r=0; r<removed.size(); r++) {
20843                        PreferredActivity pa = removed.get(r);
20844                        Slog.w(TAG, "Removing dangling preferred activity: "
20845                                + pa.mPref.mComponent);
20846                        pir.removeFilter(pa);
20847                    }
20848                    mSettings.writePackageRestrictionsLPr(
20849                            mSettings.mPreferredActivities.keyAt(i));
20850                }
20851            }
20852
20853            for (int userId : UserManagerService.getInstance().getUserIds()) {
20854                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20855                    grantPermissionsUserIds = ArrayUtils.appendInt(
20856                            grantPermissionsUserIds, userId);
20857                }
20858            }
20859        }
20860        sUserManager.systemReady();
20861        // If we upgraded grant all default permissions before kicking off.
20862        for (int userId : grantPermissionsUserIds) {
20863            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20864        }
20865
20866        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20867            // If we did not grant default permissions, we preload from this the
20868            // default permission exceptions lazily to ensure we don't hit the
20869            // disk on a new user creation.
20870            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20871        }
20872
20873        // Now that we've scanned all packages, and granted any default
20874        // permissions, ensure permissions are updated. Beware of dragons if you
20875        // try optimizing this.
20876        synchronized (mPackages) {
20877            mPermissionManager.updateAllPermissions(
20878                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20879                    mPermissionCallback);
20880        }
20881
20882        // Kick off any messages waiting for system ready
20883        if (mPostSystemReadyMessages != null) {
20884            for (Message msg : mPostSystemReadyMessages) {
20885                msg.sendToTarget();
20886            }
20887            mPostSystemReadyMessages = null;
20888        }
20889
20890        // Watch for external volumes that come and go over time
20891        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20892        storage.registerListener(mStorageListener);
20893
20894        mInstallerService.systemReady();
20895        mPackageDexOptimizer.systemReady();
20896
20897        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20898                StorageManagerInternal.class);
20899        StorageManagerInternal.addExternalStoragePolicy(
20900                new StorageManagerInternal.ExternalStorageMountPolicy() {
20901            @Override
20902            public int getMountMode(int uid, String packageName) {
20903                if (Process.isIsolated(uid)) {
20904                    return Zygote.MOUNT_EXTERNAL_NONE;
20905                }
20906                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20907                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20908                }
20909                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20910                    return Zygote.MOUNT_EXTERNAL_READ;
20911                }
20912                return Zygote.MOUNT_EXTERNAL_WRITE;
20913            }
20914
20915            @Override
20916            public boolean hasExternalStorage(int uid, String packageName) {
20917                return true;
20918            }
20919        });
20920
20921        // Now that we're mostly running, clean up stale users and apps
20922        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20923        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20924
20925        mPermissionManager.systemReady();
20926
20927        if (mInstantAppResolverConnection != null) {
20928            mContext.registerReceiver(new BroadcastReceiver() {
20929                @Override
20930                public void onReceive(Context context, Intent intent) {
20931                    mInstantAppResolverConnection.optimisticBind();
20932                    mContext.unregisterReceiver(this);
20933                }
20934            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
20935        }
20936    }
20937
20938    public void waitForAppDataPrepared() {
20939        if (mPrepareAppDataFuture == null) {
20940            return;
20941        }
20942        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20943        mPrepareAppDataFuture = null;
20944    }
20945
20946    @Override
20947    public boolean isSafeMode() {
20948        // allow instant applications
20949        return mSafeMode;
20950    }
20951
20952    @Override
20953    public boolean hasSystemUidErrors() {
20954        // allow instant applications
20955        return mHasSystemUidErrors;
20956    }
20957
20958    static String arrayToString(int[] array) {
20959        StringBuffer buf = new StringBuffer(128);
20960        buf.append('[');
20961        if (array != null) {
20962            for (int i=0; i<array.length; i++) {
20963                if (i > 0) buf.append(", ");
20964                buf.append(array[i]);
20965            }
20966        }
20967        buf.append(']');
20968        return buf.toString();
20969    }
20970
20971    @Override
20972    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20973            FileDescriptor err, String[] args, ShellCallback callback,
20974            ResultReceiver resultReceiver) {
20975        (new PackageManagerShellCommand(this)).exec(
20976                this, in, out, err, args, callback, resultReceiver);
20977    }
20978
20979    @Override
20980    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20981        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20982
20983        DumpState dumpState = new DumpState();
20984        boolean fullPreferred = false;
20985        boolean checkin = false;
20986
20987        String packageName = null;
20988        ArraySet<String> permissionNames = null;
20989
20990        int opti = 0;
20991        while (opti < args.length) {
20992            String opt = args[opti];
20993            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20994                break;
20995            }
20996            opti++;
20997
20998            if ("-a".equals(opt)) {
20999                // Right now we only know how to print all.
21000            } else if ("-h".equals(opt)) {
21001                pw.println("Package manager dump options:");
21002                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21003                pw.println("    --checkin: dump for a checkin");
21004                pw.println("    -f: print details of intent filters");
21005                pw.println("    -h: print this help");
21006                pw.println("  cmd may be one of:");
21007                pw.println("    l[ibraries]: list known shared libraries");
21008                pw.println("    f[eatures]: list device features");
21009                pw.println("    k[eysets]: print known keysets");
21010                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21011                pw.println("    perm[issions]: dump permissions");
21012                pw.println("    permission [name ...]: dump declaration and use of given permission");
21013                pw.println("    pref[erred]: print preferred package settings");
21014                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21015                pw.println("    prov[iders]: dump content providers");
21016                pw.println("    p[ackages]: dump installed packages");
21017                pw.println("    s[hared-users]: dump shared user IDs");
21018                pw.println("    m[essages]: print collected runtime messages");
21019                pw.println("    v[erifiers]: print package verifier info");
21020                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21021                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21022                pw.println("    version: print database version info");
21023                pw.println("    write: write current settings now");
21024                pw.println("    installs: details about install sessions");
21025                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21026                pw.println("    dexopt: dump dexopt state");
21027                pw.println("    compiler-stats: dump compiler statistics");
21028                pw.println("    service-permissions: dump permissions required by services");
21029                pw.println("    <package.name>: info about given package");
21030                return;
21031            } else if ("--checkin".equals(opt)) {
21032                checkin = true;
21033            } else if ("-f".equals(opt)) {
21034                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21035            } else if ("--proto".equals(opt)) {
21036                dumpProto(fd);
21037                return;
21038            } else {
21039                pw.println("Unknown argument: " + opt + "; use -h for help");
21040            }
21041        }
21042
21043        // Is the caller requesting to dump a particular piece of data?
21044        if (opti < args.length) {
21045            String cmd = args[opti];
21046            opti++;
21047            // Is this a package name?
21048            if ("android".equals(cmd) || cmd.contains(".")) {
21049                packageName = cmd;
21050                // When dumping a single package, we always dump all of its
21051                // filter information since the amount of data will be reasonable.
21052                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21053            } else if ("check-permission".equals(cmd)) {
21054                if (opti >= args.length) {
21055                    pw.println("Error: check-permission missing permission argument");
21056                    return;
21057                }
21058                String perm = args[opti];
21059                opti++;
21060                if (opti >= args.length) {
21061                    pw.println("Error: check-permission missing package argument");
21062                    return;
21063                }
21064
21065                String pkg = args[opti];
21066                opti++;
21067                int user = UserHandle.getUserId(Binder.getCallingUid());
21068                if (opti < args.length) {
21069                    try {
21070                        user = Integer.parseInt(args[opti]);
21071                    } catch (NumberFormatException e) {
21072                        pw.println("Error: check-permission user argument is not a number: "
21073                                + args[opti]);
21074                        return;
21075                    }
21076                }
21077
21078                // Normalize package name to handle renamed packages and static libs
21079                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21080
21081                pw.println(checkPermission(perm, pkg, user));
21082                return;
21083            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21084                dumpState.setDump(DumpState.DUMP_LIBS);
21085            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21086                dumpState.setDump(DumpState.DUMP_FEATURES);
21087            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21088                if (opti >= args.length) {
21089                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21090                            | DumpState.DUMP_SERVICE_RESOLVERS
21091                            | DumpState.DUMP_RECEIVER_RESOLVERS
21092                            | DumpState.DUMP_CONTENT_RESOLVERS);
21093                } else {
21094                    while (opti < args.length) {
21095                        String name = args[opti];
21096                        if ("a".equals(name) || "activity".equals(name)) {
21097                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21098                        } else if ("s".equals(name) || "service".equals(name)) {
21099                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21100                        } else if ("r".equals(name) || "receiver".equals(name)) {
21101                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21102                        } else if ("c".equals(name) || "content".equals(name)) {
21103                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21104                        } else {
21105                            pw.println("Error: unknown resolver table type: " + name);
21106                            return;
21107                        }
21108                        opti++;
21109                    }
21110                }
21111            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21112                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21113            } else if ("permission".equals(cmd)) {
21114                if (opti >= args.length) {
21115                    pw.println("Error: permission requires permission name");
21116                    return;
21117                }
21118                permissionNames = new ArraySet<>();
21119                while (opti < args.length) {
21120                    permissionNames.add(args[opti]);
21121                    opti++;
21122                }
21123                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21124                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21125            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21126                dumpState.setDump(DumpState.DUMP_PREFERRED);
21127            } else if ("preferred-xml".equals(cmd)) {
21128                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21129                if (opti < args.length && "--full".equals(args[opti])) {
21130                    fullPreferred = true;
21131                    opti++;
21132                }
21133            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21134                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21135            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21136                dumpState.setDump(DumpState.DUMP_PACKAGES);
21137            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21138                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21139            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21140                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21141            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21142                dumpState.setDump(DumpState.DUMP_MESSAGES);
21143            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21144                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21145            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21146                    || "intent-filter-verifiers".equals(cmd)) {
21147                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21148            } else if ("version".equals(cmd)) {
21149                dumpState.setDump(DumpState.DUMP_VERSION);
21150            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21151                dumpState.setDump(DumpState.DUMP_KEYSETS);
21152            } else if ("installs".equals(cmd)) {
21153                dumpState.setDump(DumpState.DUMP_INSTALLS);
21154            } else if ("frozen".equals(cmd)) {
21155                dumpState.setDump(DumpState.DUMP_FROZEN);
21156            } else if ("volumes".equals(cmd)) {
21157                dumpState.setDump(DumpState.DUMP_VOLUMES);
21158            } else if ("dexopt".equals(cmd)) {
21159                dumpState.setDump(DumpState.DUMP_DEXOPT);
21160            } else if ("compiler-stats".equals(cmd)) {
21161                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21162            } else if ("changes".equals(cmd)) {
21163                dumpState.setDump(DumpState.DUMP_CHANGES);
21164            } else if ("service-permissions".equals(cmd)) {
21165                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21166            } else if ("write".equals(cmd)) {
21167                synchronized (mPackages) {
21168                    mSettings.writeLPr();
21169                    pw.println("Settings written.");
21170                    return;
21171                }
21172            }
21173        }
21174
21175        if (checkin) {
21176            pw.println("vers,1");
21177        }
21178
21179        // reader
21180        synchronized (mPackages) {
21181            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21182                if (!checkin) {
21183                    if (dumpState.onTitlePrinted())
21184                        pw.println();
21185                    pw.println("Database versions:");
21186                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21187                }
21188            }
21189
21190            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21191                if (!checkin) {
21192                    if (dumpState.onTitlePrinted())
21193                        pw.println();
21194                    pw.println("Verifiers:");
21195                    pw.print("  Required: ");
21196                    pw.print(mRequiredVerifierPackage);
21197                    pw.print(" (uid=");
21198                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21199                            UserHandle.USER_SYSTEM));
21200                    pw.println(")");
21201                } else if (mRequiredVerifierPackage != null) {
21202                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21203                    pw.print(",");
21204                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21205                            UserHandle.USER_SYSTEM));
21206                }
21207            }
21208
21209            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21210                    packageName == null) {
21211                if (mIntentFilterVerifierComponent != null) {
21212                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21213                    if (!checkin) {
21214                        if (dumpState.onTitlePrinted())
21215                            pw.println();
21216                        pw.println("Intent Filter Verifier:");
21217                        pw.print("  Using: ");
21218                        pw.print(verifierPackageName);
21219                        pw.print(" (uid=");
21220                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21221                                UserHandle.USER_SYSTEM));
21222                        pw.println(")");
21223                    } else if (verifierPackageName != null) {
21224                        pw.print("ifv,"); pw.print(verifierPackageName);
21225                        pw.print(",");
21226                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21227                                UserHandle.USER_SYSTEM));
21228                    }
21229                } else {
21230                    pw.println();
21231                    pw.println("No Intent Filter Verifier available!");
21232                }
21233            }
21234
21235            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21236                boolean printedHeader = false;
21237                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21238                while (it.hasNext()) {
21239                    String libName = it.next();
21240                    LongSparseArray<SharedLibraryEntry> versionedLib
21241                            = mSharedLibraries.get(libName);
21242                    if (versionedLib == null) {
21243                        continue;
21244                    }
21245                    final int versionCount = versionedLib.size();
21246                    for (int i = 0; i < versionCount; i++) {
21247                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21248                        if (!checkin) {
21249                            if (!printedHeader) {
21250                                if (dumpState.onTitlePrinted())
21251                                    pw.println();
21252                                pw.println("Libraries:");
21253                                printedHeader = true;
21254                            }
21255                            pw.print("  ");
21256                        } else {
21257                            pw.print("lib,");
21258                        }
21259                        pw.print(libEntry.info.getName());
21260                        if (libEntry.info.isStatic()) {
21261                            pw.print(" version=" + libEntry.info.getLongVersion());
21262                        }
21263                        if (!checkin) {
21264                            pw.print(" -> ");
21265                        }
21266                        if (libEntry.path != null) {
21267                            pw.print(" (jar) ");
21268                            pw.print(libEntry.path);
21269                        } else {
21270                            pw.print(" (apk) ");
21271                            pw.print(libEntry.apk);
21272                        }
21273                        pw.println();
21274                    }
21275                }
21276            }
21277
21278            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21279                if (dumpState.onTitlePrinted())
21280                    pw.println();
21281                if (!checkin) {
21282                    pw.println("Features:");
21283                }
21284
21285                synchronized (mAvailableFeatures) {
21286                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21287                        if (checkin) {
21288                            pw.print("feat,");
21289                            pw.print(feat.name);
21290                            pw.print(",");
21291                            pw.println(feat.version);
21292                        } else {
21293                            pw.print("  ");
21294                            pw.print(feat.name);
21295                            if (feat.version > 0) {
21296                                pw.print(" version=");
21297                                pw.print(feat.version);
21298                            }
21299                            pw.println();
21300                        }
21301                    }
21302                }
21303            }
21304
21305            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21306                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21307                        : "Activity Resolver Table:", "  ", packageName,
21308                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21309                    dumpState.setTitlePrinted(true);
21310                }
21311            }
21312            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21313                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21314                        : "Receiver Resolver Table:", "  ", packageName,
21315                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21316                    dumpState.setTitlePrinted(true);
21317                }
21318            }
21319            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21320                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21321                        : "Service Resolver Table:", "  ", packageName,
21322                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21323                    dumpState.setTitlePrinted(true);
21324                }
21325            }
21326            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21327                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21328                        : "Provider Resolver Table:", "  ", packageName,
21329                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21330                    dumpState.setTitlePrinted(true);
21331                }
21332            }
21333
21334            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21335                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21336                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21337                    int user = mSettings.mPreferredActivities.keyAt(i);
21338                    if (pir.dump(pw,
21339                            dumpState.getTitlePrinted()
21340                                ? "\nPreferred Activities User " + user + ":"
21341                                : "Preferred Activities User " + user + ":", "  ",
21342                            packageName, true, false)) {
21343                        dumpState.setTitlePrinted(true);
21344                    }
21345                }
21346            }
21347
21348            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21349                pw.flush();
21350                FileOutputStream fout = new FileOutputStream(fd);
21351                BufferedOutputStream str = new BufferedOutputStream(fout);
21352                XmlSerializer serializer = new FastXmlSerializer();
21353                try {
21354                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21355                    serializer.startDocument(null, true);
21356                    serializer.setFeature(
21357                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21358                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21359                    serializer.endDocument();
21360                    serializer.flush();
21361                } catch (IllegalArgumentException e) {
21362                    pw.println("Failed writing: " + e);
21363                } catch (IllegalStateException e) {
21364                    pw.println("Failed writing: " + e);
21365                } catch (IOException e) {
21366                    pw.println("Failed writing: " + e);
21367                }
21368            }
21369
21370            if (!checkin
21371                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21372                    && packageName == null) {
21373                pw.println();
21374                int count = mSettings.mPackages.size();
21375                if (count == 0) {
21376                    pw.println("No applications!");
21377                    pw.println();
21378                } else {
21379                    final String prefix = "  ";
21380                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21381                    if (allPackageSettings.size() == 0) {
21382                        pw.println("No domain preferred apps!");
21383                        pw.println();
21384                    } else {
21385                        pw.println("App verification status:");
21386                        pw.println();
21387                        count = 0;
21388                        for (PackageSetting ps : allPackageSettings) {
21389                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21390                            if (ivi == null || ivi.getPackageName() == null) continue;
21391                            pw.println(prefix + "Package: " + ivi.getPackageName());
21392                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21393                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21394                            pw.println();
21395                            count++;
21396                        }
21397                        if (count == 0) {
21398                            pw.println(prefix + "No app verification established.");
21399                            pw.println();
21400                        }
21401                        for (int userId : sUserManager.getUserIds()) {
21402                            pw.println("App linkages for user " + userId + ":");
21403                            pw.println();
21404                            count = 0;
21405                            for (PackageSetting ps : allPackageSettings) {
21406                                final long status = ps.getDomainVerificationStatusForUser(userId);
21407                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21408                                        && !DEBUG_DOMAIN_VERIFICATION) {
21409                                    continue;
21410                                }
21411                                pw.println(prefix + "Package: " + ps.name);
21412                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21413                                String statusStr = IntentFilterVerificationInfo.
21414                                        getStatusStringFromValue(status);
21415                                pw.println(prefix + "Status:  " + statusStr);
21416                                pw.println();
21417                                count++;
21418                            }
21419                            if (count == 0) {
21420                                pw.println(prefix + "No configured app linkages.");
21421                                pw.println();
21422                            }
21423                        }
21424                    }
21425                }
21426            }
21427
21428            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21429                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21430            }
21431
21432            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21433                boolean printedSomething = false;
21434                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21435                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21436                        continue;
21437                    }
21438                    if (!printedSomething) {
21439                        if (dumpState.onTitlePrinted())
21440                            pw.println();
21441                        pw.println("Registered ContentProviders:");
21442                        printedSomething = true;
21443                    }
21444                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21445                    pw.print("    "); pw.println(p.toString());
21446                }
21447                printedSomething = false;
21448                for (Map.Entry<String, PackageParser.Provider> entry :
21449                        mProvidersByAuthority.entrySet()) {
21450                    PackageParser.Provider p = entry.getValue();
21451                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21452                        continue;
21453                    }
21454                    if (!printedSomething) {
21455                        if (dumpState.onTitlePrinted())
21456                            pw.println();
21457                        pw.println("ContentProvider Authorities:");
21458                        printedSomething = true;
21459                    }
21460                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21461                    pw.print("    "); pw.println(p.toString());
21462                    if (p.info != null && p.info.applicationInfo != null) {
21463                        final String appInfo = p.info.applicationInfo.toString();
21464                        pw.print("      applicationInfo="); pw.println(appInfo);
21465                    }
21466                }
21467            }
21468
21469            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21470                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21471            }
21472
21473            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21474                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21475            }
21476
21477            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21478                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21479            }
21480
21481            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21482                if (dumpState.onTitlePrinted()) pw.println();
21483                pw.println("Package Changes:");
21484                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21485                final int K = mChangedPackages.size();
21486                for (int i = 0; i < K; i++) {
21487                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21488                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21489                    final int N = changes.size();
21490                    if (N == 0) {
21491                        pw.print("    "); pw.println("No packages changed");
21492                    } else {
21493                        for (int j = 0; j < N; j++) {
21494                            final String pkgName = changes.valueAt(j);
21495                            final int sequenceNumber = changes.keyAt(j);
21496                            pw.print("    ");
21497                            pw.print("seq=");
21498                            pw.print(sequenceNumber);
21499                            pw.print(", package=");
21500                            pw.println(pkgName);
21501                        }
21502                    }
21503                }
21504            }
21505
21506            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21507                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21508            }
21509
21510            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21511                // XXX should handle packageName != null by dumping only install data that
21512                // the given package is involved with.
21513                if (dumpState.onTitlePrinted()) pw.println();
21514
21515                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21516                    ipw.println();
21517                    ipw.println("Frozen packages:");
21518                    ipw.increaseIndent();
21519                    if (mFrozenPackages.size() == 0) {
21520                        ipw.println("(none)");
21521                    } else {
21522                        for (int i = 0; i < mFrozenPackages.size(); i++) {
21523                            ipw.println(mFrozenPackages.valueAt(i));
21524                        }
21525                    }
21526                    ipw.decreaseIndent();
21527                }
21528            }
21529
21530            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21531                if (dumpState.onTitlePrinted()) pw.println();
21532
21533                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21534                    ipw.println();
21535                    ipw.println("Loaded volumes:");
21536                    ipw.increaseIndent();
21537                    if (mLoadedVolumes.size() == 0) {
21538                        ipw.println("(none)");
21539                    } else {
21540                        for (int i = 0; i < mLoadedVolumes.size(); i++) {
21541                            ipw.println(mLoadedVolumes.valueAt(i));
21542                        }
21543                    }
21544                    ipw.decreaseIndent();
21545                }
21546            }
21547
21548            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21549                    && packageName == null) {
21550                if (dumpState.onTitlePrinted()) pw.println();
21551                pw.println("Service permissions:");
21552
21553                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21554                while (filterIterator.hasNext()) {
21555                    final ServiceIntentInfo info = filterIterator.next();
21556                    final ServiceInfo serviceInfo = info.service.info;
21557                    final String permission = serviceInfo.permission;
21558                    if (permission != null) {
21559                        pw.print("    ");
21560                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21561                        pw.print(": ");
21562                        pw.println(permission);
21563                    }
21564                }
21565            }
21566
21567            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21568                if (dumpState.onTitlePrinted()) pw.println();
21569                dumpDexoptStateLPr(pw, packageName);
21570            }
21571
21572            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21573                if (dumpState.onTitlePrinted()) pw.println();
21574                dumpCompilerStatsLPr(pw, packageName);
21575            }
21576
21577            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21578                if (dumpState.onTitlePrinted()) pw.println();
21579                mSettings.dumpReadMessagesLPr(pw, dumpState);
21580
21581                pw.println();
21582                pw.println("Package warning messages:");
21583                dumpCriticalInfo(pw, null);
21584            }
21585
21586            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21587                dumpCriticalInfo(pw, "msg,");
21588            }
21589        }
21590
21591        // PackageInstaller should be called outside of mPackages lock
21592        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21593            // XXX should handle packageName != null by dumping only install data that
21594            // the given package is involved with.
21595            if (dumpState.onTitlePrinted()) pw.println();
21596            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21597        }
21598    }
21599
21600    private void dumpProto(FileDescriptor fd) {
21601        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21602
21603        synchronized (mPackages) {
21604            final long requiredVerifierPackageToken =
21605                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21606            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21607            proto.write(
21608                    PackageServiceDumpProto.PackageShortProto.UID,
21609                    getPackageUid(
21610                            mRequiredVerifierPackage,
21611                            MATCH_DEBUG_TRIAGED_MISSING,
21612                            UserHandle.USER_SYSTEM));
21613            proto.end(requiredVerifierPackageToken);
21614
21615            if (mIntentFilterVerifierComponent != null) {
21616                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21617                final long verifierPackageToken =
21618                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21619                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21620                proto.write(
21621                        PackageServiceDumpProto.PackageShortProto.UID,
21622                        getPackageUid(
21623                                verifierPackageName,
21624                                MATCH_DEBUG_TRIAGED_MISSING,
21625                                UserHandle.USER_SYSTEM));
21626                proto.end(verifierPackageToken);
21627            }
21628
21629            dumpSharedLibrariesProto(proto);
21630            dumpFeaturesProto(proto);
21631            mSettings.dumpPackagesProto(proto);
21632            mSettings.dumpSharedUsersProto(proto);
21633            dumpCriticalInfo(proto);
21634        }
21635        proto.flush();
21636    }
21637
21638    private void dumpFeaturesProto(ProtoOutputStream proto) {
21639        synchronized (mAvailableFeatures) {
21640            final int count = mAvailableFeatures.size();
21641            for (int i = 0; i < count; i++) {
21642                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21643            }
21644        }
21645    }
21646
21647    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21648        final int count = mSharedLibraries.size();
21649        for (int i = 0; i < count; i++) {
21650            final String libName = mSharedLibraries.keyAt(i);
21651            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21652            if (versionedLib == null) {
21653                continue;
21654            }
21655            final int versionCount = versionedLib.size();
21656            for (int j = 0; j < versionCount; j++) {
21657                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21658                final long sharedLibraryToken =
21659                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21660                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21661                final boolean isJar = (libEntry.path != null);
21662                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21663                if (isJar) {
21664                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21665                } else {
21666                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21667                }
21668                proto.end(sharedLibraryToken);
21669            }
21670        }
21671    }
21672
21673    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21674        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21675            ipw.println();
21676            ipw.println("Dexopt state:");
21677            ipw.increaseIndent();
21678            Collection<PackageParser.Package> packages = null;
21679            if (packageName != null) {
21680                PackageParser.Package targetPackage = mPackages.get(packageName);
21681                if (targetPackage != null) {
21682                    packages = Collections.singletonList(targetPackage);
21683                } else {
21684                    ipw.println("Unable to find package: " + packageName);
21685                    return;
21686                }
21687            } else {
21688                packages = mPackages.values();
21689            }
21690
21691            for (PackageParser.Package pkg : packages) {
21692                ipw.println("[" + pkg.packageName + "]");
21693                ipw.increaseIndent();
21694                mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21695                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21696                ipw.decreaseIndent();
21697            }
21698        }
21699    }
21700
21701    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21702        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21703            ipw.println();
21704            ipw.println("Compiler stats:");
21705            ipw.increaseIndent();
21706            Collection<PackageParser.Package> packages = null;
21707            if (packageName != null) {
21708                PackageParser.Package targetPackage = mPackages.get(packageName);
21709                if (targetPackage != null) {
21710                    packages = Collections.singletonList(targetPackage);
21711                } else {
21712                    ipw.println("Unable to find package: " + packageName);
21713                    return;
21714                }
21715            } else {
21716                packages = mPackages.values();
21717            }
21718
21719            for (PackageParser.Package pkg : packages) {
21720                ipw.println("[" + pkg.packageName + "]");
21721                ipw.increaseIndent();
21722
21723                CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21724                if (stats == null) {
21725                    ipw.println("(No recorded stats)");
21726                } else {
21727                    stats.dump(ipw);
21728                }
21729                ipw.decreaseIndent();
21730            }
21731        }
21732    }
21733
21734    private String dumpDomainString(String packageName) {
21735        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21736                .getList();
21737        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21738
21739        ArraySet<String> result = new ArraySet<>();
21740        if (iviList.size() > 0) {
21741            for (IntentFilterVerificationInfo ivi : iviList) {
21742                for (String host : ivi.getDomains()) {
21743                    result.add(host);
21744                }
21745            }
21746        }
21747        if (filters != null && filters.size() > 0) {
21748            for (IntentFilter filter : filters) {
21749                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21750                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21751                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21752                    result.addAll(filter.getHostsList());
21753                }
21754            }
21755        }
21756
21757        StringBuilder sb = new StringBuilder(result.size() * 16);
21758        for (String domain : result) {
21759            if (sb.length() > 0) sb.append(" ");
21760            sb.append(domain);
21761        }
21762        return sb.toString();
21763    }
21764
21765    // ------- apps on sdcard specific code -------
21766    static final boolean DEBUG_SD_INSTALL = false;
21767
21768    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21769
21770    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21771
21772    private boolean mMediaMounted = false;
21773
21774    static String getEncryptKey() {
21775        try {
21776            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21777                    SD_ENCRYPTION_KEYSTORE_NAME);
21778            if (sdEncKey == null) {
21779                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21780                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21781                if (sdEncKey == null) {
21782                    Slog.e(TAG, "Failed to create encryption keys");
21783                    return null;
21784                }
21785            }
21786            return sdEncKey;
21787        } catch (NoSuchAlgorithmException nsae) {
21788            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21789            return null;
21790        } catch (IOException ioe) {
21791            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21792            return null;
21793        }
21794    }
21795
21796    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21797            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21798        final int size = infos.size();
21799        final String[] packageNames = new String[size];
21800        final int[] packageUids = new int[size];
21801        for (int i = 0; i < size; i++) {
21802            final ApplicationInfo info = infos.get(i);
21803            packageNames[i] = info.packageName;
21804            packageUids[i] = info.uid;
21805        }
21806        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21807                finishedReceiver);
21808    }
21809
21810    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21811            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21812        sendResourcesChangedBroadcast(mediaStatus, replacing,
21813                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21814    }
21815
21816    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21817            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21818        int size = pkgList.length;
21819        if (size > 0) {
21820            // Send broadcasts here
21821            Bundle extras = new Bundle();
21822            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21823            if (uidArr != null) {
21824                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21825            }
21826            if (replacing) {
21827                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21828            }
21829            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21830                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21831            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21832        }
21833    }
21834
21835    private void loadPrivatePackages(final VolumeInfo vol) {
21836        mHandler.post(new Runnable() {
21837            @Override
21838            public void run() {
21839                loadPrivatePackagesInner(vol);
21840            }
21841        });
21842    }
21843
21844    private void loadPrivatePackagesInner(VolumeInfo vol) {
21845        final String volumeUuid = vol.fsUuid;
21846        if (TextUtils.isEmpty(volumeUuid)) {
21847            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21848            return;
21849        }
21850
21851        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21852        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21853        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21854
21855        final VersionInfo ver;
21856        final List<PackageSetting> packages;
21857        synchronized (mPackages) {
21858            ver = mSettings.findOrCreateVersion(volumeUuid);
21859            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21860        }
21861
21862        for (PackageSetting ps : packages) {
21863            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21864            synchronized (mInstallLock) {
21865                final PackageParser.Package pkg;
21866                try {
21867                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21868                    loaded.add(pkg.applicationInfo);
21869
21870                } catch (PackageManagerException e) {
21871                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21872                }
21873
21874                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21875                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21876                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21877                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21878                }
21879            }
21880        }
21881
21882        // Reconcile app data for all started/unlocked users
21883        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21884        final UserManager um = mContext.getSystemService(UserManager.class);
21885        UserManagerInternal umInternal = getUserManagerInternal();
21886        for (UserInfo user : um.getUsers()) {
21887            final int flags;
21888            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21889                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21890            } else if (umInternal.isUserRunning(user.id)) {
21891                flags = StorageManager.FLAG_STORAGE_DE;
21892            } else {
21893                continue;
21894            }
21895
21896            try {
21897                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21898                synchronized (mInstallLock) {
21899                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21900                }
21901            } catch (IllegalStateException e) {
21902                // Device was probably ejected, and we'll process that event momentarily
21903                Slog.w(TAG, "Failed to prepare storage: " + e);
21904            }
21905        }
21906
21907        synchronized (mPackages) {
21908            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21909            if (sdkUpdated) {
21910                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21911                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21912            }
21913            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21914                    mPermissionCallback);
21915
21916            // Yay, everything is now upgraded
21917            ver.forceCurrent();
21918
21919            mSettings.writeLPr();
21920        }
21921
21922        for (PackageFreezer freezer : freezers) {
21923            freezer.close();
21924        }
21925
21926        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21927        sendResourcesChangedBroadcast(true, false, loaded, null);
21928        mLoadedVolumes.add(vol.getId());
21929    }
21930
21931    private void unloadPrivatePackages(final VolumeInfo vol) {
21932        mHandler.post(new Runnable() {
21933            @Override
21934            public void run() {
21935                unloadPrivatePackagesInner(vol);
21936            }
21937        });
21938    }
21939
21940    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21941        final String volumeUuid = vol.fsUuid;
21942        if (TextUtils.isEmpty(volumeUuid)) {
21943            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21944            return;
21945        }
21946
21947        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21948        synchronized (mInstallLock) {
21949        synchronized (mPackages) {
21950            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21951            for (PackageSetting ps : packages) {
21952                if (ps.pkg == null) continue;
21953
21954                final ApplicationInfo info = ps.pkg.applicationInfo;
21955                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21956                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21957
21958                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21959                        "unloadPrivatePackagesInner")) {
21960                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21961                            false, null)) {
21962                        unloaded.add(info);
21963                    } else {
21964                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21965                    }
21966                }
21967
21968                // Try very hard to release any references to this package
21969                // so we don't risk the system server being killed due to
21970                // open FDs
21971                AttributeCache.instance().removePackage(ps.name);
21972            }
21973
21974            mSettings.writeLPr();
21975        }
21976        }
21977
21978        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21979        sendResourcesChangedBroadcast(false, false, unloaded, null);
21980        mLoadedVolumes.remove(vol.getId());
21981
21982        // Try very hard to release any references to this path so we don't risk
21983        // the system server being killed due to open FDs
21984        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21985
21986        for (int i = 0; i < 3; i++) {
21987            System.gc();
21988            System.runFinalization();
21989        }
21990    }
21991
21992    private void assertPackageKnown(String volumeUuid, String packageName)
21993            throws PackageManagerException {
21994        synchronized (mPackages) {
21995            // Normalize package name to handle renamed packages
21996            packageName = normalizePackageNameLPr(packageName);
21997
21998            final PackageSetting ps = mSettings.mPackages.get(packageName);
21999            if (ps == null) {
22000                throw new PackageManagerException("Package " + packageName + " is unknown");
22001            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22002                throw new PackageManagerException(
22003                        "Package " + packageName + " found on unknown volume " + volumeUuid
22004                                + "; expected volume " + ps.volumeUuid);
22005            }
22006        }
22007    }
22008
22009    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22010            throws PackageManagerException {
22011        synchronized (mPackages) {
22012            // Normalize package name to handle renamed packages
22013            packageName = normalizePackageNameLPr(packageName);
22014
22015            final PackageSetting ps = mSettings.mPackages.get(packageName);
22016            if (ps == null) {
22017                throw new PackageManagerException("Package " + packageName + " is unknown");
22018            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22019                throw new PackageManagerException(
22020                        "Package " + packageName + " found on unknown volume " + volumeUuid
22021                                + "; expected volume " + ps.volumeUuid);
22022            } else if (!ps.getInstalled(userId)) {
22023                throw new PackageManagerException(
22024                        "Package " + packageName + " not installed for user " + userId);
22025            }
22026        }
22027    }
22028
22029    private List<String> collectAbsoluteCodePaths() {
22030        synchronized (mPackages) {
22031            List<String> codePaths = new ArrayList<>();
22032            final int packageCount = mSettings.mPackages.size();
22033            for (int i = 0; i < packageCount; i++) {
22034                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22035                codePaths.add(ps.codePath.getAbsolutePath());
22036            }
22037            return codePaths;
22038        }
22039    }
22040
22041    /**
22042     * Examine all apps present on given mounted volume, and destroy apps that
22043     * aren't expected, either due to uninstallation or reinstallation on
22044     * another volume.
22045     */
22046    private void reconcileApps(String volumeUuid) {
22047        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22048        List<File> filesToDelete = null;
22049
22050        final File[] files = FileUtils.listFilesOrEmpty(
22051                Environment.getDataAppDirectory(volumeUuid));
22052        for (File file : files) {
22053            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22054                    && !PackageInstallerService.isStageName(file.getName());
22055            if (!isPackage) {
22056                // Ignore entries which are not packages
22057                continue;
22058            }
22059
22060            String absolutePath = file.getAbsolutePath();
22061
22062            boolean pathValid = false;
22063            final int absoluteCodePathCount = absoluteCodePaths.size();
22064            for (int i = 0; i < absoluteCodePathCount; i++) {
22065                String absoluteCodePath = absoluteCodePaths.get(i);
22066                if (absolutePath.startsWith(absoluteCodePath)) {
22067                    pathValid = true;
22068                    break;
22069                }
22070            }
22071
22072            if (!pathValid) {
22073                if (filesToDelete == null) {
22074                    filesToDelete = new ArrayList<>();
22075                }
22076                filesToDelete.add(file);
22077            }
22078        }
22079
22080        if (filesToDelete != null) {
22081            final int fileToDeleteCount = filesToDelete.size();
22082            for (int i = 0; i < fileToDeleteCount; i++) {
22083                File fileToDelete = filesToDelete.get(i);
22084                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22085                synchronized (mInstallLock) {
22086                    removeCodePathLI(fileToDelete);
22087                }
22088            }
22089        }
22090    }
22091
22092    /**
22093     * Reconcile all app data for the given user.
22094     * <p>
22095     * Verifies that directories exist and that ownership and labeling is
22096     * correct for all installed apps on all mounted volumes.
22097     */
22098    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22099        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22100        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22101            final String volumeUuid = vol.getFsUuid();
22102            synchronized (mInstallLock) {
22103                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22104            }
22105        }
22106    }
22107
22108    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22109            boolean migrateAppData) {
22110        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22111    }
22112
22113    /**
22114     * Reconcile all app data on given mounted volume.
22115     * <p>
22116     * Destroys app data that isn't expected, either due to uninstallation or
22117     * reinstallation on another volume.
22118     * <p>
22119     * Verifies that directories exist and that ownership and labeling is
22120     * correct for all installed apps.
22121     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22122     */
22123    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22124            boolean migrateAppData, boolean onlyCoreApps) {
22125        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22126                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22127        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22128
22129        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22130        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22131
22132        // First look for stale data that doesn't belong, and check if things
22133        // have changed since we did our last restorecon
22134        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22135            if (StorageManager.isFileEncryptedNativeOrEmulated()
22136                    && !StorageManager.isUserKeyUnlocked(userId)) {
22137                throw new RuntimeException(
22138                        "Yikes, someone asked us to reconcile CE storage while " + userId
22139                                + " was still locked; this would have caused massive data loss!");
22140            }
22141
22142            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22143            for (File file : files) {
22144                final String packageName = file.getName();
22145                try {
22146                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22147                } catch (PackageManagerException e) {
22148                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22149                    try {
22150                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22151                                StorageManager.FLAG_STORAGE_CE, 0);
22152                    } catch (InstallerException e2) {
22153                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22154                    }
22155                }
22156            }
22157        }
22158        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22159            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22160            for (File file : files) {
22161                final String packageName = file.getName();
22162                try {
22163                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22164                } catch (PackageManagerException e) {
22165                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22166                    try {
22167                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22168                                StorageManager.FLAG_STORAGE_DE, 0);
22169                    } catch (InstallerException e2) {
22170                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22171                    }
22172                }
22173            }
22174        }
22175
22176        // Ensure that data directories are ready to roll for all packages
22177        // installed for this volume and user
22178        final List<PackageSetting> packages;
22179        synchronized (mPackages) {
22180            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22181        }
22182        int preparedCount = 0;
22183        for (PackageSetting ps : packages) {
22184            final String packageName = ps.name;
22185            if (ps.pkg == null) {
22186                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22187                // TODO: might be due to legacy ASEC apps; we should circle back
22188                // and reconcile again once they're scanned
22189                continue;
22190            }
22191            // Skip non-core apps if requested
22192            if (onlyCoreApps && !ps.pkg.coreApp) {
22193                result.add(packageName);
22194                continue;
22195            }
22196
22197            if (ps.getInstalled(userId)) {
22198                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22199                preparedCount++;
22200            }
22201        }
22202
22203        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22204        return result;
22205    }
22206
22207    /**
22208     * Prepare app data for the given app just after it was installed or
22209     * upgraded. This method carefully only touches users that it's installed
22210     * for, and it forces a restorecon to handle any seinfo changes.
22211     * <p>
22212     * Verifies that directories exist and that ownership and labeling is
22213     * correct for all installed apps. If there is an ownership mismatch, it
22214     * will try recovering system apps by wiping data; third-party app data is
22215     * left intact.
22216     * <p>
22217     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22218     */
22219    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22220        final PackageSetting ps;
22221        synchronized (mPackages) {
22222            ps = mSettings.mPackages.get(pkg.packageName);
22223            mSettings.writeKernelMappingLPr(ps);
22224        }
22225
22226        final UserManager um = mContext.getSystemService(UserManager.class);
22227        UserManagerInternal umInternal = getUserManagerInternal();
22228        for (UserInfo user : um.getUsers()) {
22229            final int flags;
22230            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22231                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22232            } else if (umInternal.isUserRunning(user.id)) {
22233                flags = StorageManager.FLAG_STORAGE_DE;
22234            } else {
22235                continue;
22236            }
22237
22238            if (ps.getInstalled(user.id)) {
22239                // TODO: when user data is locked, mark that we're still dirty
22240                prepareAppDataLIF(pkg, user.id, flags);
22241            }
22242        }
22243    }
22244
22245    /**
22246     * Prepare app data for the given app.
22247     * <p>
22248     * Verifies that directories exist and that ownership and labeling is
22249     * correct for all installed apps. If there is an ownership mismatch, this
22250     * will try recovering system apps by wiping data; third-party app data is
22251     * left intact.
22252     */
22253    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22254        if (pkg == null) {
22255            Slog.wtf(TAG, "Package was null!", new Throwable());
22256            return;
22257        }
22258        prepareAppDataLeafLIF(pkg, userId, flags);
22259        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22260        for (int i = 0; i < childCount; i++) {
22261            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22262        }
22263    }
22264
22265    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22266            boolean maybeMigrateAppData) {
22267        prepareAppDataLIF(pkg, userId, flags);
22268
22269        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22270            // We may have just shuffled around app data directories, so
22271            // prepare them one more time
22272            prepareAppDataLIF(pkg, userId, flags);
22273        }
22274    }
22275
22276    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22277        if (DEBUG_APP_DATA) {
22278            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22279                    + Integer.toHexString(flags));
22280        }
22281
22282        final String volumeUuid = pkg.volumeUuid;
22283        final String packageName = pkg.packageName;
22284        final ApplicationInfo app = pkg.applicationInfo;
22285        final int appId = UserHandle.getAppId(app.uid);
22286
22287        Preconditions.checkNotNull(app.seInfo);
22288
22289        long ceDataInode = -1;
22290        try {
22291            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22292                    appId, app.seInfo, app.targetSdkVersion);
22293        } catch (InstallerException e) {
22294            if (app.isSystemApp()) {
22295                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22296                        + ", but trying to recover: " + e);
22297                destroyAppDataLeafLIF(pkg, userId, flags);
22298                try {
22299                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22300                            appId, app.seInfo, app.targetSdkVersion);
22301                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22302                } catch (InstallerException e2) {
22303                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22304                }
22305            } else {
22306                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22307            }
22308        }
22309        // Prepare the application profiles only for upgrades and first boot (so that we don't
22310        // repeat the same operation at each boot).
22311        // We only have to cover the upgrade and first boot here because for app installs we
22312        // prepare the profiles before invoking dexopt (in installPackageLI).
22313        //
22314        // We also have to cover non system users because we do not call the usual install package
22315        // methods for them.
22316        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22317            mArtManagerService.prepareAppProfiles(pkg, userId);
22318        }
22319
22320        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22321            // TODO: mark this structure as dirty so we persist it!
22322            synchronized (mPackages) {
22323                final PackageSetting ps = mSettings.mPackages.get(packageName);
22324                if (ps != null) {
22325                    ps.setCeDataInode(ceDataInode, userId);
22326                }
22327            }
22328        }
22329
22330        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22331    }
22332
22333    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22334        if (pkg == null) {
22335            Slog.wtf(TAG, "Package was null!", new Throwable());
22336            return;
22337        }
22338        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22339        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22340        for (int i = 0; i < childCount; i++) {
22341            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22342        }
22343    }
22344
22345    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22346        final String volumeUuid = pkg.volumeUuid;
22347        final String packageName = pkg.packageName;
22348        final ApplicationInfo app = pkg.applicationInfo;
22349
22350        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22351            // Create a native library symlink only if we have native libraries
22352            // and if the native libraries are 32 bit libraries. We do not provide
22353            // this symlink for 64 bit libraries.
22354            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22355                final String nativeLibPath = app.nativeLibraryDir;
22356                try {
22357                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22358                            nativeLibPath, userId);
22359                } catch (InstallerException e) {
22360                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22361                }
22362            }
22363        }
22364    }
22365
22366    /**
22367     * For system apps on non-FBE devices, this method migrates any existing
22368     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22369     * requested by the app.
22370     */
22371    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22372        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22373                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22374            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22375                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22376            try {
22377                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22378                        storageTarget);
22379            } catch (InstallerException e) {
22380                logCriticalInfo(Log.WARN,
22381                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22382            }
22383            return true;
22384        } else {
22385            return false;
22386        }
22387    }
22388
22389    public PackageFreezer freezePackage(String packageName, String killReason) {
22390        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22391    }
22392
22393    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22394        return new PackageFreezer(packageName, userId, killReason);
22395    }
22396
22397    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22398            String killReason) {
22399        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22400    }
22401
22402    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22403            String killReason) {
22404        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22405            return new PackageFreezer();
22406        } else {
22407            return freezePackage(packageName, userId, killReason);
22408        }
22409    }
22410
22411    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22412            String killReason) {
22413        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22414    }
22415
22416    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22417            String killReason) {
22418        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22419            return new PackageFreezer();
22420        } else {
22421            return freezePackage(packageName, userId, killReason);
22422        }
22423    }
22424
22425    /**
22426     * Class that freezes and kills the given package upon creation, and
22427     * unfreezes it upon closing. This is typically used when doing surgery on
22428     * app code/data to prevent the app from running while you're working.
22429     */
22430    private class PackageFreezer implements AutoCloseable {
22431        private final String mPackageName;
22432        private final PackageFreezer[] mChildren;
22433
22434        private final boolean mWeFroze;
22435
22436        private final AtomicBoolean mClosed = new AtomicBoolean();
22437        private final CloseGuard mCloseGuard = CloseGuard.get();
22438
22439        /**
22440         * Create and return a stub freezer that doesn't actually do anything,
22441         * typically used when someone requested
22442         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22443         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22444         */
22445        public PackageFreezer() {
22446            mPackageName = null;
22447            mChildren = null;
22448            mWeFroze = false;
22449            mCloseGuard.open("close");
22450        }
22451
22452        public PackageFreezer(String packageName, int userId, String killReason) {
22453            synchronized (mPackages) {
22454                mPackageName = packageName;
22455                mWeFroze = mFrozenPackages.add(mPackageName);
22456
22457                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22458                if (ps != null) {
22459                    killApplication(ps.name, ps.appId, userId, killReason);
22460                }
22461
22462                final PackageParser.Package p = mPackages.get(packageName);
22463                if (p != null && p.childPackages != null) {
22464                    final int N = p.childPackages.size();
22465                    mChildren = new PackageFreezer[N];
22466                    for (int i = 0; i < N; i++) {
22467                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22468                                userId, killReason);
22469                    }
22470                } else {
22471                    mChildren = null;
22472                }
22473            }
22474            mCloseGuard.open("close");
22475        }
22476
22477        @Override
22478        protected void finalize() throws Throwable {
22479            try {
22480                if (mCloseGuard != null) {
22481                    mCloseGuard.warnIfOpen();
22482                }
22483
22484                close();
22485            } finally {
22486                super.finalize();
22487            }
22488        }
22489
22490        @Override
22491        public void close() {
22492            mCloseGuard.close();
22493            if (mClosed.compareAndSet(false, true)) {
22494                synchronized (mPackages) {
22495                    if (mWeFroze) {
22496                        mFrozenPackages.remove(mPackageName);
22497                    }
22498
22499                    if (mChildren != null) {
22500                        for (PackageFreezer freezer : mChildren) {
22501                            freezer.close();
22502                        }
22503                    }
22504                }
22505            }
22506        }
22507    }
22508
22509    /**
22510     * Verify that given package is currently frozen.
22511     */
22512    private void checkPackageFrozen(String packageName) {
22513        synchronized (mPackages) {
22514            if (!mFrozenPackages.contains(packageName)) {
22515                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22516            }
22517        }
22518    }
22519
22520    @Override
22521    public int movePackage(final String packageName, final String volumeUuid) {
22522        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22523
22524        final int callingUid = Binder.getCallingUid();
22525        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22526        final int moveId = mNextMoveId.getAndIncrement();
22527        mHandler.post(new Runnable() {
22528            @Override
22529            public void run() {
22530                try {
22531                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22532                } catch (PackageManagerException e) {
22533                    Slog.w(TAG, "Failed to move " + packageName, e);
22534                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22535                }
22536            }
22537        });
22538        return moveId;
22539    }
22540
22541    private void movePackageInternal(final String packageName, final String volumeUuid,
22542            final int moveId, final int callingUid, UserHandle user)
22543                    throws PackageManagerException {
22544        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22545        final PackageManager pm = mContext.getPackageManager();
22546
22547        final boolean currentAsec;
22548        final String currentVolumeUuid;
22549        final File codeFile;
22550        final String installerPackageName;
22551        final String packageAbiOverride;
22552        final int appId;
22553        final String seinfo;
22554        final String label;
22555        final int targetSdkVersion;
22556        final PackageFreezer freezer;
22557        final int[] installedUserIds;
22558
22559        // reader
22560        synchronized (mPackages) {
22561            final PackageParser.Package pkg = mPackages.get(packageName);
22562            final PackageSetting ps = mSettings.mPackages.get(packageName);
22563            if (pkg == null
22564                    || ps == null
22565                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22566                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22567            }
22568            if (pkg.applicationInfo.isSystemApp()) {
22569                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22570                        "Cannot move system application");
22571            }
22572
22573            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22574            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22575                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22576            if (isInternalStorage && !allow3rdPartyOnInternal) {
22577                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22578                        "3rd party apps are not allowed on internal storage");
22579            }
22580
22581            if (pkg.applicationInfo.isExternalAsec()) {
22582                currentAsec = true;
22583                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22584            } else if (pkg.applicationInfo.isForwardLocked()) {
22585                currentAsec = true;
22586                currentVolumeUuid = "forward_locked";
22587            } else {
22588                currentAsec = false;
22589                currentVolumeUuid = ps.volumeUuid;
22590
22591                final File probe = new File(pkg.codePath);
22592                final File probeOat = new File(probe, "oat");
22593                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22594                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22595                            "Move only supported for modern cluster style installs");
22596                }
22597            }
22598
22599            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22600                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22601                        "Package already moved to " + volumeUuid);
22602            }
22603            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22604                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22605                        "Device admin cannot be moved");
22606            }
22607
22608            if (mFrozenPackages.contains(packageName)) {
22609                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22610                        "Failed to move already frozen package");
22611            }
22612
22613            codeFile = new File(pkg.codePath);
22614            installerPackageName = ps.installerPackageName;
22615            packageAbiOverride = ps.cpuAbiOverrideString;
22616            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22617            seinfo = pkg.applicationInfo.seInfo;
22618            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22619            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22620            freezer = freezePackage(packageName, "movePackageInternal");
22621            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22622        }
22623
22624        final Bundle extras = new Bundle();
22625        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22626        extras.putString(Intent.EXTRA_TITLE, label);
22627        mMoveCallbacks.notifyCreated(moveId, extras);
22628
22629        int installFlags;
22630        final boolean moveCompleteApp;
22631        final File measurePath;
22632
22633        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22634            installFlags = INSTALL_INTERNAL;
22635            moveCompleteApp = !currentAsec;
22636            measurePath = Environment.getDataAppDirectory(volumeUuid);
22637        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22638            installFlags = INSTALL_EXTERNAL;
22639            moveCompleteApp = false;
22640            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22641        } else {
22642            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22643            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22644                    || !volume.isMountedWritable()) {
22645                freezer.close();
22646                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22647                        "Move location not mounted private volume");
22648            }
22649
22650            Preconditions.checkState(!currentAsec);
22651
22652            installFlags = INSTALL_INTERNAL;
22653            moveCompleteApp = true;
22654            measurePath = Environment.getDataAppDirectory(volumeUuid);
22655        }
22656
22657        // If we're moving app data around, we need all the users unlocked
22658        if (moveCompleteApp) {
22659            for (int userId : installedUserIds) {
22660                if (StorageManager.isFileEncryptedNativeOrEmulated()
22661                        && !StorageManager.isUserKeyUnlocked(userId)) {
22662                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22663                            "User " + userId + " must be unlocked");
22664                }
22665            }
22666        }
22667
22668        final PackageStats stats = new PackageStats(null, -1);
22669        synchronized (mInstaller) {
22670            for (int userId : installedUserIds) {
22671                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22672                    freezer.close();
22673                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22674                            "Failed to measure package size");
22675                }
22676            }
22677        }
22678
22679        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22680                + stats.dataSize);
22681
22682        final long startFreeBytes = measurePath.getUsableSpace();
22683        final long sizeBytes;
22684        if (moveCompleteApp) {
22685            sizeBytes = stats.codeSize + stats.dataSize;
22686        } else {
22687            sizeBytes = stats.codeSize;
22688        }
22689
22690        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22691            freezer.close();
22692            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22693                    "Not enough free space to move");
22694        }
22695
22696        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22697
22698        final CountDownLatch installedLatch = new CountDownLatch(1);
22699        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22700            @Override
22701            public void onUserActionRequired(Intent intent) throws RemoteException {
22702                throw new IllegalStateException();
22703            }
22704
22705            @Override
22706            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22707                    Bundle extras) throws RemoteException {
22708                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22709                        + PackageManager.installStatusToString(returnCode, msg));
22710
22711                installedLatch.countDown();
22712                freezer.close();
22713
22714                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22715                switch (status) {
22716                    case PackageInstaller.STATUS_SUCCESS:
22717                        mMoveCallbacks.notifyStatusChanged(moveId,
22718                                PackageManager.MOVE_SUCCEEDED);
22719                        break;
22720                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22721                        mMoveCallbacks.notifyStatusChanged(moveId,
22722                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22723                        break;
22724                    default:
22725                        mMoveCallbacks.notifyStatusChanged(moveId,
22726                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22727                        break;
22728                }
22729            }
22730        };
22731
22732        final MoveInfo move;
22733        if (moveCompleteApp) {
22734            // Kick off a thread to report progress estimates
22735            new Thread() {
22736                @Override
22737                public void run() {
22738                    while (true) {
22739                        try {
22740                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22741                                break;
22742                            }
22743                        } catch (InterruptedException ignored) {
22744                        }
22745
22746                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22747                        final int progress = 10 + (int) MathUtils.constrain(
22748                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22749                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22750                    }
22751                }
22752            }.start();
22753
22754            final String dataAppName = codeFile.getName();
22755            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22756                    dataAppName, appId, seinfo, targetSdkVersion);
22757        } else {
22758            move = null;
22759        }
22760
22761        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22762
22763        final Message msg = mHandler.obtainMessage(INIT_COPY);
22764        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22765        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22766                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22767                packageAbiOverride, null /*grantedPermissions*/,
22768                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22769        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22770        msg.obj = params;
22771
22772        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22773                System.identityHashCode(msg.obj));
22774        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22775                System.identityHashCode(msg.obj));
22776
22777        mHandler.sendMessage(msg);
22778    }
22779
22780    @Override
22781    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22782        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22783
22784        final int realMoveId = mNextMoveId.getAndIncrement();
22785        final Bundle extras = new Bundle();
22786        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22787        mMoveCallbacks.notifyCreated(realMoveId, extras);
22788
22789        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22790            @Override
22791            public void onCreated(int moveId, Bundle extras) {
22792                // Ignored
22793            }
22794
22795            @Override
22796            public void onStatusChanged(int moveId, int status, long estMillis) {
22797                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22798            }
22799        };
22800
22801        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22802        storage.setPrimaryStorageUuid(volumeUuid, callback);
22803        return realMoveId;
22804    }
22805
22806    @Override
22807    public int getMoveStatus(int moveId) {
22808        mContext.enforceCallingOrSelfPermission(
22809                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22810        return mMoveCallbacks.mLastStatus.get(moveId);
22811    }
22812
22813    @Override
22814    public void registerMoveCallback(IPackageMoveObserver callback) {
22815        mContext.enforceCallingOrSelfPermission(
22816                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22817        mMoveCallbacks.register(callback);
22818    }
22819
22820    @Override
22821    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22822        mContext.enforceCallingOrSelfPermission(
22823                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22824        mMoveCallbacks.unregister(callback);
22825    }
22826
22827    @Override
22828    public boolean setInstallLocation(int loc) {
22829        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22830                null);
22831        if (getInstallLocation() == loc) {
22832            return true;
22833        }
22834        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22835                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22836            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22837                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22838            return true;
22839        }
22840        return false;
22841   }
22842
22843    @Override
22844    public int getInstallLocation() {
22845        // allow instant app access
22846        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22847                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22848                PackageHelper.APP_INSTALL_AUTO);
22849    }
22850
22851    /** Called by UserManagerService */
22852    void cleanUpUser(UserManagerService userManager, int userHandle) {
22853        synchronized (mPackages) {
22854            mDirtyUsers.remove(userHandle);
22855            mUserNeedsBadging.delete(userHandle);
22856            mSettings.removeUserLPw(userHandle);
22857            mPendingBroadcasts.remove(userHandle);
22858            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22859            removeUnusedPackagesLPw(userManager, userHandle);
22860        }
22861    }
22862
22863    /**
22864     * We're removing userHandle and would like to remove any downloaded packages
22865     * that are no longer in use by any other user.
22866     * @param userHandle the user being removed
22867     */
22868    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22869        final boolean DEBUG_CLEAN_APKS = false;
22870        int [] users = userManager.getUserIds();
22871        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22872        while (psit.hasNext()) {
22873            PackageSetting ps = psit.next();
22874            if (ps.pkg == null) {
22875                continue;
22876            }
22877            final String packageName = ps.pkg.packageName;
22878            // Skip over if system app
22879            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22880                continue;
22881            }
22882            if (DEBUG_CLEAN_APKS) {
22883                Slog.i(TAG, "Checking package " + packageName);
22884            }
22885            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22886            if (keep) {
22887                if (DEBUG_CLEAN_APKS) {
22888                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22889                }
22890            } else {
22891                for (int i = 0; i < users.length; i++) {
22892                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22893                        keep = true;
22894                        if (DEBUG_CLEAN_APKS) {
22895                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22896                                    + users[i]);
22897                        }
22898                        break;
22899                    }
22900                }
22901            }
22902            if (!keep) {
22903                if (DEBUG_CLEAN_APKS) {
22904                    Slog.i(TAG, "  Removing package " + packageName);
22905                }
22906                mHandler.post(new Runnable() {
22907                    public void run() {
22908                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22909                                userHandle, 0);
22910                    } //end run
22911                });
22912            }
22913        }
22914    }
22915
22916    /** Called by UserManagerService */
22917    void createNewUser(int userId, String[] disallowedPackages) {
22918        synchronized (mInstallLock) {
22919            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22920        }
22921        synchronized (mPackages) {
22922            scheduleWritePackageRestrictionsLocked(userId);
22923            scheduleWritePackageListLocked(userId);
22924            applyFactoryDefaultBrowserLPw(userId);
22925            primeDomainVerificationsLPw(userId);
22926        }
22927    }
22928
22929    void onNewUserCreated(final int userId) {
22930        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22931        synchronized(mPackages) {
22932            // If permission review for legacy apps is required, we represent
22933            // dagerous permissions for such apps as always granted runtime
22934            // permissions to keep per user flag state whether review is needed.
22935            // Hence, if a new user is added we have to propagate dangerous
22936            // permission grants for these legacy apps.
22937            if (mSettings.mPermissions.mPermissionReviewRequired) {
22938// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22939                mPermissionManager.updateAllPermissions(
22940                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22941                        mPermissionCallback);
22942            }
22943        }
22944    }
22945
22946    @Override
22947    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22948        mContext.enforceCallingOrSelfPermission(
22949                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22950                "Only package verification agents can read the verifier device identity");
22951
22952        synchronized (mPackages) {
22953            return mSettings.getVerifierDeviceIdentityLPw();
22954        }
22955    }
22956
22957    @Override
22958    public void setPermissionEnforced(String permission, boolean enforced) {
22959        // TODO: Now that we no longer change GID for storage, this should to away.
22960        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22961                "setPermissionEnforced");
22962        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22963            synchronized (mPackages) {
22964                if (mSettings.mReadExternalStorageEnforced == null
22965                        || mSettings.mReadExternalStorageEnforced != enforced) {
22966                    mSettings.mReadExternalStorageEnforced =
22967                            enforced ? Boolean.TRUE : Boolean.FALSE;
22968                    mSettings.writeLPr();
22969                }
22970            }
22971            // kill any non-foreground processes so we restart them and
22972            // grant/revoke the GID.
22973            final IActivityManager am = ActivityManager.getService();
22974            if (am != null) {
22975                final long token = Binder.clearCallingIdentity();
22976                try {
22977                    am.killProcessesBelowForeground("setPermissionEnforcement");
22978                } catch (RemoteException e) {
22979                } finally {
22980                    Binder.restoreCallingIdentity(token);
22981                }
22982            }
22983        } else {
22984            throw new IllegalArgumentException("No selective enforcement for " + permission);
22985        }
22986    }
22987
22988    @Override
22989    @Deprecated
22990    public boolean isPermissionEnforced(String permission) {
22991        // allow instant applications
22992        return true;
22993    }
22994
22995    @Override
22996    public boolean isStorageLow() {
22997        // allow instant applications
22998        final long token = Binder.clearCallingIdentity();
22999        try {
23000            final DeviceStorageMonitorInternal
23001                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23002            if (dsm != null) {
23003                return dsm.isMemoryLow();
23004            } else {
23005                return false;
23006            }
23007        } finally {
23008            Binder.restoreCallingIdentity(token);
23009        }
23010    }
23011
23012    @Override
23013    public IPackageInstaller getPackageInstaller() {
23014        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23015            return null;
23016        }
23017        return mInstallerService;
23018    }
23019
23020    @Override
23021    public IArtManager getArtManager() {
23022        return mArtManagerService;
23023    }
23024
23025    private boolean userNeedsBadging(int userId) {
23026        int index = mUserNeedsBadging.indexOfKey(userId);
23027        if (index < 0) {
23028            final UserInfo userInfo;
23029            final long token = Binder.clearCallingIdentity();
23030            try {
23031                userInfo = sUserManager.getUserInfo(userId);
23032            } finally {
23033                Binder.restoreCallingIdentity(token);
23034            }
23035            final boolean b;
23036            if (userInfo != null && userInfo.isManagedProfile()) {
23037                b = true;
23038            } else {
23039                b = false;
23040            }
23041            mUserNeedsBadging.put(userId, b);
23042            return b;
23043        }
23044        return mUserNeedsBadging.valueAt(index);
23045    }
23046
23047    @Override
23048    public KeySet getKeySetByAlias(String packageName, String alias) {
23049        if (packageName == null || alias == null) {
23050            return null;
23051        }
23052        synchronized(mPackages) {
23053            final PackageParser.Package pkg = mPackages.get(packageName);
23054            if (pkg == null) {
23055                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23056                throw new IllegalArgumentException("Unknown package: " + packageName);
23057            }
23058            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23059            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23060                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23061                throw new IllegalArgumentException("Unknown package: " + packageName);
23062            }
23063            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23064            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23065        }
23066    }
23067
23068    @Override
23069    public KeySet getSigningKeySet(String packageName) {
23070        if (packageName == null) {
23071            return null;
23072        }
23073        synchronized(mPackages) {
23074            final int callingUid = Binder.getCallingUid();
23075            final int callingUserId = UserHandle.getUserId(callingUid);
23076            final PackageParser.Package pkg = mPackages.get(packageName);
23077            if (pkg == null) {
23078                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23079                throw new IllegalArgumentException("Unknown package: " + packageName);
23080            }
23081            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23082            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23083                // filter and pretend the package doesn't exist
23084                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23085                        + ", uid:" + callingUid);
23086                throw new IllegalArgumentException("Unknown package: " + packageName);
23087            }
23088            if (pkg.applicationInfo.uid != callingUid
23089                    && Process.SYSTEM_UID != callingUid) {
23090                throw new SecurityException("May not access signing KeySet of other apps.");
23091            }
23092            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23093            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23094        }
23095    }
23096
23097    @Override
23098    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23099        final int callingUid = Binder.getCallingUid();
23100        if (getInstantAppPackageName(callingUid) != null) {
23101            return false;
23102        }
23103        if (packageName == null || ks == null) {
23104            return false;
23105        }
23106        synchronized(mPackages) {
23107            final PackageParser.Package pkg = mPackages.get(packageName);
23108            if (pkg == null
23109                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23110                            UserHandle.getUserId(callingUid))) {
23111                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23112                throw new IllegalArgumentException("Unknown package: " + packageName);
23113            }
23114            IBinder ksh = ks.getToken();
23115            if (ksh instanceof KeySetHandle) {
23116                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23117                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23118            }
23119            return false;
23120        }
23121    }
23122
23123    @Override
23124    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23125        final int callingUid = Binder.getCallingUid();
23126        if (getInstantAppPackageName(callingUid) != null) {
23127            return false;
23128        }
23129        if (packageName == null || ks == null) {
23130            return false;
23131        }
23132        synchronized(mPackages) {
23133            final PackageParser.Package pkg = mPackages.get(packageName);
23134            if (pkg == null
23135                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23136                            UserHandle.getUserId(callingUid))) {
23137                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23138                throw new IllegalArgumentException("Unknown package: " + packageName);
23139            }
23140            IBinder ksh = ks.getToken();
23141            if (ksh instanceof KeySetHandle) {
23142                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23143                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23144            }
23145            return false;
23146        }
23147    }
23148
23149    private void deletePackageIfUnusedLPr(final String packageName) {
23150        PackageSetting ps = mSettings.mPackages.get(packageName);
23151        if (ps == null) {
23152            return;
23153        }
23154        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23155            // TODO Implement atomic delete if package is unused
23156            // It is currently possible that the package will be deleted even if it is installed
23157            // after this method returns.
23158            mHandler.post(new Runnable() {
23159                public void run() {
23160                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23161                            0, PackageManager.DELETE_ALL_USERS);
23162                }
23163            });
23164        }
23165    }
23166
23167    /**
23168     * Check and throw if the given before/after packages would be considered a
23169     * downgrade.
23170     */
23171    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23172            throws PackageManagerException {
23173        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23174            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23175                    "Update version code " + after.versionCode + " is older than current "
23176                    + before.getLongVersionCode());
23177        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23178            if (after.baseRevisionCode < before.baseRevisionCode) {
23179                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23180                        "Update base revision code " + after.baseRevisionCode
23181                        + " is older than current " + before.baseRevisionCode);
23182            }
23183
23184            if (!ArrayUtils.isEmpty(after.splitNames)) {
23185                for (int i = 0; i < after.splitNames.length; i++) {
23186                    final String splitName = after.splitNames[i];
23187                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23188                    if (j != -1) {
23189                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23190                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23191                                    "Update split " + splitName + " revision code "
23192                                    + after.splitRevisionCodes[i] + " is older than current "
23193                                    + before.splitRevisionCodes[j]);
23194                        }
23195                    }
23196                }
23197            }
23198        }
23199    }
23200
23201    private static class MoveCallbacks extends Handler {
23202        private static final int MSG_CREATED = 1;
23203        private static final int MSG_STATUS_CHANGED = 2;
23204
23205        private final RemoteCallbackList<IPackageMoveObserver>
23206                mCallbacks = new RemoteCallbackList<>();
23207
23208        private final SparseIntArray mLastStatus = new SparseIntArray();
23209
23210        public MoveCallbacks(Looper looper) {
23211            super(looper);
23212        }
23213
23214        public void register(IPackageMoveObserver callback) {
23215            mCallbacks.register(callback);
23216        }
23217
23218        public void unregister(IPackageMoveObserver callback) {
23219            mCallbacks.unregister(callback);
23220        }
23221
23222        @Override
23223        public void handleMessage(Message msg) {
23224            final SomeArgs args = (SomeArgs) msg.obj;
23225            final int n = mCallbacks.beginBroadcast();
23226            for (int i = 0; i < n; i++) {
23227                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23228                try {
23229                    invokeCallback(callback, msg.what, args);
23230                } catch (RemoteException ignored) {
23231                }
23232            }
23233            mCallbacks.finishBroadcast();
23234            args.recycle();
23235        }
23236
23237        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23238                throws RemoteException {
23239            switch (what) {
23240                case MSG_CREATED: {
23241                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23242                    break;
23243                }
23244                case MSG_STATUS_CHANGED: {
23245                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23246                    break;
23247                }
23248            }
23249        }
23250
23251        private void notifyCreated(int moveId, Bundle extras) {
23252            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23253
23254            final SomeArgs args = SomeArgs.obtain();
23255            args.argi1 = moveId;
23256            args.arg2 = extras;
23257            obtainMessage(MSG_CREATED, args).sendToTarget();
23258        }
23259
23260        private void notifyStatusChanged(int moveId, int status) {
23261            notifyStatusChanged(moveId, status, -1);
23262        }
23263
23264        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23265            Slog.v(TAG, "Move " + moveId + " status " + status);
23266
23267            final SomeArgs args = SomeArgs.obtain();
23268            args.argi1 = moveId;
23269            args.argi2 = status;
23270            args.arg3 = estMillis;
23271            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23272
23273            synchronized (mLastStatus) {
23274                mLastStatus.put(moveId, status);
23275            }
23276        }
23277    }
23278
23279    private final static class OnPermissionChangeListeners extends Handler {
23280        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23281
23282        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23283                new RemoteCallbackList<>();
23284
23285        public OnPermissionChangeListeners(Looper looper) {
23286            super(looper);
23287        }
23288
23289        @Override
23290        public void handleMessage(Message msg) {
23291            switch (msg.what) {
23292                case MSG_ON_PERMISSIONS_CHANGED: {
23293                    final int uid = msg.arg1;
23294                    handleOnPermissionsChanged(uid);
23295                } break;
23296            }
23297        }
23298
23299        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23300            mPermissionListeners.register(listener);
23301
23302        }
23303
23304        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23305            mPermissionListeners.unregister(listener);
23306        }
23307
23308        public void onPermissionsChanged(int uid) {
23309            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23310                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23311            }
23312        }
23313
23314        private void handleOnPermissionsChanged(int uid) {
23315            final int count = mPermissionListeners.beginBroadcast();
23316            try {
23317                for (int i = 0; i < count; i++) {
23318                    IOnPermissionsChangeListener callback = mPermissionListeners
23319                            .getBroadcastItem(i);
23320                    try {
23321                        callback.onPermissionsChanged(uid);
23322                    } catch (RemoteException e) {
23323                        Log.e(TAG, "Permission listener is dead", e);
23324                    }
23325                }
23326            } finally {
23327                mPermissionListeners.finishBroadcast();
23328            }
23329        }
23330    }
23331
23332    private class PackageManagerNative extends IPackageManagerNative.Stub {
23333        @Override
23334        public String[] getNamesForUids(int[] uids) throws RemoteException {
23335            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23336            // massage results so they can be parsed by the native binder
23337            for (int i = results.length - 1; i >= 0; --i) {
23338                if (results[i] == null) {
23339                    results[i] = "";
23340                }
23341            }
23342            return results;
23343        }
23344
23345        // NB: this differentiates between preloads and sideloads
23346        @Override
23347        public String getInstallerForPackage(String packageName) throws RemoteException {
23348            final String installerName = getInstallerPackageName(packageName);
23349            if (!TextUtils.isEmpty(installerName)) {
23350                return installerName;
23351            }
23352            // differentiate between preload and sideload
23353            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23354            ApplicationInfo appInfo = getApplicationInfo(packageName,
23355                                    /*flags*/ 0,
23356                                    /*userId*/ callingUser);
23357            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23358                return "preload";
23359            }
23360            return "";
23361        }
23362
23363        @Override
23364        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23365            try {
23366                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23367                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23368                if (pInfo != null) {
23369                    return pInfo.getLongVersionCode();
23370                }
23371            } catch (Exception e) {
23372            }
23373            return 0;
23374        }
23375    }
23376
23377    private class PackageManagerInternalImpl extends PackageManagerInternal {
23378        @Override
23379        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23380                int flagValues, int userId) {
23381            PackageManagerService.this.updatePermissionFlags(
23382                    permName, packageName, flagMask, flagValues, userId);
23383        }
23384
23385        @Override
23386        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23387            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23388        }
23389
23390        @Override
23391        public boolean isInstantApp(String packageName, int userId) {
23392            return PackageManagerService.this.isInstantApp(packageName, userId);
23393        }
23394
23395        @Override
23396        public String getInstantAppPackageName(int uid) {
23397            return PackageManagerService.this.getInstantAppPackageName(uid);
23398        }
23399
23400        @Override
23401        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23402            synchronized (mPackages) {
23403                return PackageManagerService.this.filterAppAccessLPr(
23404                        (PackageSetting) pkg.mExtras, callingUid, userId);
23405            }
23406        }
23407
23408        @Override
23409        public PackageParser.Package getPackage(String packageName) {
23410            synchronized (mPackages) {
23411                packageName = resolveInternalPackageNameLPr(
23412                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23413                return mPackages.get(packageName);
23414            }
23415        }
23416
23417        @Override
23418        public PackageList getPackageList(PackageListObserver observer) {
23419            synchronized (mPackages) {
23420                final int N = mPackages.size();
23421                final ArrayList<String> list = new ArrayList<>(N);
23422                for (int i = 0; i < N; i++) {
23423                    list.add(mPackages.keyAt(i));
23424                }
23425                final PackageList packageList = new PackageList(list, observer);
23426                if (observer != null) {
23427                    mPackageListObservers.add(packageList);
23428                }
23429                return packageList;
23430            }
23431        }
23432
23433        @Override
23434        public void removePackageListObserver(PackageListObserver observer) {
23435            synchronized (mPackages) {
23436                mPackageListObservers.remove(observer);
23437            }
23438        }
23439
23440        @Override
23441        public PackageParser.Package getDisabledPackage(String packageName) {
23442            synchronized (mPackages) {
23443                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23444                return (ps != null) ? ps.pkg : null;
23445            }
23446        }
23447
23448        @Override
23449        public String getKnownPackageName(int knownPackage, int userId) {
23450            switch(knownPackage) {
23451                case PackageManagerInternal.PACKAGE_BROWSER:
23452                    return getDefaultBrowserPackageName(userId);
23453                case PackageManagerInternal.PACKAGE_INSTALLER:
23454                    return mRequiredInstallerPackage;
23455                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23456                    return mSetupWizardPackage;
23457                case PackageManagerInternal.PACKAGE_SYSTEM:
23458                    return "android";
23459                case PackageManagerInternal.PACKAGE_VERIFIER:
23460                    return mRequiredVerifierPackage;
23461                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23462                    return mSystemTextClassifierPackage;
23463            }
23464            return null;
23465        }
23466
23467        @Override
23468        public boolean isResolveActivityComponent(ComponentInfo component) {
23469            return mResolveActivity.packageName.equals(component.packageName)
23470                    && mResolveActivity.name.equals(component.name);
23471        }
23472
23473        @Override
23474        public void setLocationPackagesProvider(PackagesProvider provider) {
23475            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23476        }
23477
23478        @Override
23479        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23480            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23481        }
23482
23483        @Override
23484        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23485            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23486        }
23487
23488        @Override
23489        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23490            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23491        }
23492
23493        @Override
23494        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23495            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23496        }
23497
23498        @Override
23499        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23500            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23501        }
23502
23503        @Override
23504        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23505            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23506        }
23507
23508        @Override
23509        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23510            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23511        }
23512
23513        @Override
23514        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23515            synchronized (mPackages) {
23516                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23517            }
23518            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23519        }
23520
23521        @Override
23522        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23523            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23524                    packageName, userId);
23525        }
23526
23527        @Override
23528        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23529            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23530                    packageName, userId);
23531        }
23532
23533        @Override
23534        public void setKeepUninstalledPackages(final List<String> packageList) {
23535            Preconditions.checkNotNull(packageList);
23536            List<String> removedFromList = null;
23537            synchronized (mPackages) {
23538                if (mKeepUninstalledPackages != null) {
23539                    final int packagesCount = mKeepUninstalledPackages.size();
23540                    for (int i = 0; i < packagesCount; i++) {
23541                        String oldPackage = mKeepUninstalledPackages.get(i);
23542                        if (packageList != null && packageList.contains(oldPackage)) {
23543                            continue;
23544                        }
23545                        if (removedFromList == null) {
23546                            removedFromList = new ArrayList<>();
23547                        }
23548                        removedFromList.add(oldPackage);
23549                    }
23550                }
23551                mKeepUninstalledPackages = new ArrayList<>(packageList);
23552                if (removedFromList != null) {
23553                    final int removedCount = removedFromList.size();
23554                    for (int i = 0; i < removedCount; i++) {
23555                        deletePackageIfUnusedLPr(removedFromList.get(i));
23556                    }
23557                }
23558            }
23559        }
23560
23561        @Override
23562        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23563            synchronized (mPackages) {
23564                return mPermissionManager.isPermissionsReviewRequired(
23565                        mPackages.get(packageName), userId);
23566            }
23567        }
23568
23569        @Override
23570        public PackageInfo getPackageInfo(
23571                String packageName, int flags, int filterCallingUid, int userId) {
23572            return PackageManagerService.this
23573                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23574                            flags, filterCallingUid, userId);
23575        }
23576
23577        @Override
23578        public int getPackageUid(String packageName, int flags, int userId) {
23579            return PackageManagerService.this
23580                    .getPackageUid(packageName, flags, userId);
23581        }
23582
23583        @Override
23584        public ApplicationInfo getApplicationInfo(
23585                String packageName, int flags, int filterCallingUid, int userId) {
23586            return PackageManagerService.this
23587                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23588        }
23589
23590        @Override
23591        public ActivityInfo getActivityInfo(
23592                ComponentName component, int flags, int filterCallingUid, int userId) {
23593            return PackageManagerService.this
23594                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23595        }
23596
23597        @Override
23598        public List<ResolveInfo> queryIntentActivities(
23599                Intent intent, int flags, int filterCallingUid, int userId) {
23600            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23601            return PackageManagerService.this
23602                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23603                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23604        }
23605
23606        @Override
23607        public List<ResolveInfo> queryIntentServices(
23608                Intent intent, int flags, int callingUid, int userId) {
23609            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23610            return PackageManagerService.this
23611                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23612                            false);
23613        }
23614
23615        @Override
23616        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23617                int userId) {
23618            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23619        }
23620
23621        @Override
23622        public ComponentName getDefaultHomeActivity(int userId) {
23623            return PackageManagerService.this.getDefaultHomeActivity(userId);
23624        }
23625
23626        @Override
23627        public void setDeviceAndProfileOwnerPackages(
23628                int deviceOwnerUserId, String deviceOwnerPackage,
23629                SparseArray<String> profileOwnerPackages) {
23630            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23631                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23632        }
23633
23634        @Override
23635        public boolean isPackageDataProtected(int userId, String packageName) {
23636            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23637        }
23638
23639        @Override
23640        public boolean isPackageEphemeral(int userId, String packageName) {
23641            synchronized (mPackages) {
23642                final PackageSetting ps = mSettings.mPackages.get(packageName);
23643                return ps != null ? ps.getInstantApp(userId) : false;
23644            }
23645        }
23646
23647        @Override
23648        public boolean wasPackageEverLaunched(String packageName, int userId) {
23649            synchronized (mPackages) {
23650                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23651            }
23652        }
23653
23654        @Override
23655        public void grantRuntimePermission(String packageName, String permName, int userId,
23656                boolean overridePolicy) {
23657            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23658                    permName, packageName, overridePolicy, getCallingUid(), userId,
23659                    mPermissionCallback);
23660        }
23661
23662        @Override
23663        public void revokeRuntimePermission(String packageName, String permName, int userId,
23664                boolean overridePolicy) {
23665            mPermissionManager.revokeRuntimePermission(
23666                    permName, packageName, overridePolicy, getCallingUid(), userId,
23667                    mPermissionCallback);
23668        }
23669
23670        @Override
23671        public String getNameForUid(int uid) {
23672            return PackageManagerService.this.getNameForUid(uid);
23673        }
23674
23675        @Override
23676        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23677                Intent origIntent, String resolvedType, String callingPackage,
23678                Bundle verificationBundle, int userId) {
23679            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23680                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23681                    userId);
23682        }
23683
23684        @Override
23685        public void grantEphemeralAccess(int userId, Intent intent,
23686                int targetAppId, int ephemeralAppId) {
23687            synchronized (mPackages) {
23688                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23689                        targetAppId, ephemeralAppId);
23690            }
23691        }
23692
23693        @Override
23694        public boolean isInstantAppInstallerComponent(ComponentName component) {
23695            synchronized (mPackages) {
23696                return mInstantAppInstallerActivity != null
23697                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23698            }
23699        }
23700
23701        @Override
23702        public void pruneInstantApps() {
23703            mInstantAppRegistry.pruneInstantApps();
23704        }
23705
23706        @Override
23707        public String getSetupWizardPackageName() {
23708            return mSetupWizardPackage;
23709        }
23710
23711        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23712            if (policy != null) {
23713                mExternalSourcesPolicy = policy;
23714            }
23715        }
23716
23717        @Override
23718        public boolean isPackagePersistent(String packageName) {
23719            synchronized (mPackages) {
23720                PackageParser.Package pkg = mPackages.get(packageName);
23721                return pkg != null
23722                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23723                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23724                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23725                        : false;
23726            }
23727        }
23728
23729        @Override
23730        public boolean isLegacySystemApp(Package pkg) {
23731            synchronized (mPackages) {
23732                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23733                return mPromoteSystemApps
23734                        && ps.isSystem()
23735                        && mExistingSystemPackages.contains(ps.name);
23736            }
23737        }
23738
23739        @Override
23740        public List<PackageInfo> getOverlayPackages(int userId) {
23741            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23742            synchronized (mPackages) {
23743                for (PackageParser.Package p : mPackages.values()) {
23744                    if (p.mOverlayTarget != null) {
23745                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23746                        if (pkg != null) {
23747                            overlayPackages.add(pkg);
23748                        }
23749                    }
23750                }
23751            }
23752            return overlayPackages;
23753        }
23754
23755        @Override
23756        public List<String> getTargetPackageNames(int userId) {
23757            List<String> targetPackages = new ArrayList<>();
23758            synchronized (mPackages) {
23759                for (PackageParser.Package p : mPackages.values()) {
23760                    if (p.mOverlayTarget == null) {
23761                        targetPackages.add(p.packageName);
23762                    }
23763                }
23764            }
23765            return targetPackages;
23766        }
23767
23768        @Override
23769        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23770                @Nullable List<String> overlayPackageNames) {
23771            synchronized (mPackages) {
23772                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23773                    Slog.e(TAG, "failed to find package " + targetPackageName);
23774                    return false;
23775                }
23776                ArrayList<String> overlayPaths = null;
23777                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23778                    final int N = overlayPackageNames.size();
23779                    overlayPaths = new ArrayList<>(N);
23780                    for (int i = 0; i < N; i++) {
23781                        final String packageName = overlayPackageNames.get(i);
23782                        final PackageParser.Package pkg = mPackages.get(packageName);
23783                        if (pkg == null) {
23784                            Slog.e(TAG, "failed to find package " + packageName);
23785                            return false;
23786                        }
23787                        overlayPaths.add(pkg.baseCodePath);
23788                    }
23789                }
23790
23791                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23792                ps.setOverlayPaths(overlayPaths, userId);
23793                return true;
23794            }
23795        }
23796
23797        @Override
23798        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23799                int flags, int userId, boolean resolveForStart) {
23800            return resolveIntentInternal(
23801                    intent, resolvedType, flags, userId, resolveForStart);
23802        }
23803
23804        @Override
23805        public ResolveInfo resolveService(Intent intent, String resolvedType,
23806                int flags, int userId, int callingUid) {
23807            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23808        }
23809
23810        @Override
23811        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23812            return PackageManagerService.this.resolveContentProviderInternal(
23813                    name, flags, userId);
23814        }
23815
23816        @Override
23817        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23818            synchronized (mPackages) {
23819                mIsolatedOwners.put(isolatedUid, ownerUid);
23820            }
23821        }
23822
23823        @Override
23824        public void removeIsolatedUid(int isolatedUid) {
23825            synchronized (mPackages) {
23826                mIsolatedOwners.delete(isolatedUid);
23827            }
23828        }
23829
23830        @Override
23831        public int getUidTargetSdkVersion(int uid) {
23832            synchronized (mPackages) {
23833                return getUidTargetSdkVersionLockedLPr(uid);
23834            }
23835        }
23836
23837        @Override
23838        public int getPackageTargetSdkVersion(String packageName) {
23839            synchronized (mPackages) {
23840                return getPackageTargetSdkVersionLockedLPr(packageName);
23841            }
23842        }
23843
23844        @Override
23845        public boolean canAccessInstantApps(int callingUid, int userId) {
23846            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23847        }
23848
23849        @Override
23850        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
23851            synchronized (mPackages) {
23852                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
23853                return !PackageManagerService.this.filterAppAccessLPr(
23854                        ps, callingUid, component, TYPE_UNKNOWN, userId);
23855            }
23856        }
23857
23858        @Override
23859        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23860            synchronized (mPackages) {
23861                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23862            }
23863        }
23864
23865        @Override
23866        public void notifyPackageUse(String packageName, int reason) {
23867            synchronized (mPackages) {
23868                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23869            }
23870        }
23871    }
23872
23873    @Override
23874    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23875        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23876        synchronized (mPackages) {
23877            final long identity = Binder.clearCallingIdentity();
23878            try {
23879                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23880                        packageNames, userId);
23881            } finally {
23882                Binder.restoreCallingIdentity(identity);
23883            }
23884        }
23885    }
23886
23887    @Override
23888    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23889        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23890        synchronized (mPackages) {
23891            final long identity = Binder.clearCallingIdentity();
23892            try {
23893                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23894                        packageNames, userId);
23895            } finally {
23896                Binder.restoreCallingIdentity(identity);
23897            }
23898        }
23899    }
23900
23901    private static void enforceSystemOrPhoneCaller(String tag) {
23902        int callingUid = Binder.getCallingUid();
23903        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23904            throw new SecurityException(
23905                    "Cannot call " + tag + " from UID " + callingUid);
23906        }
23907    }
23908
23909    boolean isHistoricalPackageUsageAvailable() {
23910        return mPackageUsage.isHistoricalPackageUsageAvailable();
23911    }
23912
23913    /**
23914     * Return a <b>copy</b> of the collection of packages known to the package manager.
23915     * @return A copy of the values of mPackages.
23916     */
23917    Collection<PackageParser.Package> getPackages() {
23918        synchronized (mPackages) {
23919            return new ArrayList<>(mPackages.values());
23920        }
23921    }
23922
23923    /**
23924     * Logs process start information (including base APK hash) to the security log.
23925     * @hide
23926     */
23927    @Override
23928    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23929            String apkFile, int pid) {
23930        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23931            return;
23932        }
23933        if (!SecurityLog.isLoggingEnabled()) {
23934            return;
23935        }
23936        Bundle data = new Bundle();
23937        data.putLong("startTimestamp", System.currentTimeMillis());
23938        data.putString("processName", processName);
23939        data.putInt("uid", uid);
23940        data.putString("seinfo", seinfo);
23941        data.putString("apkFile", apkFile);
23942        data.putInt("pid", pid);
23943        Message msg = mProcessLoggingHandler.obtainMessage(
23944                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23945        msg.setData(data);
23946        mProcessLoggingHandler.sendMessage(msg);
23947    }
23948
23949    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23950        return mCompilerStats.getPackageStats(pkgName);
23951    }
23952
23953    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23954        return getOrCreateCompilerPackageStats(pkg.packageName);
23955    }
23956
23957    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23958        return mCompilerStats.getOrCreatePackageStats(pkgName);
23959    }
23960
23961    public void deleteCompilerPackageStats(String pkgName) {
23962        mCompilerStats.deletePackageStats(pkgName);
23963    }
23964
23965    @Override
23966    public int getInstallReason(String packageName, int userId) {
23967        final int callingUid = Binder.getCallingUid();
23968        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23969                true /* requireFullPermission */, false /* checkShell */,
23970                "get install reason");
23971        synchronized (mPackages) {
23972            final PackageSetting ps = mSettings.mPackages.get(packageName);
23973            if (filterAppAccessLPr(ps, callingUid, userId)) {
23974                return PackageManager.INSTALL_REASON_UNKNOWN;
23975            }
23976            if (ps != null) {
23977                return ps.getInstallReason(userId);
23978            }
23979        }
23980        return PackageManager.INSTALL_REASON_UNKNOWN;
23981    }
23982
23983    @Override
23984    public boolean canRequestPackageInstalls(String packageName, int userId) {
23985        return canRequestPackageInstallsInternal(packageName, 0, userId,
23986                true /* throwIfPermNotDeclared*/);
23987    }
23988
23989    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23990            boolean throwIfPermNotDeclared) {
23991        int callingUid = Binder.getCallingUid();
23992        int uid = getPackageUid(packageName, 0, userId);
23993        if (callingUid != uid && callingUid != Process.ROOT_UID
23994                && callingUid != Process.SYSTEM_UID) {
23995            throw new SecurityException(
23996                    "Caller uid " + callingUid + " does not own package " + packageName);
23997        }
23998        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23999        if (info == null) {
24000            return false;
24001        }
24002        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24003            return false;
24004        }
24005        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24006        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24007        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24008            if (throwIfPermNotDeclared) {
24009                throw new SecurityException("Need to declare " + appOpPermission
24010                        + " to call this api");
24011            } else {
24012                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24013                return false;
24014            }
24015        }
24016        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24017            return false;
24018        }
24019        if (mExternalSourcesPolicy != null) {
24020            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24021            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24022                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24023            }
24024        }
24025        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24026    }
24027
24028    @Override
24029    public ComponentName getInstantAppResolverSettingsComponent() {
24030        return mInstantAppResolverSettingsComponent;
24031    }
24032
24033    @Override
24034    public ComponentName getInstantAppInstallerComponent() {
24035        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24036            return null;
24037        }
24038        return mInstantAppInstallerActivity == null
24039                ? null : mInstantAppInstallerActivity.getComponentName();
24040    }
24041
24042    @Override
24043    public String getInstantAppAndroidId(String packageName, int userId) {
24044        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24045                "getInstantAppAndroidId");
24046        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24047                true /* requireFullPermission */, false /* checkShell */,
24048                "getInstantAppAndroidId");
24049        // Make sure the target is an Instant App.
24050        if (!isInstantApp(packageName, userId)) {
24051            return null;
24052        }
24053        synchronized (mPackages) {
24054            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24055        }
24056    }
24057
24058    boolean canHaveOatDir(String packageName) {
24059        synchronized (mPackages) {
24060            PackageParser.Package p = mPackages.get(packageName);
24061            if (p == null) {
24062                return false;
24063            }
24064            return p.canHaveOatDir();
24065        }
24066    }
24067
24068    private String getOatDir(PackageParser.Package pkg) {
24069        if (!pkg.canHaveOatDir()) {
24070            return null;
24071        }
24072        File codePath = new File(pkg.codePath);
24073        if (codePath.isDirectory()) {
24074            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24075        }
24076        return null;
24077    }
24078
24079    void deleteOatArtifactsOfPackage(String packageName) {
24080        final String[] instructionSets;
24081        final List<String> codePaths;
24082        final String oatDir;
24083        final PackageParser.Package pkg;
24084        synchronized (mPackages) {
24085            pkg = mPackages.get(packageName);
24086        }
24087        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24088        codePaths = pkg.getAllCodePaths();
24089        oatDir = getOatDir(pkg);
24090
24091        for (String codePath : codePaths) {
24092            for (String isa : instructionSets) {
24093                try {
24094                    mInstaller.deleteOdex(codePath, isa, oatDir);
24095                } catch (InstallerException e) {
24096                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24097                }
24098            }
24099        }
24100    }
24101
24102    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24103        Set<String> unusedPackages = new HashSet<>();
24104        long currentTimeInMillis = System.currentTimeMillis();
24105        synchronized (mPackages) {
24106            for (PackageParser.Package pkg : mPackages.values()) {
24107                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24108                if (ps == null) {
24109                    continue;
24110                }
24111                PackageDexUsage.PackageUseInfo packageUseInfo =
24112                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24113                if (PackageManagerServiceUtils
24114                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24115                                downgradeTimeThresholdMillis, packageUseInfo,
24116                                pkg.getLatestPackageUseTimeInMills(),
24117                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24118                    unusedPackages.add(pkg.packageName);
24119                }
24120            }
24121        }
24122        return unusedPackages;
24123    }
24124
24125    @Override
24126    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24127            int userId) {
24128        final int callingUid = Binder.getCallingUid();
24129        final int callingAppId = UserHandle.getAppId(callingUid);
24130
24131        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24132                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24133
24134        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24135                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24136            throw new SecurityException("Caller must have the "
24137                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24138        }
24139
24140        synchronized(mPackages) {
24141            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24142            scheduleWritePackageRestrictionsLocked(userId);
24143        }
24144    }
24145
24146    @Nullable
24147    @Override
24148    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24149        final int callingUid = Binder.getCallingUid();
24150        final int callingAppId = UserHandle.getAppId(callingUid);
24151
24152        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24153                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24154
24155        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24156                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24157            throw new SecurityException("Caller must have the "
24158                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24159        }
24160
24161        synchronized(mPackages) {
24162            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24163        }
24164    }
24165}
24166
24167interface PackageSender {
24168    /**
24169     * @param userIds User IDs where the action occurred on a full application
24170     * @param instantUserIds User IDs where the action occurred on an instant application
24171     */
24172    void sendPackageBroadcast(final String action, final String pkg,
24173        final Bundle extras, final int flags, final String targetPkg,
24174        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24175    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24176        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24177    void notifyPackageAdded(String packageName);
24178    void notifyPackageRemoved(String packageName);
24179}
24180